Skip to content

Commit b941552

Browse files
Datasource - google_sql_database_instances (#6980) (#13433)
* Added validation for "type" in cloud_sql_user_resource for preventing user from setting "password" or "host" for CLOUD_IAM_USER and CLOUD_IAM_SERVICE_ACCOUNT user types. * Added new data_source_sql_database_instance_list data source and test file * Added new data_source_sql_database_instance_list data source and test file * Reverting validation of usert types, this would be added as a seperate PR * Added documentation for the new google_sql_database_instances data source * mend * mend * mend * mend * mend Signed-off-by: Modular Magician <[email protected]> Signed-off-by: Modular Magician <[email protected]>
1 parent 75800f9 commit b941552

5 files changed

+653
-0
lines changed

.changelog/6980.txt

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
```release-note:new-datasource
2+
`google_sql_database_instances`
3+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,193 @@
1+
package google
2+
3+
import (
4+
"fmt"
5+
"strings"
6+
7+
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
8+
sqladmin "google.golang.org/api/sqladmin/v1beta4"
9+
)
10+
11+
func dataSourceSqlDatabaseInstances() *schema.Resource {
12+
13+
return &schema.Resource{
14+
Read: dataSourceSqlDatabaseInstancesRead,
15+
16+
Schema: map[string]*schema.Schema{
17+
"project": {
18+
Type: schema.TypeString,
19+
Optional: true,
20+
Description: `Project ID of the project that contains the instances.`,
21+
},
22+
"database_version": {
23+
Type: schema.TypeString,
24+
Optional: true,
25+
Description: `To filter out the database instances which are of the specified database version.`,
26+
},
27+
"region": {
28+
Type: schema.TypeString,
29+
Optional: true,
30+
Description: `To filter out the database instances which are located in this specified region.`,
31+
},
32+
"zone": {
33+
Type: schema.TypeString,
34+
Optional: true,
35+
Description: `To filter out the database instances which are located in this specified zone.`,
36+
},
37+
"tier": {
38+
Type: schema.TypeString,
39+
Optional: true,
40+
Description: `To filter out the database instances based on the machine type.`,
41+
},
42+
"state": {
43+
Type: schema.TypeString,
44+
Optional: true,
45+
Description: `To filter out the database instances based on the current state of the database instance, valid values include : "SQL_INSTANCE_STATE_UNSPECIFIED", "RUNNABLE", "SUSPENDED", "PENDING_DELETE", "PENDING_CREATE", "MAINTENANCE" and "FAILED".`,
46+
},
47+
"instances": {
48+
Type: schema.TypeList,
49+
Computed: true,
50+
Elem: &schema.Resource{
51+
Schema: datasourceSchemaFromResourceSchema(resourceSqlDatabaseInstance().Schema),
52+
},
53+
},
54+
},
55+
}
56+
}
57+
58+
func dataSourceSqlDatabaseInstancesRead(d *schema.ResourceData, meta interface{}) error {
59+
config := meta.(*Config)
60+
userAgent, err := generateUserAgentString(d, config.userAgent)
61+
if err != nil {
62+
return err
63+
}
64+
project, err := getProject(d, config)
65+
if err != nil {
66+
return err
67+
}
68+
filter := ""
69+
70+
if v, ok := d.GetOk("database_version"); ok {
71+
filter += fmt.Sprintf("databaseVersion:%s", v.(string))
72+
}
73+
if v, ok := d.GetOk("region"); ok {
74+
if filter != "" {
75+
filter += " AND "
76+
}
77+
filter += fmt.Sprintf("region:%s", v.(string))
78+
}
79+
if v, ok := d.GetOk("zone"); ok {
80+
if filter != "" {
81+
filter += " AND "
82+
}
83+
filter += fmt.Sprintf("gceZone:%s", v.(string))
84+
}
85+
if v, ok := d.GetOk("tier"); ok {
86+
if filter != "" {
87+
filter += " AND "
88+
}
89+
filter += fmt.Sprintf("settings.tier:%s", v.(string))
90+
}
91+
if v, ok := d.GetOk("state"); ok {
92+
if filter != "" {
93+
filter += " AND "
94+
}
95+
filter += fmt.Sprintf("state:%s", v.(string))
96+
}
97+
pageToken := ""
98+
databaseInstances := make([]map[string]interface{}, 0)
99+
for {
100+
var instances *sqladmin.InstancesListResponse
101+
err = retryTimeDuration(func() (rerr error) {
102+
instances, rerr = config.NewSqlAdminClient(userAgent).Instances.List(project).Filter(filter).PageToken(pageToken).Do()
103+
return rerr
104+
}, d.Timeout(schema.TimeoutRead), isSqlOperationInProgressError)
105+
if err != nil {
106+
return err
107+
}
108+
109+
pageInstances := flattenDatasourceGoogleDatabaseInstancesList(instances.Items, project)
110+
databaseInstances = append(databaseInstances, pageInstances...)
111+
112+
pageToken = instances.NextPageToken
113+
if pageToken == "" {
114+
break
115+
}
116+
}
117+
118+
if err := d.Set("instances", databaseInstances); err != nil {
119+
return fmt.Errorf("Error retrieving instances: %s", err)
120+
}
121+
122+
d.SetId(fmt.Sprintf("database_instances_ds/%s/%s/%s/%s/%s/%s", project, d.Get("database_version").(string), d.Get("region").(string), d.Get("zone").(string), d.Get("tier").(string), d.Get("state").(string)))
123+
124+
return nil
125+
}
126+
127+
func flattenDatasourceGoogleDatabaseInstancesList(fetchedInstances []*sqladmin.DatabaseInstance, project string) []map[string]interface{} {
128+
if fetchedInstances == nil {
129+
return make([]map[string]interface{}, 0)
130+
}
131+
132+
instances := make([]map[string]interface{}, 0, len(fetchedInstances))
133+
for _, rawInstance := range fetchedInstances {
134+
instance := make(map[string]interface{})
135+
instance["name"] = rawInstance.Name
136+
instance["region"] = rawInstance.Region
137+
instance["database_version"] = rawInstance.DatabaseVersion
138+
instance["connection_name"] = rawInstance.ConnectionName
139+
instance["maintenance_version"] = rawInstance.MaintenanceVersion
140+
instance["available_maintenance_versions"] = rawInstance.AvailableMaintenanceVersions
141+
instance["service_account_email_address"] = rawInstance.ServiceAccountEmailAddress
142+
instance["settings"] = flattenSettings(rawInstance.Settings)
143+
144+
if rawInstance.DiskEncryptionConfiguration != nil {
145+
instance["encryption_key_name"] = rawInstance.DiskEncryptionConfiguration.KmsKeyName
146+
}
147+
148+
instance["replica_configuration"] = flattenReplicaConfigurationforDataSource(rawInstance.ReplicaConfiguration)
149+
150+
ipAddresses := flattenIpAddresses(rawInstance.IpAddresses)
151+
instance["ip_address"] = ipAddresses
152+
153+
if len(ipAddresses) > 0 {
154+
instance["first_ip_address"] = ipAddresses[0]["ip_address"]
155+
}
156+
157+
publicIpAddress := ""
158+
privateIpAddress := ""
159+
for _, ip := range rawInstance.IpAddresses {
160+
if publicIpAddress == "" && ip.Type == "PRIMARY" {
161+
publicIpAddress = ip.IpAddress
162+
}
163+
164+
if privateIpAddress == "" && ip.Type == "PRIVATE" {
165+
privateIpAddress = ip.IpAddress
166+
}
167+
}
168+
instance["public_ip_address"] = publicIpAddress
169+
instance["private_ip_address"] = privateIpAddress
170+
instance["server_ca_cert"] = flattenServerCaCerts([]*sqladmin.SslCert{rawInstance.ServerCaCert})
171+
instance["master_instance_name"] = strings.TrimPrefix(rawInstance.MasterInstanceName, project+":")
172+
instance["project"] = project
173+
instance["self_link"] = rawInstance.SelfLink
174+
175+
instances = append(instances, instance)
176+
}
177+
178+
return instances
179+
}
180+
func flattenReplicaConfigurationforDataSource(replicaConfiguration *sqladmin.ReplicaConfiguration) []map[string]interface{} {
181+
rc := []map[string]interface{}{}
182+
183+
if replicaConfiguration != nil {
184+
data := map[string]interface{}{
185+
"failover_target": replicaConfiguration.FailoverTarget,
186+
// Don't attempt to assign anything from replicaConfiguration.MysqlReplicaConfiguration,
187+
// since those fields are set on create and then not stored. Hence, those fields are not shown.
188+
}
189+
rc = append(rc, data)
190+
}
191+
192+
return rc
193+
}

0 commit comments

Comments
 (0)