forked from hashicorp/terraform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_aws_network_interface.go
271 lines (224 loc) · 7.68 KB
/
resource_aws_network_interface.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
package aws
import (
"bytes"
"fmt"
"log"
"strconv"
"time"
"github.com/hashicorp/aws-sdk-go/aws"
"github.com/hashicorp/aws-sdk-go/gen/ec2"
"github.com/hashicorp/terraform/helper/hashcode"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
)
func resourceAwsNetworkInterface() *schema.Resource {
return &schema.Resource{
Create: resourceAwsNetworkInterfaceCreate,
Read: resourceAwsNetworkInterfaceRead,
Update: resourceAwsNetworkInterfaceUpdate,
Delete: resourceAwsNetworkInterfaceDelete,
Schema: map[string]*schema.Schema{
"subnet_id": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"private_ips": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: func(v interface{}) int {
return hashcode.String(v.(string))
},
},
"security_groups": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: func(v interface{}) int {
return hashcode.String(v.(string))
},
},
"attachment": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"instance": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"device_index": &schema.Schema{
Type: schema.TypeInt,
Required: true,
},
"attachment_id": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
},
},
Set: resourceAwsEniAttachmentHash,
},
"tags": tagsSchema(),
},
}
}
func resourceAwsNetworkInterfaceCreate(d *schema.ResourceData, meta interface{}) error {
ec2conn := meta.(*AWSClient).ec2conn
request := &ec2.CreateNetworkInterfaceRequest{
Groups: expandStringList(d.Get("security_groups").(*schema.Set).List()),
SubnetID: aws.String(d.Get("subnet_id").(string)),
PrivateIPAddresses: expandPrivateIPAddesses(d.Get("private_ips").(*schema.Set).List()),
}
log.Printf("[DEBUG] Creating network interface")
resp, err := ec2conn.CreateNetworkInterface(request)
if err != nil {
return fmt.Errorf("Error creating ENI: %s", err)
}
d.SetId(*resp.NetworkInterface.NetworkInterfaceID)
log.Printf("[INFO] ENI ID: %s", d.Id())
return resourceAwsNetworkInterfaceUpdate(d, meta)
}
func resourceAwsNetworkInterfaceRead(d *schema.ResourceData, meta interface{}) error {
ec2conn := meta.(*AWSClient).ec2conn
describe_network_interfaces_request := &ec2.DescribeNetworkInterfacesRequest{
NetworkInterfaceIDs: []string{d.Id()},
}
describeResp, err := ec2conn.DescribeNetworkInterfaces(describe_network_interfaces_request)
if err != nil {
if ec2err, ok := err.(aws.APIError); ok && ec2err.Code == "InvalidNetworkInterfaceID.NotFound" {
// The ENI is gone now, so just remove it from the state
d.SetId("")
return nil
}
return fmt.Errorf("Error retrieving ENI: %s", err)
}
if len(describeResp.NetworkInterfaces) != 1 {
return fmt.Errorf("Unable to find ENI: %#v", describeResp.NetworkInterfaces)
}
eni := describeResp.NetworkInterfaces[0]
d.Set("subnet_id", eni.SubnetID)
d.Set("private_ips", flattenNetworkInterfacesPrivateIPAddesses(eni.PrivateIPAddresses))
d.Set("security_groups", flattenGroupIdentifiers(eni.Groups))
// Tags
d.Set("tags", tagsToMap(eni.TagSet))
if eni.Attachment != nil {
attachment := []map[string]interface{}{flattenAttachment(eni.Attachment)}
d.Set("attachment", attachment)
} else {
d.Set("attachment", nil)
}
return nil
}
func networkInterfaceAttachmentRefreshFunc(ec2conn *ec2.EC2, id string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
describe_network_interfaces_request := &ec2.DescribeNetworkInterfacesRequest{
NetworkInterfaceIDs: []string{id},
}
describeResp, err := ec2conn.DescribeNetworkInterfaces(describe_network_interfaces_request)
if err != nil {
log.Printf("[ERROR] Could not find network interface %s. %s", id, err)
return nil, "", err
}
eni := describeResp.NetworkInterfaces[0]
hasAttachment := strconv.FormatBool(eni.Attachment != nil)
log.Printf("[DEBUG] ENI %s has attachment state %s", id, hasAttachment)
return eni, hasAttachment, nil
}
}
func resourceAwsNetworkInterfaceDetach(oa *schema.Set, meta interface{}, eniId string) error {
// if there was an old attachment, remove it
if oa != nil && len(oa.List()) > 0 {
old_attachment := oa.List()[0].(map[string]interface{})
detach_request := &ec2.DetachNetworkInterfaceRequest{
AttachmentID: aws.String(old_attachment["attachment_id"].(string)),
Force: aws.Boolean(true),
}
ec2conn := meta.(*AWSClient).ec2conn
detach_err := ec2conn.DetachNetworkInterface(detach_request)
if detach_err != nil {
return fmt.Errorf("Error detaching ENI: %s", detach_err)
}
log.Printf("[DEBUG] Waiting for ENI (%s) to become dettached", eniId)
stateConf := &resource.StateChangeConf{
Pending: []string{"true"},
Target: "false",
Refresh: networkInterfaceAttachmentRefreshFunc(ec2conn, eniId),
Timeout: 10 * time.Minute,
}
if _, err := stateConf.WaitForState(); err != nil {
return fmt.Errorf(
"Error waiting for ENI (%s) to become dettached: %s", eniId, err)
}
}
return nil
}
func resourceAwsNetworkInterfaceUpdate(d *schema.ResourceData, meta interface{}) error {
ec2conn := meta.(*AWSClient).ec2conn
d.Partial(true)
if d.HasChange("attachment") {
ec2conn := meta.(*AWSClient).ec2conn
oa, na := d.GetChange("attachment")
detach_err := resourceAwsNetworkInterfaceDetach(oa.(*schema.Set), meta, d.Id())
if detach_err != nil {
return detach_err
}
// if there is a new attachment, attach it
if na != nil && len(na.(*schema.Set).List()) > 0 {
new_attachment := na.(*schema.Set).List()[0].(map[string]interface{})
attach_request := &ec2.AttachNetworkInterfaceRequest{
DeviceIndex: aws.Integer(new_attachment["device_index"].(int)),
InstanceID: aws.String(new_attachment["instance"].(string)),
NetworkInterfaceID: aws.String(d.Id()),
}
_, attach_err := ec2conn.AttachNetworkInterface(attach_request)
if attach_err != nil {
return fmt.Errorf("Error attaching ENI: %s", attach_err)
}
}
d.SetPartial("attachment")
}
if d.HasChange("security_groups") {
request := &ec2.ModifyNetworkInterfaceAttributeRequest{
NetworkInterfaceID: aws.String(d.Id()),
Groups: expandStringList(d.Get("security_groups").(*schema.Set).List()),
}
err := ec2conn.ModifyNetworkInterfaceAttribute(request)
if err != nil {
return fmt.Errorf("Failure updating ENI: %s", err)
}
d.SetPartial("security_groups")
}
if err := setTags(ec2conn, d); err != nil {
return err
} else {
d.SetPartial("tags")
}
d.Partial(false)
return resourceAwsNetworkInterfaceRead(d, meta)
}
func resourceAwsNetworkInterfaceDelete(d *schema.ResourceData, meta interface{}) error {
ec2conn := meta.(*AWSClient).ec2conn
log.Printf("[INFO] Deleting ENI: %s", d.Id())
detach_err := resourceAwsNetworkInterfaceDetach(d.Get("attachment").(*schema.Set), meta, d.Id())
if detach_err != nil {
return detach_err
}
deleteEniOpts := ec2.DeleteNetworkInterfaceRequest{
NetworkInterfaceID: aws.String(d.Id()),
}
if err := ec2conn.DeleteNetworkInterface(&deleteEniOpts); err != nil {
return fmt.Errorf("Error deleting ENI: %s", err)
}
return nil
}
func resourceAwsEniAttachmentHash(v interface{}) int {
var buf bytes.Buffer
m := v.(map[string]interface{})
buf.WriteString(fmt.Sprintf("%s-", m["instance"].(string)))
buf.WriteString(fmt.Sprintf("%d-", m["device_index"].(int)))
return hashcode.String(buf.String())
}