github.com/acm1/terraform@v0.6.2-0.20150729164239-1f314444f45c/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 ForceNew: true, 37 Computed: true, 38 Elem: &schema.Schema{Type: schema.TypeString}, 39 Set: schema.HashString, 40 }, 41 42 "security_groups": &schema.Schema{ 43 Type: schema.TypeSet, 44 Optional: true, 45 Computed: true, 46 Elem: &schema.Schema{Type: schema.TypeString}, 47 Set: schema.HashString, 48 }, 49 50 "source_dest_check": &schema.Schema{ 51 Type: schema.TypeBool, 52 Optional: true, 53 Default: true, 54 }, 55 56 "attachment": &schema.Schema{ 57 Type: schema.TypeSet, 58 Optional: 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 = expandPrivateIPAddesses(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", flattenNetworkInterfacesPrivateIPAddesses(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: "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 request := &ec2.ModifyNetworkInterfaceAttributeInput{ 233 NetworkInterfaceID: aws.String(d.Id()), 234 SourceDestCheck: &ec2.AttributeBooleanValue{Value: aws.Bool(d.Get("source_dest_check").(bool))}, 235 } 236 237 _, err := conn.ModifyNetworkInterfaceAttribute(request) 238 if err != nil { 239 return fmt.Errorf("Failure updating ENI: %s", err) 240 } 241 242 d.SetPartial("source_dest_check") 243 244 if d.HasChange("security_groups") { 245 request := &ec2.ModifyNetworkInterfaceAttributeInput{ 246 NetworkInterfaceID: aws.String(d.Id()), 247 Groups: expandStringList(d.Get("security_groups").(*schema.Set).List()), 248 } 249 250 _, err := conn.ModifyNetworkInterfaceAttribute(request) 251 if err != nil { 252 return fmt.Errorf("Failure updating ENI: %s", err) 253 } 254 255 d.SetPartial("security_groups") 256 } 257 258 if err := setTags(conn, d); err != nil { 259 return err 260 } else { 261 d.SetPartial("tags") 262 } 263 264 d.Partial(false) 265 266 return resourceAwsNetworkInterfaceRead(d, meta) 267 } 268 269 func resourceAwsNetworkInterfaceDelete(d *schema.ResourceData, meta interface{}) error { 270 conn := meta.(*AWSClient).ec2conn 271 272 log.Printf("[INFO] Deleting ENI: %s", d.Id()) 273 274 detach_err := resourceAwsNetworkInterfaceDetach(d.Get("attachment").(*schema.Set), meta, d.Id()) 275 if detach_err != nil { 276 return detach_err 277 } 278 279 deleteEniOpts := ec2.DeleteNetworkInterfaceInput{ 280 NetworkInterfaceID: aws.String(d.Id()), 281 } 282 if _, err := conn.DeleteNetworkInterface(&deleteEniOpts); err != nil { 283 return fmt.Errorf("Error deleting ENI: %s", err) 284 } 285 286 return nil 287 } 288 289 func resourceAwsEniAttachmentHash(v interface{}) int { 290 var buf bytes.Buffer 291 m := v.(map[string]interface{}) 292 buf.WriteString(fmt.Sprintf("%s-", m["instance"].(string))) 293 buf.WriteString(fmt.Sprintf("%d-", m["device_index"].(int))) 294 return hashcode.String(buf.String()) 295 }