Skip to content

Commit ac0ee30

Browse files
Added a new datasource for fetching the available alloydb locations (#7678) (#14355)
* 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. * Removed validation and added documentation to prevent setting of host or password field for CLOUD_IAM_USER and CLOUD_IAM_SERVICE_ACCOUNT * Added a new data source for fetching the details of available alloydb locations * using go client libraries to call the apis * using go client library to call the apis * using go client library to call the apis * Using v1 and v1beta go client for ga and beta versions respectively * Using v1 and v1beta go client for ga and beta versions respectively * Revert "Added a new data source for fetching the details of available alloydb locations" This reverts commit a6791a3a1c4ae327d7271081141bb2e0ff1b37ff. * calling http calls using magic modules send request insted of alloydb go client * calling http calls using magic modules send request insted of alloydb go client Signed-off-by: Modular Magician <[email protected]>
1 parent ef80543 commit ac0ee30

File tree

5 files changed

+255
-0
lines changed

5 files changed

+255
-0
lines changed

.changelog/7678.txt

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
```release-note:new-datasource
2+
`google_alloydb_locations`
3+
```
+140
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
package google
2+
3+
import (
4+
"fmt"
5+
6+
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
7+
)
8+
9+
func DataSourceAlloydbLocations() *schema.Resource {
10+
11+
return &schema.Resource{
12+
Read: dataSourceAlloydbLocationsRead,
13+
14+
Schema: map[string]*schema.Schema{
15+
"project": {
16+
Type: schema.TypeString,
17+
Optional: true,
18+
Description: `Project ID of the project.`,
19+
},
20+
"locations": {
21+
Type: schema.TypeList,
22+
Computed: true,
23+
Elem: &schema.Resource{
24+
Schema: map[string]*schema.Schema{
25+
"name": {
26+
Type: schema.TypeString,
27+
Computed: true,
28+
Optional: true,
29+
Description: `Resource name for the location, which may vary between implementations. For example: "projects/example-project/locations/us-east1`,
30+
},
31+
"location_id": {
32+
Type: schema.TypeString,
33+
Computed: true,
34+
Optional: true,
35+
Description: `The canonical id for this location. For example: "us-east1".`,
36+
},
37+
"display_name": {
38+
Type: schema.TypeString,
39+
Computed: true,
40+
Optional: true,
41+
Description: `The friendly name for this location, typically a nearby city name. For example, "Tokyo".`,
42+
},
43+
"labels": {
44+
Type: schema.TypeMap,
45+
Computed: true,
46+
Optional: true,
47+
Description: `Cross-service attributes for the location. For example {"cloud.googleapis.com/region": "us-east1"}`,
48+
Elem: &schema.Schema{Type: schema.TypeString},
49+
},
50+
"metadata": {
51+
Type: schema.TypeMap,
52+
Computed: true,
53+
Optional: true,
54+
Description: `Service-specific metadata. For example the available capacity at the given location.`,
55+
Elem: &schema.Schema{Type: schema.TypeString},
56+
},
57+
},
58+
},
59+
},
60+
},
61+
}
62+
}
63+
64+
func dataSourceAlloydbLocationsRead(d *schema.ResourceData, meta interface{}) error {
65+
config := meta.(*Config)
66+
userAgent, err := generateUserAgentString(d, config.UserAgent)
67+
if err != nil {
68+
return err
69+
}
70+
billingProject := ""
71+
72+
project, err := getProject(d, config)
73+
if err != nil {
74+
return fmt.Errorf("Error fetching project: %s", err)
75+
}
76+
billingProject = project
77+
78+
// err == nil indicates that the billing_project value was found
79+
if bp, err := getBillingProject(d, config); err == nil {
80+
billingProject = bp
81+
}
82+
83+
url, err := ReplaceVars(d, config, "{{AlloydbBasePath}}projects/{{project}}/locations")
84+
if err != nil {
85+
return fmt.Errorf("Error setting api endpoint")
86+
}
87+
res, err := SendRequest(config, "GET", billingProject, url, userAgent, nil)
88+
if err != nil {
89+
return handleNotFoundError(err, d, fmt.Sprintf("Locations %q", d.Id()))
90+
}
91+
var locations []map[string]interface{}
92+
for {
93+
fetchedLocations := res["locations"].([]interface{})
94+
for _, loc := range fetchedLocations {
95+
locationDetails := make(map[string]interface{})
96+
l := loc.(map[string]interface{})
97+
if l["name"] != nil {
98+
locationDetails["name"] = l["name"].(string)
99+
}
100+
if l["locationId"] != nil {
101+
locationDetails["location_id"] = l["locationId"].(string)
102+
}
103+
if l["displayName"] != nil {
104+
locationDetails["display_id"] = l["displayName"].(string)
105+
}
106+
if l["labels"] != nil {
107+
labels := make(map[string]string)
108+
for k, v := range l["labels"].(map[string]interface{}) {
109+
labels[k] = v.(string)
110+
}
111+
locationDetails["labels"] = labels
112+
}
113+
if l["metadata"] != nil {
114+
metadata := make(map[string]string)
115+
for k, v := range l["metadata"].(map[interface{}]interface{}) {
116+
metadata[k.(string)] = v.(string)
117+
}
118+
locationDetails["metadata"] = metadata
119+
}
120+
locations = append(locations, locationDetails)
121+
}
122+
if res["nextPageToken"] == nil || res["nextPageToken"].(string) == "" {
123+
break
124+
}
125+
url, err = ReplaceVars(d, config, "{{AlloydbBasePath}}projects/{{project}}/locations?pageToken="+res["nextPageToken"].(string))
126+
if err != nil {
127+
return fmt.Errorf("Error setting api endpoint")
128+
}
129+
res, err = SendRequest(config, "GET", billingProject, url, userAgent, nil)
130+
if err != nil {
131+
return handleNotFoundError(err, d, fmt.Sprintf("Locations %q", d.Id()))
132+
}
133+
}
134+
135+
if err := d.Set("locations", locations); err != nil {
136+
return fmt.Errorf("Error setting locations: %s", err)
137+
}
138+
d.SetId(fmt.Sprintf("projects/%s/locations", project))
139+
return nil
140+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package google
2+
3+
import (
4+
"errors"
5+
"fmt"
6+
"strconv"
7+
"testing"
8+
9+
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
10+
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
11+
)
12+
13+
func TestAccDataSourceAlloydbLocations_basic(t *testing.T) {
14+
t.Parallel()
15+
16+
context := map[string]interface{}{
17+
"random_suffix": RandString(t, 10),
18+
}
19+
20+
VcrTest(t, resource.TestCase{
21+
PreCheck: func() { AccTestPreCheck(t) },
22+
Providers: TestAccProviders,
23+
CheckDestroy: testAccSqlDatabaseDestroyProducer(t),
24+
Steps: []resource.TestStep{
25+
{
26+
Config: testAccDataSourceAlloydbLocations_basic(context),
27+
Check: resource.ComposeTestCheckFunc(
28+
validateAlloydbLocationsResult(
29+
"data.google_alloydb_locations.qa",
30+
),
31+
),
32+
},
33+
},
34+
})
35+
}
36+
37+
func testAccDataSourceAlloydbLocations_basic(context map[string]interface{}) string {
38+
return Nprintf(`
39+
data "google_alloydb_locations" "qa" {
40+
}
41+
`, context)
42+
}
43+
44+
func validateAlloydbLocationsResult(dataSourceName string) func(*terraform.State) error {
45+
return func(s *terraform.State) error {
46+
ds, ok := s.RootModule().Resources[dataSourceName]
47+
if !ok {
48+
return fmt.Errorf("can't find %s in state", dataSourceName)
49+
}
50+
var dsAttr map[string]string
51+
dsAttr = ds.Primary.Attributes
52+
53+
totalFlags, err := strconv.Atoi(dsAttr["locations.#"])
54+
if err != nil {
55+
return errors.New("Couldn't convert length of flags list to integer")
56+
}
57+
if totalFlags == 0 {
58+
return errors.New("No locations are fetched")
59+
}
60+
for i := 0; i < totalFlags; i++ {
61+
if dsAttr["locations."+strconv.Itoa(i)+".name"] == "" {
62+
return errors.New("name parameter is not set for the location")
63+
}
64+
if dsAttr["locations."+strconv.Itoa(i)+".location_id"] == "" {
65+
return errors.New("location_id parameter is not set for the location")
66+
}
67+
}
68+
return nil
69+
}
70+
}

google/provider.go

+1
Original file line numberDiff line numberDiff line change
@@ -577,6 +577,7 @@ func Provider() *schema.Provider {
577577
"google_access_approval_organization_service_account": DataSourceAccessApprovalOrganizationServiceAccount(),
578578
"google_access_approval_project_service_account": DataSourceAccessApprovalProjectServiceAccount(),
579579
"google_active_folder": DataSourceGoogleActiveFolder(),
580+
"google_alloydb_locations": DataSourceAlloydbLocations(),
580581
"google_artifact_registry_repository": DataSourceArtifactRegistryRepository(),
581582
"google_app_engine_default_service_account": DataSourceGoogleAppEngineDefaultServiceAccount(),
582583
"google_beyondcorp_app_connection": DataSourceGoogleBeyondcorpAppConnection(),
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
---
2+
subcategory: "Alloydb"
3+
description: |-
4+
Fetches the details of available locations.
5+
---
6+
7+
# google\_alloydb\_locations
8+
9+
Use this data source to get information about the available locations. For more details refer the [API docs](https://cloud.google.com/alloydb/docs/reference/rest/v1/projects.locations).
10+
11+
## Example Usage
12+
13+
14+
```hcl
15+
data "google_alloydb_locations" "qa" {
16+
}
17+
```
18+
19+
## Argument Reference
20+
21+
The following arguments are supported:
22+
23+
* `project` - (optional) The ID of the project.
24+
25+
## Attributes Reference
26+
27+
In addition to the arguments listed above, the following computed attributes are exported:
28+
29+
* `locations` - Contains a list of `location`, which contains the details about a particular location.
30+
31+
A `location` object would contain the following fields:-
32+
33+
* `name` - Resource name for the location, which may vary between implementations. For example: "projects/example-project/locations/us-east1".
34+
35+
* `location_id` - The canonical id for this location. For example: "us-east1"..
36+
37+
* `display_name` - The friendly name for this location, typically a nearby city name. For example, "Tokyo".
38+
39+
* `labels` - Cross-service attributes for the location. For example `{"cloud.googleapis.com/region": "us-east1"}`.
40+
41+
* `metadata` - Service-specific metadata. For example the available capacity at the given location.

0 commit comments

Comments
 (0)