/
data_source_cloud_run_locations.go
81 lines (67 loc) · 1.91 KB
/
data_source_cloud_run_locations.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package google
import (
"fmt"
"log"
"sort"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func dataSourceGoogleCloudRunLocations() *schema.Resource {
return &schema.Resource{
Read: dataSourceGoogleCloudRunLocationsRead,
Schema: map[string]*schema.Schema{
"project": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"locations": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
}
}
func dataSourceGoogleCloudRunLocationsRead(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
userAgent, err := generateUserAgentString(d, config.userAgent)
if err != nil {
return err
}
project, err := getProject(d, config)
if err != nil {
return err
}
url, err := replaceVars(d, config, "https://run.googleapis.com/v1/projects/{{project}}/locations")
if err != nil {
return err
}
res, err := sendRequest(config, "GET", project, url, userAgent, nil)
if err != nil {
return fmt.Errorf("Error listing Cloud Run Locations : %s", err)
}
locationsRaw := flattenCloudRunLocations(res)
locations := make([]string, len(locationsRaw))
for i, loc := range locationsRaw {
locations[i] = loc.(string)
}
sort.Strings(locations)
log.Printf("[DEBUG] Received Google Cloud Run Locations: %q", locations)
if err := d.Set("project", project); err != nil {
return fmt.Errorf("Error setting project: %s", err)
}
if err := d.Set("locations", locations); err != nil {
return fmt.Errorf("Error setting location: %s", err)
}
d.SetId(fmt.Sprintf("projects/%s", project))
return nil
}
func flattenCloudRunLocations(resp map[string]interface{}) []interface{} {
regionList := resp["locations"].([]interface{})
regions := make([]interface{}, len(regionList))
for i, v := range regionList {
regionObj := v.(map[string]interface{})
regions[i] = regionObj["locationId"]
}
return regions
}