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