-
Notifications
You must be signed in to change notification settings - Fork 9.3k
/
Copy pathresource_aws_internet_gateway.go
390 lines (331 loc) · 10.2 KB
/
resource_aws_internet_gateway.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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
package aws
import (
"fmt"
"log"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
)
func resourceAwsInternetGateway() *schema.Resource {
return &schema.Resource{
Create: resourceAwsInternetGatewayCreate,
Read: resourceAwsInternetGatewayRead,
Update: resourceAwsInternetGatewayUpdate,
Delete: resourceAwsInternetGatewayDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"vpc_id": {
Type: schema.TypeString,
Optional: true,
},
"tags": tagsSchema(),
"owner_id": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceAwsInternetGatewayCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
// Create the gateway
log.Printf("[DEBUG] Creating internet gateway")
var err error
resp, err := conn.CreateInternetGateway(nil)
if err != nil {
return fmt.Errorf("Error creating internet gateway: %s", err)
}
// Get the ID and store it
ig := *resp.InternetGateway
d.SetId(*ig.InternetGatewayId)
log.Printf("[INFO] InternetGateway ID: %s", d.Id())
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
igRaw, _, err := IGStateRefreshFunc(conn, d.Id())()
if igRaw != nil {
return nil
}
if err == nil {
return resource.RetryableError(err)
} else {
return resource.NonRetryableError(err)
}
})
if err != nil {
return fmt.Errorf("%s", err)
}
err = setTags(conn, d)
if err != nil {
return err
}
// Attach the new gateway to the correct vpc
err = resourceAwsInternetGatewayAttach(d, meta)
if err != nil {
return fmt.Errorf("error attaching EC2 Internet Gateway (%s): %s", d.Id(), err)
}
return resourceAwsInternetGatewayRead(d, meta)
}
func resourceAwsInternetGatewayRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
igRaw, _, err := IGStateRefreshFunc(conn, d.Id())()
if err != nil {
return err
}
if igRaw == nil {
// Seems we have lost our internet gateway
d.SetId("")
return nil
}
ig := igRaw.(*ec2.InternetGateway)
if len(ig.Attachments) == 0 {
// Gateway exists but not attached to the VPC
d.Set("vpc_id", "")
} else {
d.Set("vpc_id", ig.Attachments[0].VpcId)
}
d.Set("tags", tagsToMap(ig.Tags))
d.Set("owner_id", ig.OwnerId)
return nil
}
func resourceAwsInternetGatewayUpdate(d *schema.ResourceData, meta interface{}) error {
if d.HasChange("vpc_id") {
// If we're already attached, detach it first
if err := resourceAwsInternetGatewayDetach(d, meta); err != nil {
return err
}
// Attach the gateway to the new vpc
if err := resourceAwsInternetGatewayAttach(d, meta); err != nil {
return err
}
}
conn := meta.(*AWSClient).ec2conn
if err := setTags(conn, d); err != nil {
return err
}
d.SetPartial("tags")
return resourceAwsInternetGatewayRead(d, meta)
}
func resourceAwsInternetGatewayDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
// Detach if it is attached
if err := resourceAwsInternetGatewayDetach(d, meta); err != nil {
return err
}
log.Printf("[INFO] Deleting Internet Gateway: %s", d.Id())
return resource.Retry(10*time.Minute, func() *resource.RetryError {
_, err := conn.DeleteInternetGateway(&ec2.DeleteInternetGatewayInput{
InternetGatewayId: aws.String(d.Id()),
})
if err == nil {
return nil
}
ec2err, ok := err.(awserr.Error)
if !ok {
return resource.RetryableError(err)
}
switch ec2err.Code() {
case "InvalidInternetGatewayID.NotFound":
return nil
case "DependencyViolation":
return resource.RetryableError(err) // retry
}
return resource.NonRetryableError(err)
})
}
func resourceAwsInternetGatewayAttach(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
if d.Get("vpc_id").(string) == "" {
log.Printf(
"[DEBUG] Not attaching Internet Gateway '%s' as no VPC ID is set",
d.Id())
return nil
}
log.Printf(
"[INFO] Attaching Internet Gateway '%s' to VPC '%s'",
d.Id(),
d.Get("vpc_id").(string))
err := resource.Retry(2*time.Minute, func() *resource.RetryError {
_, err := conn.AttachInternetGateway(&ec2.AttachInternetGatewayInput{
InternetGatewayId: aws.String(d.Id()),
VpcId: aws.String(d.Get("vpc_id").(string)),
})
if err == nil {
return nil
}
if ec2err, ok := err.(awserr.Error); ok {
switch ec2err.Code() {
case "InvalidInternetGatewayID.NotFound":
return resource.RetryableError(err) // retry
}
}
return resource.NonRetryableError(err)
})
if err != nil {
return err
}
// A note on the states below: the AWS docs (as of July, 2014) say
// that the states would be: attached, attaching, detached, detaching,
// but when running, I noticed that the state is usually "available" when
// it is attached.
// Wait for it to be fully attached before continuing
log.Printf("[DEBUG] Waiting for internet gateway (%s) to attach", d.Id())
stateConf := &resource.StateChangeConf{
Pending: []string{"detached", "attaching"},
Target: []string{"available"},
Refresh: IGAttachStateRefreshFunc(conn, d.Id(), "available"),
Timeout: 4 * time.Minute,
}
if _, err := stateConf.WaitForState(); err != nil {
return fmt.Errorf(
"Error waiting for internet gateway (%s) to attach: %s",
d.Id(), err)
}
return nil
}
func resourceAwsInternetGatewayDetach(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
// Get the old VPC ID to detach from
vpcID, _ := d.GetChange("vpc_id")
if vpcID.(string) == "" {
log.Printf(
"[DEBUG] Not detaching Internet Gateway '%s' as no VPC ID is set",
d.Id())
return nil
}
log.Printf(
"[INFO] Detaching Internet Gateway '%s' from VPC '%s'",
d.Id(),
vpcID.(string))
// Wait for it to be fully detached before continuing
log.Printf("[DEBUG] Waiting for internet gateway (%s) to detach", d.Id())
stateConf := &resource.StateChangeConf{
Pending: []string{"detaching"},
Target: []string{"detached"},
Refresh: detachIGStateRefreshFunc(conn, d.Id(), vpcID.(string)),
Timeout: 15 * time.Minute,
Delay: 10 * time.Second,
NotFoundChecks: 30,
}
if _, err := stateConf.WaitForState(); err != nil {
return fmt.Errorf(
"Error waiting for internet gateway (%s) to detach: %s",
d.Id(), err)
}
return nil
}
// InstanceStateRefreshFunc returns a resource.StateRefreshFunc that is used to watch
// an EC2 instance.
func detachIGStateRefreshFunc(conn *ec2.EC2, gatewayID, vpcID string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
_, err := conn.DetachInternetGateway(&ec2.DetachInternetGatewayInput{
InternetGatewayId: aws.String(gatewayID),
VpcId: aws.String(vpcID),
})
if err != nil {
if ec2err, ok := err.(awserr.Error); ok {
switch ec2err.Code() {
case "InvalidInternetGatewayID.NotFound":
log.Printf("[TRACE] Error detaching Internet Gateway '%s' from VPC '%s': %s", gatewayID, vpcID, err)
return nil, "", nil
case "Gateway.NotAttached":
return 42, "detached", nil
case "DependencyViolation":
// This can be caused by associated public IPs left (e.g. by ELBs)
// and here we find and log which ones are to blame
out, err := findPublicNetworkInterfacesForVpcID(conn, vpcID)
if err != nil {
return 42, "detaching", err
}
if len(out.NetworkInterfaces) > 0 {
log.Printf("[DEBUG] Waiting for the following %d ENIs to be gone: %s",
len(out.NetworkInterfaces), out.NetworkInterfaces)
}
return 42, "detaching", nil
}
}
return 42, "", err
}
// DetachInternetGateway only returns an error, so if it's nil, assume we're
// detached
return 42, "detached", nil
}
}
func findPublicNetworkInterfacesForVpcID(conn *ec2.EC2, vpcID string) (*ec2.DescribeNetworkInterfacesOutput, error) {
return conn.DescribeNetworkInterfaces(&ec2.DescribeNetworkInterfacesInput{
Filters: []*ec2.Filter{
{
Name: aws.String("vpc-id"),
Values: []*string{aws.String(vpcID)},
},
{
Name: aws.String("association.public-ip"),
Values: []*string{aws.String("*")},
},
},
})
}
// IGStateRefreshFunc returns a resource.StateRefreshFunc that is used to watch
// an internet gateway.
func IGStateRefreshFunc(conn *ec2.EC2, id string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
resp, err := conn.DescribeInternetGateways(&ec2.DescribeInternetGatewaysInput{
InternetGatewayIds: []*string{aws.String(id)},
})
if err != nil {
ec2err, ok := err.(awserr.Error)
if ok && ec2err.Code() == "InvalidInternetGatewayID.NotFound" {
resp = nil
} else {
log.Printf("[ERROR] Error on IGStateRefresh: %s", err)
return nil, "", err
}
}
if resp == nil {
// Sometimes AWS just has consistency issues and doesn't see
// our instance yet. Return an empty state.
return nil, "", nil
}
ig := resp.InternetGateways[0]
return ig, "available", nil
}
}
// IGAttachStateRefreshFunc returns a resource.StateRefreshFunc that is used
// watch the state of an internet gateway's attachment.
func IGAttachStateRefreshFunc(conn *ec2.EC2, id string, expected string) resource.StateRefreshFunc {
var start time.Time
return func() (interface{}, string, error) {
if start.IsZero() {
start = time.Now()
}
resp, err := conn.DescribeInternetGateways(&ec2.DescribeInternetGatewaysInput{
InternetGatewayIds: []*string{aws.String(id)},
})
if err != nil {
ec2err, ok := err.(awserr.Error)
if ok && ec2err.Code() == "InvalidInternetGatewayID.NotFound" {
resp = nil
} else {
log.Printf("[ERROR] Error on IGStateRefresh: %s", err)
return nil, "", err
}
}
if resp == nil {
// Sometimes AWS just has consistency issues and doesn't see
// our instance yet. Return an empty state.
return nil, "", nil
}
ig := resp.InternetGateways[0]
if time.Since(start) > 10*time.Second {
return ig, expected, nil
}
if len(ig.Attachments) == 0 {
// No attachments, we're detached
return ig, "detached", nil
}
return ig, *ig.Attachments[0].State, nil
}
}