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

     1  package aws
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"log"
     7  	"strconv"
     8  	"time"
     9  
    10  	"github.com/aws/aws-sdk-go/aws"
    11  	"github.com/aws/aws-sdk-go/aws/awserr"
    12  	"github.com/aws/aws-sdk-go/service/ec2"
    13  	"github.com/hashicorp/terraform/helper/hashcode"
    14  	"github.com/hashicorp/terraform/helper/resource"
    15  	"github.com/hashicorp/terraform/helper/schema"
    16  )
    17  
    18  func resourceAwsNetworkInterface() *schema.Resource {
    19  	return &schema.Resource{
    20  		Create: resourceAwsNetworkInterfaceCreate,
    21  		Read:   resourceAwsNetworkInterfaceRead,
    22  		Update: resourceAwsNetworkInterfaceUpdate,
    23  		Delete: resourceAwsNetworkInterfaceDelete,
    24  
    25  		Schema: map[string]*schema.Schema{
    26  
    27  			"subnet_id": &schema.Schema{
    28  				Type:     schema.TypeString,
    29  				Required: true,
    30  				ForceNew: true,
    31  			},
    32  
    33  			"private_ips": &schema.Schema{
    34  				Type:     schema.TypeSet,
    35  				Optional: true,
    36  				Computed: true,
    37  				Elem:     &schema.Schema{Type: schema.TypeString},
    38  				Set:      schema.HashString,
    39  			},
    40  
    41  			"security_groups": &schema.Schema{
    42  				Type:     schema.TypeSet,
    43  				Optional: true,
    44  				Computed: true,
    45  				Elem:     &schema.Schema{Type: schema.TypeString},
    46  				Set:      schema.HashString,
    47  			},
    48  
    49  			"source_dest_check": &schema.Schema{
    50  				Type:     schema.TypeBool,
    51  				Optional: true,
    52  				Default:  true,
    53  			},
    54  
    55  			"attachment": &schema.Schema{
    56  				Type:     schema.TypeSet,
    57  				Optional: true,
    58  				Computed: true,
    59  				Elem: &schema.Resource{
    60  					Schema: map[string]*schema.Schema{
    61  						"instance": &schema.Schema{
    62  							Type:     schema.TypeString,
    63  							Required: true,
    64  						},
    65  						"device_index": &schema.Schema{
    66  							Type:     schema.TypeInt,
    67  							Required: true,
    68  						},
    69  						"attachment_id": &schema.Schema{
    70  							Type:     schema.TypeString,
    71  							Computed: true,
    72  						},
    73  					},
    74  				},
    75  				Set: resourceAwsEniAttachmentHash,
    76  			},
    77  
    78  			"tags": tagsSchema(),
    79  		},
    80  	}
    81  }
    82  
    83  func resourceAwsNetworkInterfaceCreate(d *schema.ResourceData, meta interface{}) error {
    84  
    85  	conn := meta.(*AWSClient).ec2conn
    86  
    87  	request := &ec2.CreateNetworkInterfaceInput{
    88  		SubnetId: aws.String(d.Get("subnet_id").(string)),
    89  	}
    90  
    91  	security_groups := d.Get("security_groups").(*schema.Set).List()
    92  	if len(security_groups) != 0 {
    93  		request.Groups = expandStringList(security_groups)
    94  	}
    95  
    96  	private_ips := d.Get("private_ips").(*schema.Set).List()
    97  	if len(private_ips) != 0 {
    98  		request.PrivateIpAddresses = expandPrivateIPAddresses(private_ips)
    99  	}
   100  
   101  	log.Printf("[DEBUG] Creating network interface")
   102  	resp, err := conn.CreateNetworkInterface(request)
   103  	if err != nil {
   104  		return fmt.Errorf("Error creating ENI: %s", err)
   105  	}
   106  
   107  	d.SetId(*resp.NetworkInterface.NetworkInterfaceId)
   108  	log.Printf("[INFO] ENI ID: %s", d.Id())
   109  	return resourceAwsNetworkInterfaceUpdate(d, meta)
   110  }
   111  
   112  func resourceAwsNetworkInterfaceRead(d *schema.ResourceData, meta interface{}) error {
   113  
   114  	conn := meta.(*AWSClient).ec2conn
   115  	describe_network_interfaces_request := &ec2.DescribeNetworkInterfacesInput{
   116  		NetworkInterfaceIds: []*string{aws.String(d.Id())},
   117  	}
   118  	describeResp, err := conn.DescribeNetworkInterfaces(describe_network_interfaces_request)
   119  
   120  	if err != nil {
   121  		if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidNetworkInterfaceID.NotFound" {
   122  			// The ENI is gone now, so just remove it from the state
   123  			d.SetId("")
   124  			return nil
   125  		}
   126  
   127  		return fmt.Errorf("Error retrieving ENI: %s", err)
   128  	}
   129  	if len(describeResp.NetworkInterfaces) != 1 {
   130  		return fmt.Errorf("Unable to find ENI: %#v", describeResp.NetworkInterfaces)
   131  	}
   132  
   133  	eni := describeResp.NetworkInterfaces[0]
   134  	d.Set("subnet_id", eni.SubnetId)
   135  	d.Set("private_ips", flattenNetworkInterfacesPrivateIPAddresses(eni.PrivateIpAddresses))
   136  	d.Set("security_groups", flattenGroupIdentifiers(eni.Groups))
   137  	d.Set("source_dest_check", eni.SourceDestCheck)
   138  
   139  	// Tags
   140  	d.Set("tags", tagsToMap(eni.TagSet))
   141  
   142  	if eni.Attachment != nil {
   143  		attachment := []map[string]interface{}{flattenAttachment(eni.Attachment)}
   144  		d.Set("attachment", attachment)
   145  	} else {
   146  		d.Set("attachment", nil)
   147  	}
   148  
   149  	return nil
   150  }
   151  
   152  func networkInterfaceAttachmentRefreshFunc(conn *ec2.EC2, id string) resource.StateRefreshFunc {
   153  	return func() (interface{}, string, error) {
   154  
   155  		describe_network_interfaces_request := &ec2.DescribeNetworkInterfacesInput{
   156  			NetworkInterfaceIds: []*string{aws.String(id)},
   157  		}
   158  		describeResp, err := conn.DescribeNetworkInterfaces(describe_network_interfaces_request)
   159  
   160  		if err != nil {
   161  			log.Printf("[ERROR] Could not find network interface %s. %s", id, err)
   162  			return nil, "", err
   163  		}
   164  
   165  		eni := describeResp.NetworkInterfaces[0]
   166  		hasAttachment := strconv.FormatBool(eni.Attachment != nil)
   167  		log.Printf("[DEBUG] ENI %s has attachment state %s", id, hasAttachment)
   168  		return eni, hasAttachment, nil
   169  	}
   170  }
   171  
   172  func resourceAwsNetworkInterfaceDetach(oa *schema.Set, meta interface{}, eniId string) error {
   173  	// if there was an old attachment, remove it
   174  	if oa != nil && len(oa.List()) > 0 {
   175  		old_attachment := oa.List()[0].(map[string]interface{})
   176  		detach_request := &ec2.DetachNetworkInterfaceInput{
   177  			AttachmentId: aws.String(old_attachment["attachment_id"].(string)),
   178  			Force:        aws.Bool(true),
   179  		}
   180  		conn := meta.(*AWSClient).ec2conn
   181  		_, detach_err := conn.DetachNetworkInterface(detach_request)
   182  		if detach_err != nil {
   183  			return fmt.Errorf("Error detaching ENI: %s", detach_err)
   184  		}
   185  
   186  		log.Printf("[DEBUG] Waiting for ENI (%s) to become dettached", eniId)
   187  		stateConf := &resource.StateChangeConf{
   188  			Pending: []string{"true"},
   189  			Target:  []string{"false"},
   190  			Refresh: networkInterfaceAttachmentRefreshFunc(conn, eniId),
   191  			Timeout: 10 * time.Minute,
   192  		}
   193  		if _, err := stateConf.WaitForState(); err != nil {
   194  			return fmt.Errorf(
   195  				"Error waiting for ENI (%s) to become dettached: %s", eniId, err)
   196  		}
   197  	}
   198  
   199  	return nil
   200  }
   201  
   202  func resourceAwsNetworkInterfaceUpdate(d *schema.ResourceData, meta interface{}) error {
   203  	conn := meta.(*AWSClient).ec2conn
   204  	d.Partial(true)
   205  
   206  	if d.HasChange("attachment") {
   207  		oa, na := d.GetChange("attachment")
   208  
   209  		detach_err := resourceAwsNetworkInterfaceDetach(oa.(*schema.Set), meta, d.Id())
   210  		if detach_err != nil {
   211  			return detach_err
   212  		}
   213  
   214  		// if there is a new attachment, attach it
   215  		if na != nil && len(na.(*schema.Set).List()) > 0 {
   216  			new_attachment := na.(*schema.Set).List()[0].(map[string]interface{})
   217  			di := new_attachment["device_index"].(int)
   218  			attach_request := &ec2.AttachNetworkInterfaceInput{
   219  				DeviceIndex:        aws.Int64(int64(di)),
   220  				InstanceId:         aws.String(new_attachment["instance"].(string)),
   221  				NetworkInterfaceId: aws.String(d.Id()),
   222  			}
   223  			_, attach_err := conn.AttachNetworkInterface(attach_request)
   224  			if attach_err != nil {
   225  				return fmt.Errorf("Error attaching ENI: %s", attach_err)
   226  			}
   227  		}
   228  
   229  		d.SetPartial("attachment")
   230  	}
   231  
   232  	if d.HasChange("private_ips") {
   233  		o, n := d.GetChange("private_ips")
   234  		if o == nil {
   235  			o = new(schema.Set)
   236  		}
   237  		if n == nil {
   238  			n = new(schema.Set)
   239  		}
   240  
   241  		os := o.(*schema.Set)
   242  		ns := n.(*schema.Set)
   243  
   244  		// Unassign old IP addresses
   245  		unassignIps := os.Difference(ns)
   246  		if unassignIps.Len() != 0 {
   247  			input := &ec2.UnassignPrivateIpAddressesInput{
   248  				NetworkInterfaceId: aws.String(d.Id()),
   249  				PrivateIpAddresses: expandStringList(unassignIps.List()),
   250  			}
   251  			_, err := conn.UnassignPrivateIpAddresses(input)
   252  			if err != nil {
   253  				return fmt.Errorf("Failure to unassign Private IPs: %s", err)
   254  			}
   255  		}
   256  
   257  		// Assign new IP addresses
   258  		assignIps := ns.Difference(os)
   259  		if assignIps.Len() != 0 {
   260  			input := &ec2.AssignPrivateIpAddressesInput{
   261  				NetworkInterfaceId: aws.String(d.Id()),
   262  				PrivateIpAddresses: expandStringList(assignIps.List()),
   263  			}
   264  			_, err := conn.AssignPrivateIpAddresses(input)
   265  			if err != nil {
   266  				return fmt.Errorf("Failure to assign Private IPs: %s", err)
   267  			}
   268  		}
   269  
   270  		d.SetPartial("private_ips")
   271  	}
   272  
   273  	request := &ec2.ModifyNetworkInterfaceAttributeInput{
   274  		NetworkInterfaceId: aws.String(d.Id()),
   275  		SourceDestCheck:    &ec2.AttributeBooleanValue{Value: aws.Bool(d.Get("source_dest_check").(bool))},
   276  	}
   277  
   278  	_, err := conn.ModifyNetworkInterfaceAttribute(request)
   279  	if err != nil {
   280  		return fmt.Errorf("Failure updating ENI: %s", err)
   281  	}
   282  
   283  	d.SetPartial("source_dest_check")
   284  
   285  	if d.HasChange("security_groups") {
   286  		request := &ec2.ModifyNetworkInterfaceAttributeInput{
   287  			NetworkInterfaceId: aws.String(d.Id()),
   288  			Groups:             expandStringList(d.Get("security_groups").(*schema.Set).List()),
   289  		}
   290  
   291  		_, err := conn.ModifyNetworkInterfaceAttribute(request)
   292  		if err != nil {
   293  			return fmt.Errorf("Failure updating ENI: %s", err)
   294  		}
   295  
   296  		d.SetPartial("security_groups")
   297  	}
   298  
   299  	if err := setTags(conn, d); err != nil {
   300  		return err
   301  	} else {
   302  		d.SetPartial("tags")
   303  	}
   304  
   305  	d.Partial(false)
   306  
   307  	return resourceAwsNetworkInterfaceRead(d, meta)
   308  }
   309  
   310  func resourceAwsNetworkInterfaceDelete(d *schema.ResourceData, meta interface{}) error {
   311  	conn := meta.(*AWSClient).ec2conn
   312  
   313  	log.Printf("[INFO] Deleting ENI: %s", d.Id())
   314  
   315  	detach_err := resourceAwsNetworkInterfaceDetach(d.Get("attachment").(*schema.Set), meta, d.Id())
   316  	if detach_err != nil {
   317  		return detach_err
   318  	}
   319  
   320  	deleteEniOpts := ec2.DeleteNetworkInterfaceInput{
   321  		NetworkInterfaceId: aws.String(d.Id()),
   322  	}
   323  	if _, err := conn.DeleteNetworkInterface(&deleteEniOpts); err != nil {
   324  		return fmt.Errorf("Error deleting ENI: %s", err)
   325  	}
   326  
   327  	return nil
   328  }
   329  
   330  func resourceAwsEniAttachmentHash(v interface{}) int {
   331  	var buf bytes.Buffer
   332  	m := v.(map[string]interface{})
   333  	buf.WriteString(fmt.Sprintf("%s-", m["instance"].(string)))
   334  	buf.WriteString(fmt.Sprintf("%d-", m["device_index"].(int)))
   335  	return hashcode.String(buf.String())
   336  }