github.com/nathanielks/terraform@v0.6.1-0.20170509030759-13e1a62319dc/builtin/providers/aws/data_source_aws_prefix_list.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 dataSourceAwsPrefixList() *schema.Resource {
    13  	return &schema.Resource{
    14  		Read: dataSourceAwsPrefixListRead,
    15  
    16  		Schema: map[string]*schema.Schema{
    17  			"prefix_list_id": &schema.Schema{
    18  				Type:     schema.TypeString,
    19  				Optional: true,
    20  			},
    21  			"name": &schema.Schema{
    22  				Type:     schema.TypeString,
    23  				Optional: true,
    24  				Computed: true,
    25  			},
    26  			// Computed values.
    27  			"id": &schema.Schema{
    28  				Type:     schema.TypeString,
    29  				Computed: true,
    30  			},
    31  			"cidr_blocks": &schema.Schema{
    32  				Type:     schema.TypeList,
    33  				Computed: true,
    34  				Elem:     &schema.Schema{Type: schema.TypeString},
    35  			},
    36  		},
    37  	}
    38  }
    39  
    40  func dataSourceAwsPrefixListRead(d *schema.ResourceData, meta interface{}) error {
    41  	conn := meta.(*AWSClient).ec2conn
    42  
    43  	req := &ec2.DescribePrefixListsInput{}
    44  
    45  	if prefixListID := d.Get("prefix_list_id"); prefixListID != "" {
    46  		req.PrefixListIds = aws.StringSlice([]string{prefixListID.(string)})
    47  	}
    48  	req.Filters = buildEC2AttributeFilterList(
    49  		map[string]string{
    50  			"prefix-list-name": d.Get("name").(string),
    51  		},
    52  	)
    53  
    54  	log.Printf("[DEBUG] DescribePrefixLists %s\n", req)
    55  	resp, err := conn.DescribePrefixLists(req)
    56  	if err != nil {
    57  		return err
    58  	}
    59  	if resp == nil || len(resp.PrefixLists) == 0 {
    60  		return fmt.Errorf("no matching prefix list found; the prefix list ID or name may be invalid or not exist in the current region")
    61  	}
    62  
    63  	pl := resp.PrefixLists[0]
    64  
    65  	d.SetId(*pl.PrefixListId)
    66  	d.Set("id", pl.PrefixListId)
    67  	d.Set("name", pl.PrefixListName)
    68  
    69  	cidrs := make([]string, len(pl.Cidrs))
    70  	for i, v := range pl.Cidrs {
    71  		cidrs[i] = *v
    72  	}
    73  	d.Set("cidr_blocks", cidrs)
    74  
    75  	return nil
    76  }