github.com/danp/terraform@v0.9.5-0.20170426144147-39d740081351/builtin/providers/aws/data_source_aws_eip.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 dataSourceAwsEip() *schema.Resource {
    13  	return &schema.Resource{
    14  		Read: dataSourceAwsEipRead,
    15  
    16  		Schema: map[string]*schema.Schema{
    17  			"id": &schema.Schema{
    18  				Type:     schema.TypeString,
    19  				Optional: true,
    20  				Computed: true,
    21  			},
    22  
    23  			"public_ip": &schema.Schema{
    24  				Type:     schema.TypeString,
    25  				Optional: true,
    26  				Computed: true,
    27  			},
    28  		},
    29  	}
    30  }
    31  
    32  func dataSourceAwsEipRead(d *schema.ResourceData, meta interface{}) error {
    33  	conn := meta.(*AWSClient).ec2conn
    34  
    35  	req := &ec2.DescribeAddressesInput{}
    36  
    37  	if id := d.Get("id"); id != "" {
    38  		req.AllocationIds = []*string{aws.String(id.(string))}
    39  	}
    40  
    41  	if public_ip := d.Get("public_ip"); public_ip != "" {
    42  		req.PublicIps = []*string{aws.String(public_ip.(string))}
    43  	}
    44  
    45  	log.Printf("[DEBUG] DescribeAddresses %s\n", req)
    46  	resp, err := conn.DescribeAddresses(req)
    47  	if err != nil {
    48  		return err
    49  	}
    50  	if resp == nil || len(resp.Addresses) == 0 {
    51  		return fmt.Errorf("no matching Elastic IP found")
    52  	}
    53  	if len(resp.Addresses) > 1 {
    54  		return fmt.Errorf("multiple Elastic IPs matched; use additional constraints to reduce matches to a single Elastic IP")
    55  	}
    56  
    57  	eip := resp.Addresses[0]
    58  
    59  	d.SetId(*eip.AllocationId)
    60  	d.Set("id", eip.AllocationId)
    61  	d.Set("public_ip", eip.PublicIp)
    62  
    63  	return nil
    64  }