github.com/minamijoyo/terraform@v0.7.8-0.20161029001309-18b3736ba44b/builtin/providers/aws/data_source_aws_availability_zone.go (about)

     1  package aws
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  
     7  	"github.com/aws/aws-sdk-go/aws"
     8  	"github.com/aws/aws-sdk-go/service/ec2"
     9  	"github.com/hashicorp/terraform/helper/schema"
    10  )
    11  
    12  func dataSourceAwsAvailabilityZone() *schema.Resource {
    13  	return &schema.Resource{
    14  		Read: dataSourceAwsAvailabilityZoneRead,
    15  
    16  		Schema: map[string]*schema.Schema{
    17  			"name": &schema.Schema{
    18  				Type:     schema.TypeString,
    19  				Optional: true,
    20  				Computed: true,
    21  			},
    22  
    23  			"region": &schema.Schema{
    24  				Type:     schema.TypeString,
    25  				Computed: true,
    26  			},
    27  
    28  			"name_suffix": &schema.Schema{
    29  				Type:     schema.TypeString,
    30  				Computed: true,
    31  			},
    32  
    33  			"state": &schema.Schema{
    34  				Type:     schema.TypeString,
    35  				Optional: true,
    36  				Computed: true,
    37  			},
    38  		},
    39  	}
    40  }
    41  
    42  func dataSourceAwsAvailabilityZoneRead(d *schema.ResourceData, meta interface{}) error {
    43  	conn := meta.(*AWSClient).ec2conn
    44  
    45  	req := &ec2.DescribeAvailabilityZonesInput{}
    46  
    47  	if name := d.Get("name"); name != "" {
    48  		req.ZoneNames = []*string{aws.String(name.(string))}
    49  	}
    50  
    51  	req.Filters = buildEC2AttributeFilterList(
    52  		map[string]string{
    53  			"state": d.Get("state").(string),
    54  		},
    55  	)
    56  	if len(req.Filters) == 0 {
    57  		// Don't send an empty filters list; the EC2 API won't accept it.
    58  		req.Filters = nil
    59  	}
    60  
    61  	log.Printf("[DEBUG] DescribeAvailabilityZones %s\n", req)
    62  	resp, err := conn.DescribeAvailabilityZones(req)
    63  	if err != nil {
    64  		return err
    65  	}
    66  	if resp == nil || len(resp.AvailabilityZones) == 0 {
    67  		return fmt.Errorf("no matching AZ found")
    68  	}
    69  	if len(resp.AvailabilityZones) > 1 {
    70  		return fmt.Errorf("multiple AZs matched; use additional constraints to reduce matches to a single AZ")
    71  	}
    72  
    73  	az := resp.AvailabilityZones[0]
    74  
    75  	// As a convenience when working with AZs generically, we expose
    76  	// the AZ suffix alone, without the region name.
    77  	// This can be used e.g. to create lookup tables by AZ letter that
    78  	// work regardless of region.
    79  	nameSuffix := (*az.ZoneName)[len(*az.RegionName):]
    80  
    81  	d.SetId(*az.ZoneName)
    82  	d.Set("id", az.ZoneName)
    83  	d.Set("name", az.ZoneName)
    84  	d.Set("name_suffix", nameSuffix)
    85  	d.Set("region", az.RegionName)
    86  	d.Set("state", az.State)
    87  
    88  	return nil
    89  }