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

     1  package aws
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  
     7  	"github.com/aws/aws-sdk-go/service/ec2"
     8  	"github.com/hashicorp/terraform/helper/schema"
     9  )
    10  
    11  func dataSourceAwsSubnetIDs() *schema.Resource {
    12  	return &schema.Resource{
    13  		Read: dataSourceAwsSubnetIDsRead,
    14  		Schema: map[string]*schema.Schema{
    15  
    16  			"tags": tagsSchemaComputed(),
    17  
    18  			"vpc_id": &schema.Schema{
    19  				Type:     schema.TypeString,
    20  				Required: true,
    21  			},
    22  
    23  			"ids": &schema.Schema{
    24  				Type:     schema.TypeSet,
    25  				Computed: true,
    26  				Elem:     &schema.Schema{Type: schema.TypeString},
    27  				Set:      schema.HashString,
    28  			},
    29  		},
    30  	}
    31  }
    32  
    33  func dataSourceAwsSubnetIDsRead(d *schema.ResourceData, meta interface{}) error {
    34  	conn := meta.(*AWSClient).ec2conn
    35  
    36  	req := &ec2.DescribeSubnetsInput{}
    37  
    38  	req.Filters = buildEC2AttributeFilterList(
    39  		map[string]string{
    40  			"vpc-id": d.Get("vpc_id").(string),
    41  		},
    42  	)
    43  
    44  	req.Filters = append(req.Filters, buildEC2TagFilterList(
    45  		tagsFromMap(d.Get("tags").(map[string]interface{})),
    46  	)...)
    47  
    48  	log.Printf("[DEBUG] DescribeSubnets %s\n", req)
    49  	resp, err := conn.DescribeSubnets(req)
    50  	if err != nil {
    51  		return err
    52  	}
    53  
    54  	if resp == nil || len(resp.Subnets) == 0 {
    55  		return fmt.Errorf("no matching subnet found for vpc with id %s", d.Get("vpc_id").(string))
    56  	}
    57  
    58  	subnets := make([]string, 0)
    59  
    60  	for _, subnet := range resp.Subnets {
    61  		subnets = append(subnets, *subnet.SubnetId)
    62  	}
    63  
    64  	d.SetId(d.Get("vpc_id").(string))
    65  	d.Set("ids", subnets)
    66  
    67  	return nil
    68  }