github.com/mohanarpit/terraform@v0.6.16-0.20160909104007-291f29853544/builtin/providers/aws/data_source_availability_zones.go (about)

     1  package aws
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"sort"
     7  	"time"
     8  
     9  	"github.com/aws/aws-sdk-go/aws"
    10  	"github.com/aws/aws-sdk-go/service/ec2"
    11  	"github.com/hashicorp/terraform/helper/schema"
    12  )
    13  
    14  func dataSourceAwsAvailabilityZones() *schema.Resource {
    15  	return &schema.Resource{
    16  		Read: dataSourceAwsAvailabilityZonesRead,
    17  
    18  		Schema: map[string]*schema.Schema{
    19  			"names": &schema.Schema{
    20  				Type:     schema.TypeList,
    21  				Computed: true,
    22  				Elem:     &schema.Schema{Type: schema.TypeString},
    23  			},
    24  			"state": &schema.Schema{
    25  				Type:         schema.TypeString,
    26  				Optional:     true,
    27  				ValidateFunc: validateStateType,
    28  			},
    29  		},
    30  	}
    31  }
    32  
    33  func dataSourceAwsAvailabilityZonesRead(d *schema.ResourceData, meta interface{}) error {
    34  	conn := meta.(*AWSClient).ec2conn
    35  
    36  	log.Printf("[DEBUG] Reading Availability Zones.")
    37  	d.SetId(time.Now().UTC().String())
    38  
    39  	request := &ec2.DescribeAvailabilityZonesInput{}
    40  
    41  	if v, ok := d.GetOk("state"); ok {
    42  		request.Filters = []*ec2.Filter{
    43  			&ec2.Filter{
    44  				Name:   aws.String("state"),
    45  				Values: []*string{aws.String(v.(string))},
    46  			},
    47  		}
    48  	}
    49  
    50  	log.Printf("[DEBUG] Availability Zones request options: %#v", *request)
    51  
    52  	resp, err := conn.DescribeAvailabilityZones(request)
    53  	if err != nil {
    54  		return fmt.Errorf("Error fetching Availability Zones: %s", err)
    55  	}
    56  
    57  	raw := make([]string, len(resp.AvailabilityZones))
    58  	for i, v := range resp.AvailabilityZones {
    59  		raw[i] = *v.ZoneName
    60  	}
    61  
    62  	sort.Strings(raw)
    63  
    64  	if err := d.Set("names", raw); err != nil {
    65  		return fmt.Errorf("[WARN] Error setting Availability Zones: %s", err)
    66  	}
    67  
    68  	return nil
    69  }
    70  
    71  func validateStateType(v interface{}, k string) (ws []string, errors []error) {
    72  	value := v.(string)
    73  
    74  	validState := map[string]bool{
    75  		"available":   true,
    76  		"information": true,
    77  		"impaired":    true,
    78  		"unavailable": true,
    79  	}
    80  
    81  	if !validState[value] {
    82  		errors = append(errors, fmt.Errorf(
    83  			"%q contains an invalid Availability Zone state %q. Valid states are: %q, %q, %q and %q.",
    84  			k, value, "available", "information", "impaired", "unavailable"))
    85  	}
    86  	return
    87  }