github.com/erriapo/terraform@v0.6.12-0.20160203182612-0340ea72354f/builtin/providers/aws/resource_aws_eip.go (about)

     1  package aws
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"strings"
     7  	"time"
     8  
     9  	"github.com/aws/aws-sdk-go/aws"
    10  	"github.com/aws/aws-sdk-go/aws/awserr"
    11  	"github.com/aws/aws-sdk-go/service/ec2"
    12  	"github.com/hashicorp/terraform/helper/resource"
    13  	"github.com/hashicorp/terraform/helper/schema"
    14  )
    15  
    16  func resourceAwsEip() *schema.Resource {
    17  	return &schema.Resource{
    18  		Create: resourceAwsEipCreate,
    19  		Read:   resourceAwsEipRead,
    20  		Update: resourceAwsEipUpdate,
    21  		Delete: resourceAwsEipDelete,
    22  
    23  		Schema: map[string]*schema.Schema{
    24  			"vpc": &schema.Schema{
    25  				Type:     schema.TypeBool,
    26  				Optional: true,
    27  				ForceNew: true,
    28  			},
    29  
    30  			"instance": &schema.Schema{
    31  				Type:     schema.TypeString,
    32  				Optional: true,
    33  				Computed: true,
    34  			},
    35  
    36  			"network_interface": &schema.Schema{
    37  				Type:     schema.TypeString,
    38  				Optional: true,
    39  				Computed: true,
    40  			},
    41  
    42  			"allocation_id": &schema.Schema{
    43  				Type:     schema.TypeString,
    44  				Computed: true,
    45  			},
    46  
    47  			"association_id": &schema.Schema{
    48  				Type:     schema.TypeString,
    49  				Computed: true,
    50  			},
    51  
    52  			"domain": &schema.Schema{
    53  				Type:     schema.TypeString,
    54  				Computed: true,
    55  			},
    56  
    57  			"public_ip": &schema.Schema{
    58  				Type:     schema.TypeString,
    59  				Computed: true,
    60  			},
    61  
    62  			"private_ip": &schema.Schema{
    63  				Type:     schema.TypeString,
    64  				Computed: true,
    65  			},
    66  		},
    67  	}
    68  }
    69  
    70  func resourceAwsEipCreate(d *schema.ResourceData, meta interface{}) error {
    71  	ec2conn := meta.(*AWSClient).ec2conn
    72  
    73  	// By default, we're not in a VPC
    74  	domainOpt := ""
    75  	if v := d.Get("vpc"); v != nil && v.(bool) {
    76  		domainOpt = "vpc"
    77  	}
    78  
    79  	allocOpts := &ec2.AllocateAddressInput{
    80  		Domain: aws.String(domainOpt),
    81  	}
    82  
    83  	log.Printf("[DEBUG] EIP create configuration: %#v", allocOpts)
    84  	allocResp, err := ec2conn.AllocateAddress(allocOpts)
    85  	if err != nil {
    86  		return fmt.Errorf("Error creating EIP: %s", err)
    87  	}
    88  
    89  	// The domain tells us if we're in a VPC or not
    90  	d.Set("domain", allocResp.Domain)
    91  
    92  	// Assign the eips (unique) allocation id for use later
    93  	// the EIP api has a conditional unique ID (really), so
    94  	// if we're in a VPC we need to save the ID as such, otherwise
    95  	// it defaults to using the public IP
    96  	log.Printf("[DEBUG] EIP Allocate: %#v", allocResp)
    97  	if d.Get("domain").(string) == "vpc" {
    98  		d.SetId(*allocResp.AllocationId)
    99  	} else {
   100  		d.SetId(*allocResp.PublicIp)
   101  	}
   102  
   103  	log.Printf("[INFO] EIP ID: %s (domain: %v)", d.Id(), *allocResp.Domain)
   104  	return resourceAwsEipUpdate(d, meta)
   105  }
   106  
   107  func resourceAwsEipRead(d *schema.ResourceData, meta interface{}) error {
   108  	ec2conn := meta.(*AWSClient).ec2conn
   109  
   110  	domain := resourceAwsEipDomain(d)
   111  	id := d.Id()
   112  
   113  	req := &ec2.DescribeAddressesInput{}
   114  
   115  	if domain == "vpc" {
   116  		req.AllocationIds = []*string{aws.String(id)}
   117  	} else {
   118  		req.PublicIps = []*string{aws.String(id)}
   119  	}
   120  
   121  	log.Printf(
   122  		"[DEBUG] EIP describe configuration: %#v (domain: %s)",
   123  		req, domain)
   124  
   125  	describeAddresses, err := ec2conn.DescribeAddresses(req)
   126  	if err != nil {
   127  		if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidAllocationID.NotFound" {
   128  			d.SetId("")
   129  			return nil
   130  		}
   131  
   132  		return fmt.Errorf("Error retrieving EIP: %s", err)
   133  	}
   134  
   135  	// Verify AWS returned our EIP
   136  	if len(describeAddresses.Addresses) != 1 ||
   137  		domain == "vpc" && *describeAddresses.Addresses[0].AllocationId != id ||
   138  		*describeAddresses.Addresses[0].PublicIp != id {
   139  		if err != nil {
   140  			return fmt.Errorf("Unable to find EIP: %#v", describeAddresses.Addresses)
   141  		}
   142  	}
   143  
   144  	address := describeAddresses.Addresses[0]
   145  
   146  	d.Set("association_id", address.AssociationId)
   147  	if address.InstanceId != nil {
   148  		d.Set("instance", address.InstanceId)
   149  	} else {
   150  		d.Set("instance", "")
   151  	}
   152  	if address.NetworkInterfaceId != nil {
   153  		d.Set("network_interface", address.NetworkInterfaceId)
   154  	} else {
   155  		d.Set("network_interface", "")
   156  	}
   157  	d.Set("private_ip", address.PrivateIpAddress)
   158  	d.Set("public_ip", address.PublicIp)
   159  
   160  	return nil
   161  }
   162  
   163  func resourceAwsEipUpdate(d *schema.ResourceData, meta interface{}) error {
   164  	ec2conn := meta.(*AWSClient).ec2conn
   165  
   166  	domain := resourceAwsEipDomain(d)
   167  
   168  	// Associate to instance or interface if specified
   169  	v_instance, ok_instance := d.GetOk("instance")
   170  	v_interface, ok_interface := d.GetOk("network_interface")
   171  
   172  	if ok_instance || ok_interface {
   173  		instanceId := v_instance.(string)
   174  		networkInterfaceId := v_interface.(string)
   175  
   176  		assocOpts := &ec2.AssociateAddressInput{
   177  			InstanceId: aws.String(instanceId),
   178  			PublicIp:   aws.String(d.Id()),
   179  		}
   180  
   181  		// more unique ID conditionals
   182  		if domain == "vpc" {
   183  			assocOpts = &ec2.AssociateAddressInput{
   184  				NetworkInterfaceId: aws.String(networkInterfaceId),
   185  				InstanceId:         aws.String(instanceId),
   186  				AllocationId:       aws.String(d.Id()),
   187  			}
   188  		}
   189  
   190  		log.Printf("[DEBUG] EIP associate configuration: %#v (domain: %v)", assocOpts, domain)
   191  		_, err := ec2conn.AssociateAddress(assocOpts)
   192  		if err != nil {
   193  			// Prevent saving instance if association failed
   194  			// e.g. missing internet gateway in VPC
   195  			d.Set("instance", "")
   196  			d.Set("network_interface", "")
   197  			return fmt.Errorf("Failure associating EIP: %s", err)
   198  		}
   199  	}
   200  
   201  	return resourceAwsEipRead(d, meta)
   202  }
   203  
   204  func resourceAwsEipDelete(d *schema.ResourceData, meta interface{}) error {
   205  	ec2conn := meta.(*AWSClient).ec2conn
   206  
   207  	if err := resourceAwsEipRead(d, meta); err != nil {
   208  		return err
   209  	}
   210  	if d.Id() == "" {
   211  		// This might happen from the read
   212  		return nil
   213  	}
   214  
   215  	// If we are attached to an instance or interface, detach first.
   216  	if d.Get("instance").(string) != "" || d.Get("association_id").(string) != "" {
   217  		log.Printf("[DEBUG] Disassociating EIP: %s", d.Id())
   218  		var err error
   219  		switch resourceAwsEipDomain(d) {
   220  		case "vpc":
   221  			_, err = ec2conn.DisassociateAddress(&ec2.DisassociateAddressInput{
   222  				AssociationId: aws.String(d.Get("association_id").(string)),
   223  			})
   224  		case "standard":
   225  			_, err = ec2conn.DisassociateAddress(&ec2.DisassociateAddressInput{
   226  				PublicIp: aws.String(d.Get("public_ip").(string)),
   227  			})
   228  		}
   229  
   230  		if err != nil {
   231  			// First check if the association ID is not found. If this
   232  			// is the case, then it was already disassociated somehow,
   233  			// and that is okay. The most commmon reason for this is that
   234  			// the instance or ENI it was attached it was destroyed.
   235  			if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidAssociationID.NotFound" {
   236  				err = nil
   237  			}
   238  		}
   239  
   240  		if err != nil {
   241  			return err
   242  		}
   243  	}
   244  
   245  	domain := resourceAwsEipDomain(d)
   246  	return resource.Retry(3*time.Minute, func() error {
   247  		var err error
   248  		switch domain {
   249  		case "vpc":
   250  			log.Printf(
   251  				"[DEBUG] EIP release (destroy) address allocation: %v",
   252  				d.Id())
   253  			_, err = ec2conn.ReleaseAddress(&ec2.ReleaseAddressInput{
   254  				AllocationId: aws.String(d.Id()),
   255  			})
   256  		case "standard":
   257  			log.Printf("[DEBUG] EIP release (destroy) address: %v", d.Id())
   258  			_, err = ec2conn.ReleaseAddress(&ec2.ReleaseAddressInput{
   259  				PublicIp: aws.String(d.Id()),
   260  			})
   261  		}
   262  
   263  		if err == nil {
   264  			return nil
   265  		}
   266  		if _, ok := err.(awserr.Error); !ok {
   267  			return resource.RetryError{Err: err}
   268  		}
   269  
   270  		return err
   271  	})
   272  }
   273  
   274  func resourceAwsEipDomain(d *schema.ResourceData) string {
   275  	if v, ok := d.GetOk("domain"); ok {
   276  		return v.(string)
   277  	} else if strings.Contains(d.Id(), "eipalloc") {
   278  		// We have to do this for backwards compatibility since TF 0.1
   279  		// didn't have the "domain" computed attribute.
   280  		return "vpc"
   281  	}
   282  
   283  	return "standard"
   284  }