forked from hashicorp/terraform-provider-aws
/
resource_aws_eip.go
419 lines (356 loc) · 10.9 KB
/
resource_aws_eip.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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
package aws
import (
"fmt"
"log"
"net"
"strings"
"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 resourceAwsEip() *schema.Resource {
return &schema.Resource{
Create: resourceAwsEipCreate,
Read: resourceAwsEipRead,
Update: resourceAwsEipUpdate,
Delete: resourceAwsEipDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Read: schema.DefaultTimeout(15 * time.Minute),
Update: schema.DefaultTimeout(5 * time.Minute),
Delete: schema.DefaultTimeout(3 * time.Minute),
},
Schema: map[string]*schema.Schema{
"vpc": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Computed: true,
},
"instance": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"network_interface": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"allocation_id": {
Type: schema.TypeString,
Computed: true,
},
"association_id": {
Type: schema.TypeString,
Computed: true,
},
"domain": {
Type: schema.TypeString,
Computed: true,
},
"public_ip": {
Type: schema.TypeString,
Computed: true,
},
"private_ip": {
Type: schema.TypeString,
Computed: true,
},
"associate_with_private_ip": {
Type: schema.TypeString,
Optional: true,
},
"public_ipv4_pool": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"tags": tagsSchema(),
},
}
}
func resourceAwsEipCreate(d *schema.ResourceData, meta interface{}) error {
ec2conn := meta.(*AWSClient).ec2conn
// By default, we're not in a VPC
domainOpt := ""
if v := d.Get("vpc"); v != nil && v.(bool) {
domainOpt = "vpc"
}
allocOpts := &ec2.AllocateAddressInput{
Domain: aws.String(domainOpt),
}
if v, ok := d.GetOk("public_ipv4_pool"); ok {
allocOpts.PublicIpv4Pool = aws.String(v.(string))
}
log.Printf("[DEBUG] EIP create configuration: %#v", allocOpts)
allocResp, err := ec2conn.AllocateAddress(allocOpts)
if err != nil {
return fmt.Errorf("Error creating EIP: %s", err)
}
// The domain tells us if we're in a VPC or not
d.Set("domain", allocResp.Domain)
// Assign the eips (unique) allocation id for use later
// the EIP api has a conditional unique ID (really), so
// if we're in a VPC we need to save the ID as such, otherwise
// it defaults to using the public IP
log.Printf("[DEBUG] EIP Allocate: %#v", allocResp)
if d.Get("domain").(string) == "vpc" {
d.SetId(*allocResp.AllocationId)
} else {
d.SetId(*allocResp.PublicIp)
}
log.Printf("[INFO] EIP ID: %s (domain: %v)", d.Id(), *allocResp.Domain)
if _, ok := d.GetOk("tags"); ok {
if err := setTags(ec2conn, d); err != nil {
return fmt.Errorf("Error creating EIP tags: %s", err)
}
}
return resourceAwsEipUpdate(d, meta)
}
func resourceAwsEipRead(d *schema.ResourceData, meta interface{}) error {
ec2conn := meta.(*AWSClient).ec2conn
domain := resourceAwsEipDomain(d)
id := d.Id()
req := &ec2.DescribeAddressesInput{}
if domain == "vpc" {
req.AllocationIds = []*string{aws.String(id)}
} else {
req.PublicIps = []*string{aws.String(id)}
}
log.Printf(
"[DEBUG] EIP describe configuration: %s (domain: %s)",
req, domain)
var err error
var describeAddresses *ec2.DescribeAddressesOutput
if d.IsNewResource() {
err := resource.Retry(d.Timeout(schema.TimeoutRead), func() *resource.RetryError {
describeAddresses, err = ec2conn.DescribeAddresses(req)
if err != nil {
awsErr, ok := err.(awserr.Error)
if ok && (awsErr.Code() == "InvalidAllocationID.NotFound" ||
awsErr.Code() == "InvalidAddress.NotFound") {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return fmt.Errorf("Error retrieving EIP: %s", err)
}
} else {
describeAddresses, err = ec2conn.DescribeAddresses(req)
if err != nil {
awsErr, ok := err.(awserr.Error)
if ok && (awsErr.Code() == "InvalidAllocationID.NotFound" ||
awsErr.Code() == "InvalidAddress.NotFound") {
log.Printf("[WARN] EIP not found, removing from state: %s", req)
d.SetId("")
return nil
}
return err
}
}
var address *ec2.Address
// In the case that AWS returns more EIPs than we intend it to, we loop
// over the returned addresses to see if it's in the list of results
for _, addr := range describeAddresses.Addresses {
if (domain == "vpc" && aws.StringValue(addr.AllocationId) == id) || aws.StringValue(addr.PublicIp) == id {
address = addr
break
}
}
if address == nil {
log.Printf("[WARN] EIP %q not found, removing from state", d.Id())
d.SetId("")
return nil
}
d.Set("association_id", address.AssociationId)
if address.InstanceId != nil {
d.Set("instance", address.InstanceId)
} else {
d.Set("instance", "")
}
if address.NetworkInterfaceId != nil {
d.Set("network_interface", address.NetworkInterfaceId)
} else {
d.Set("network_interface", "")
}
d.Set("private_ip", address.PrivateIpAddress)
d.Set("public_ip", address.PublicIp)
d.Set("public_ipv4_pool", address.PublicIpv4Pool)
// On import (domain never set, which it must've been if we created),
// set the 'vpc' attribute depending on if we're in a VPC.
if address.Domain != nil {
d.Set("vpc", *address.Domain == "vpc")
}
d.Set("domain", address.Domain)
// Force ID to be an Allocation ID if we're on a VPC
// This allows users to import the EIP based on the IP if they are in a VPC
if *address.Domain == "vpc" && net.ParseIP(id) != nil {
log.Printf("[DEBUG] Re-assigning EIP ID (%s) to it's Allocation ID (%s)", d.Id(), *address.AllocationId)
d.SetId(*address.AllocationId)
}
d.Set("tags", tagsToMap(address.Tags))
return nil
}
func resourceAwsEipUpdate(d *schema.ResourceData, meta interface{}) error {
ec2conn := meta.(*AWSClient).ec2conn
domain := resourceAwsEipDomain(d)
// If we are updating an EIP that is not newly created, and we are attached to
// an instance or interface, detach first.
disassociate := false
if !d.IsNewResource() {
if d.HasChange("instance") && d.Get("instance").(string) != "" {
disassociate = true
} else if (d.HasChange("network_interface") || d.HasChange("associate_with_private_ip")) && d.Get("association_id").(string) != "" {
disassociate = true
}
}
if disassociate {
if err := disassociateEip(d, meta); err != nil {
return err
}
}
// Associate to instance or interface if specified
associate := false
v_instance, ok_instance := d.GetOk("instance")
v_interface, ok_interface := d.GetOk("network_interface")
if d.HasChange("instance") && ok_instance {
associate = true
} else if (d.HasChange("network_interface") || d.HasChange("associate_with_private_ip")) && ok_interface {
associate = true
}
if associate {
instanceId := v_instance.(string)
networkInterfaceId := v_interface.(string)
assocOpts := &ec2.AssociateAddressInput{
InstanceId: aws.String(instanceId),
PublicIp: aws.String(d.Id()),
}
// more unique ID conditionals
if domain == "vpc" {
var privateIpAddress *string
if v := d.Get("associate_with_private_ip").(string); v != "" {
privateIpAddress = aws.String(v)
}
assocOpts = &ec2.AssociateAddressInput{
NetworkInterfaceId: aws.String(networkInterfaceId),
InstanceId: aws.String(instanceId),
AllocationId: aws.String(d.Id()),
PrivateIpAddress: privateIpAddress,
}
}
log.Printf("[DEBUG] EIP associate configuration: %s (domain: %s)", assocOpts, domain)
err := resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
_, err := ec2conn.AssociateAddress(assocOpts)
if err != nil {
if isAWSErr(err, "InvalidAllocationID.NotFound", "") {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
// Prevent saving instance if association failed
// e.g. missing internet gateway in VPC
d.Set("instance", "")
d.Set("network_interface", "")
return fmt.Errorf("Failure associating EIP: %s", err)
}
}
if _, ok := d.GetOk("tags"); ok {
if err := setTags(ec2conn, d); err != nil {
return fmt.Errorf("Error updating EIP tags: %s", err)
}
}
return resourceAwsEipRead(d, meta)
}
func resourceAwsEipDelete(d *schema.ResourceData, meta interface{}) error {
ec2conn := meta.(*AWSClient).ec2conn
if err := resourceAwsEipRead(d, meta); err != nil {
return err
}
if d.Id() == "" {
// This might happen from the read
return nil
}
// If we are attached to an instance or interface, detach first.
if d.Get("instance").(string) != "" || d.Get("association_id").(string) != "" {
if err := disassociateEip(d, meta); err != nil {
return err
}
}
domain := resourceAwsEipDomain(d)
return resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
var err error
switch domain {
case "vpc":
log.Printf(
"[DEBUG] EIP release (destroy) address allocation: %v",
d.Id())
_, err = ec2conn.ReleaseAddress(&ec2.ReleaseAddressInput{
AllocationId: aws.String(d.Id()),
})
case "standard":
log.Printf("[DEBUG] EIP release (destroy) address: %v", d.Id())
_, err = ec2conn.ReleaseAddress(&ec2.ReleaseAddressInput{
PublicIp: aws.String(d.Id()),
})
}
if err == nil {
return nil
}
if _, ok := err.(awserr.Error); !ok {
return resource.NonRetryableError(err)
}
return resource.RetryableError(err)
})
}
func resourceAwsEipDomain(d *schema.ResourceData) string {
if v, ok := d.GetOk("domain"); ok {
return v.(string)
} else if strings.Contains(d.Id(), "eipalloc") {
// We have to do this for backwards compatibility since TF 0.1
// didn't have the "domain" computed attribute.
return "vpc"
}
return "standard"
}
func disassociateEip(d *schema.ResourceData, meta interface{}) error {
ec2conn := meta.(*AWSClient).ec2conn
log.Printf("[DEBUG] Disassociating EIP: %s", d.Id())
var err error
switch resourceAwsEipDomain(d) {
case "vpc":
associationID := d.Get("association_id").(string)
if associationID == "" {
// If assiciationID is empty, it means there's no association.
// Hence this disassociation can be skipped.
return nil
}
_, err = ec2conn.DisassociateAddress(&ec2.DisassociateAddressInput{
AssociationId: aws.String(associationID),
})
case "standard":
_, err = ec2conn.DisassociateAddress(&ec2.DisassociateAddressInput{
PublicIp: aws.String(d.Get("public_ip").(string)),
})
}
// First check if the association ID is not found. If this
// is the case, then it was already disassociated somehow,
// and that is okay. The most commmon reason for this is that
// the instance or ENI it was attached it was destroyed.
if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidAssociationID.NotFound" {
err = nil
}
return err
}