github.com/danp/terraform@v0.9.5-0.20170426144147-39d740081351/builtin/providers/google/data_source_google_compute_zones.go (about)

     1  package google
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"sort"
     7  	"time"
     8  
     9  	"github.com/hashicorp/terraform/helper/schema"
    10  	compute "google.golang.org/api/compute/v1"
    11  )
    12  
    13  func dataSourceGoogleComputeZones() *schema.Resource {
    14  	return &schema.Resource{
    15  		Read: dataSourceGoogleComputeZonesRead,
    16  		Schema: map[string]*schema.Schema{
    17  			"region": {
    18  				Type:     schema.TypeString,
    19  				Optional: true,
    20  			},
    21  			"names": {
    22  				Type:     schema.TypeList,
    23  				Computed: true,
    24  				Elem:     &schema.Schema{Type: schema.TypeString},
    25  			},
    26  			"status": {
    27  				Type:     schema.TypeString,
    28  				Optional: true,
    29  				ValidateFunc: func(v interface{}, k string) (ws []string, es []error) {
    30  					value := v.(string)
    31  					if value != "UP" && value != "DOWN" {
    32  						es = append(es, fmt.Errorf("%q can only be 'UP' or 'DOWN' (%q given)", k, value))
    33  					}
    34  					return
    35  				},
    36  			},
    37  		},
    38  	}
    39  }
    40  
    41  func dataSourceGoogleComputeZonesRead(d *schema.ResourceData, meta interface{}) error {
    42  	config := meta.(*Config)
    43  
    44  	region := config.Region
    45  	if r, ok := d.GetOk("region"); ok {
    46  		region = r.(string)
    47  	}
    48  
    49  	regionUrl := fmt.Sprintf("https://www.googleapis.com/compute/v1/projects/%s/regions/%s",
    50  		config.Project, region)
    51  	filter := fmt.Sprintf("(region eq %s)", regionUrl)
    52  
    53  	if s, ok := d.GetOk("status"); ok {
    54  		filter += fmt.Sprintf(" (status eq %s)", s)
    55  	}
    56  
    57  	call := config.clientCompute.Zones.List(config.Project).Filter(filter)
    58  
    59  	resp, err := call.Do()
    60  	if err != nil {
    61  		return err
    62  	}
    63  
    64  	zones := flattenZones(resp.Items)
    65  	log.Printf("[DEBUG] Received Google Compute Zones: %q", zones)
    66  
    67  	d.Set("names", zones)
    68  	d.SetId(time.Now().UTC().String())
    69  
    70  	return nil
    71  }
    72  
    73  func flattenZones(zones []*compute.Zone) []string {
    74  	result := make([]string, len(zones), len(zones))
    75  	for i, zone := range zones {
    76  		result[i] = zone.Name
    77  	}
    78  	sort.Strings(result)
    79  	return result
    80  }