-
Notifications
You must be signed in to change notification settings - Fork 9.3k
/
Copy pathvpc_peering_connection.go
425 lines (344 loc) · 14.8 KB
/
vpc_peering_connection.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
420
421
422
423
424
425
package ec2
import (
"errors"
"fmt"
"log"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-provider-aws/internal/conns"
tftags "github.com/hashicorp/terraform-provider-aws/internal/tags"
"github.com/hashicorp/terraform-provider-aws/internal/tfresource"
"github.com/hashicorp/terraform-provider-aws/internal/verify"
)
func ResourceVPCPeeringConnection() *schema.Resource {
return &schema.Resource{
Create: resourceVPCPeeringConnectionCreate,
Read: resourceVPCPeeringConnectionRead,
Update: resourceVPCPeeringConnectionUpdate,
Delete: resourceVPCPeeringConnectionDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(1 * time.Minute),
Update: schema.DefaultTimeout(1 * time.Minute),
Delete: schema.DefaultTimeout(1 * time.Minute),
},
// Keep in sync with aws_vpc_peering_connection_accepter's schema.
// See notes in vpc_peering_connection_accepter.go.
Schema: map[string]*schema.Schema{
"accept_status": {
Type: schema.TypeString,
Computed: true,
},
"accepter": vpcPeeringConnectionOptionsSchema,
"auto_accept": {
Type: schema.TypeBool,
Optional: true,
},
"peer_owner_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"peer_region": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"peer_vpc_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"requester": vpcPeeringConnectionOptionsSchema,
"tags": tftags.TagsSchema(),
"tags_all": tftags.TagsSchemaComputed(),
"vpc_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
CustomizeDiff: verify.SetTagsDiff,
}
}
var vpcPeeringConnectionOptionsSchema = &schema.Schema{
Type: schema.TypeList,
Optional: true,
Computed: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"allow_classic_link_to_remote_vpc": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"allow_remote_vpc_dns_resolution": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"allow_vpc_to_remote_classic_link": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
},
}
func resourceVPCPeeringConnectionCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*conns.AWSClient).EC2Conn
defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig
tags := defaultTagsConfig.MergeTags(tftags.New(d.Get("tags").(map[string]interface{})))
input := &ec2.CreateVpcPeeringConnectionInput{
PeerVpcId: aws.String(d.Get("peer_vpc_id").(string)),
TagSpecifications: tagSpecificationsFromKeyValueTags(tags, ec2.ResourceTypeVpcPeeringConnection),
VpcId: aws.String(d.Get("vpc_id").(string)),
}
if v, ok := d.GetOk("peer_owner_id"); ok {
input.PeerOwnerId = aws.String(v.(string))
}
if v, ok := d.GetOk("peer_region"); ok {
if _, ok := d.GetOk("auto_accept"); ok {
return fmt.Errorf("`peer_region` cannot be set whilst `auto_accept` is `true` when creating an EC2 VPC Peering Connection")
}
input.PeerRegion = aws.String(v.(string))
}
log.Printf("[DEBUG] Creating EC2 VPC Peering Connection: %s", input)
output, err := conn.CreateVpcPeeringConnection(input)
if err != nil {
return fmt.Errorf("error creating EC2 VPC Peering Connection: %w", err)
}
d.SetId(aws.StringValue(output.VpcPeeringConnection.VpcPeeringConnectionId))
vpcPeeringConnection, err := WaitVPCPeeringConnectionActive(conn, d.Id(), d.Timeout(schema.TimeoutCreate))
if err != nil {
return fmt.Errorf("error waiting for EC2 VPC Peering Connection (%s) create: %w", d.Id(), err)
}
if _, ok := d.GetOk("auto_accept"); ok && aws.StringValue(vpcPeeringConnection.Status.Code) == ec2.VpcPeeringConnectionStateReasonCodePendingAcceptance {
vpcPeeringConnection, err = acceptVPCPeeringConnection(conn, d.Id(), d.Timeout(schema.TimeoutCreate))
if err != nil {
return err
}
}
if err := modifyVPCPeeringConnectionOptions(conn, d, vpcPeeringConnection, true); err != nil {
return err
}
return resourceVPCPeeringConnectionRead(d, meta)
}
func resourceVPCPeeringConnectionRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*conns.AWSClient).EC2Conn
defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig
ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig
vpcPeeringConnection, err := FindVPCPeeringConnectionByID(conn, d.Id())
if !d.IsNewResource() && tfresource.NotFound(err) {
log.Printf("[WARN] EC2 VPC Peering Connection %s not found, removing from state", d.Id())
d.SetId("")
return nil
}
if err != nil {
return fmt.Errorf("error reading EC2 VPC Peering Connection (%s): %w", d.Id(), err)
}
d.Set("accept_status", vpcPeeringConnection.Status.Code)
d.Set("peer_region", vpcPeeringConnection.AccepterVpcInfo.Region)
if accountID := meta.(*conns.AWSClient).AccountID; accountID == aws.StringValue(vpcPeeringConnection.AccepterVpcInfo.OwnerId) && accountID != aws.StringValue(vpcPeeringConnection.RequesterVpcInfo.OwnerId) {
// We're the accepter.
d.Set("peer_owner_id", vpcPeeringConnection.RequesterVpcInfo.OwnerId)
d.Set("peer_vpc_id", vpcPeeringConnection.RequesterVpcInfo.VpcId)
d.Set("vpc_id", vpcPeeringConnection.AccepterVpcInfo.VpcId)
} else {
// We're the requester.
d.Set("peer_owner_id", vpcPeeringConnection.AccepterVpcInfo.OwnerId)
d.Set("peer_vpc_id", vpcPeeringConnection.AccepterVpcInfo.VpcId)
d.Set("vpc_id", vpcPeeringConnection.RequesterVpcInfo.VpcId)
}
if vpcPeeringConnection.AccepterVpcInfo.PeeringOptions != nil {
if err := d.Set("accepter", []interface{}{flattenVPCPeeringConnectionOptionsDescription(vpcPeeringConnection.AccepterVpcInfo.PeeringOptions)}); err != nil {
return fmt.Errorf("error setting accepter: %w", err)
}
} else {
d.Set("accepter", nil)
}
if vpcPeeringConnection.RequesterVpcInfo.PeeringOptions != nil {
if err := d.Set("requester", []interface{}{flattenVPCPeeringConnectionOptionsDescription(vpcPeeringConnection.RequesterVpcInfo.PeeringOptions)}); err != nil {
return fmt.Errorf("error setting requester: %w", err)
}
} else {
d.Set("requester", nil)
}
tags := KeyValueTags(vpcPeeringConnection.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig)
//lintignore:AWSR002
if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil {
return fmt.Errorf("error setting tags: %w", err)
}
if err := d.Set("tags_all", tags.Map()); err != nil {
return fmt.Errorf("error setting tags_all: %w", err)
}
return nil
}
func resourceVPCPeeringConnectionUpdate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*conns.AWSClient).EC2Conn
vpcPeeringConnection, err := FindVPCPeeringConnectionByID(conn, d.Id())
if err != nil {
return fmt.Errorf("error reading EC2 VPC Peering Connection (%s): %w", d.Id(), err)
}
if _, ok := d.GetOk("auto_accept"); ok && aws.StringValue(vpcPeeringConnection.Status.Code) == ec2.VpcPeeringConnectionStateReasonCodePendingAcceptance {
vpcPeeringConnection, err = acceptVPCPeeringConnection(conn, d.Id(), d.Timeout(schema.TimeoutCreate))
if err != nil {
return err
}
}
if d.HasChanges("accepter", "requester") {
if err := modifyVPCPeeringConnectionOptions(conn, d, vpcPeeringConnection, true); err != nil {
return err
}
}
if d.HasChange("tags_all") {
o, n := d.GetChange("tags_all")
if err := UpdateTags(conn, d.Id(), o, n); err != nil {
return fmt.Errorf("error updating EC2 VPC Peering Connection (%s) tags: %w", d.Id(), err)
}
}
return resourceVPCPeeringConnectionRead(d, meta)
}
func resourceVPCPeeringConnectionDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*conns.AWSClient).EC2Conn
log.Printf("[INFO] Deleting EC2 VPC Peering Connection: %s", d.Id())
_, err := conn.DeleteVpcPeeringConnection(&ec2.DeleteVpcPeeringConnectionInput{
VpcPeeringConnectionId: aws.String(d.Id()),
})
if tfawserr.ErrCodeEquals(err, errCodeInvalidVPCPeeringConnectionIDNotFound) {
return nil
}
// "InvalidStateTransition: Invalid state transition for pcx-0000000000000000, attempted to transition from failed to deleting"
if tfawserr.ErrMessageContains(err, "InvalidStateTransition", "to deleting") {
return nil
}
if err != nil {
return fmt.Errorf("error deleting EC2 VPC Peering Connection (%s): %w", d.Id(), err)
}
if _, err := WaitVPCPeeringConnectionDeleted(conn, d.Id(), d.Timeout(schema.TimeoutDelete)); err != nil {
return fmt.Errorf("error waiting for EC2 VPC Peering Connection (%s) delete: %s", d.Id(), err)
}
return nil
}
func acceptVPCPeeringConnection(conn *ec2.EC2, vpcPeeringConnectionID string, timeout time.Duration) (*ec2.VpcPeeringConnection, error) {
log.Printf("[INFO] Accepting EC2 VPC Peering Connection: %s", vpcPeeringConnectionID)
_, err := conn.AcceptVpcPeeringConnection(&ec2.AcceptVpcPeeringConnectionInput{
VpcPeeringConnectionId: aws.String(vpcPeeringConnectionID),
})
if err != nil {
return nil, fmt.Errorf("error acccepting EC2 VPC Peering Connection (%s): %w", vpcPeeringConnectionID, err)
}
// "OperationNotPermitted: Peering pcx-0000000000000000 is not active. Peering options can be added only to active peerings."
vpcPeeringConnection, err := WaitVPCPeeringConnectionActive(conn, vpcPeeringConnectionID, timeout)
if err != nil {
return nil, fmt.Errorf("error waiting for EC2 VPC Peering Connection (%s) update: %w", vpcPeeringConnectionID, err)
}
return vpcPeeringConnection, nil
}
func modifyVPCPeeringConnectionOptions(conn *ec2.EC2, d *schema.ResourceData, vpcPeeringConnection *ec2.VpcPeeringConnection, checkActive bool) error {
var accepterPeeringConnectionOptions, requesterPeeringConnectionOptions *ec2.PeeringConnectionOptionsRequest
crossRegionPeering := aws.StringValue(vpcPeeringConnection.RequesterVpcInfo.Region) != aws.StringValue(vpcPeeringConnection.AccepterVpcInfo.Region)
if key := "accepter"; d.HasChange(key) {
if v, ok := d.GetOk(key); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil {
accepterPeeringConnectionOptions = expandPeeringConnectionOptionsRequest(v.([]interface{})[0].(map[string]interface{}), crossRegionPeering)
}
}
if key := "requester"; d.HasChange(key) {
if v, ok := d.GetOk(key); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil {
requesterPeeringConnectionOptions = expandPeeringConnectionOptionsRequest(v.([]interface{})[0].(map[string]interface{}), crossRegionPeering)
}
}
if accepterPeeringConnectionOptions == nil && requesterPeeringConnectionOptions == nil {
return nil
}
if checkActive {
switch statusCode := aws.StringValue(vpcPeeringConnection.Status.Code); statusCode {
case ec2.VpcPeeringConnectionStateReasonCodeActive, ec2.VpcPeeringConnectionStateReasonCodeProvisioning:
default:
return fmt.Errorf(
"Unable to modify EC2 VPC Peering Connection Options. EC2 VPC Peering Connection (%s) is not active (current status: %s). "+
"Please set the `auto_accept` attribute to `true` or activate the EC2 VPC Peering Connection manually.",
d.Id(), statusCode)
}
}
input := &ec2.ModifyVpcPeeringConnectionOptionsInput{
AccepterPeeringConnectionOptions: accepterPeeringConnectionOptions,
RequesterPeeringConnectionOptions: requesterPeeringConnectionOptions,
VpcPeeringConnectionId: aws.String(d.Id()),
}
log.Printf("[DEBUG] Modifying VPC Peering Connection Options: %s", input)
if _, err := conn.ModifyVpcPeeringConnectionOptions(input); err != nil {
return fmt.Errorf("error modifying EC2 VPC Peering Connection (%s) Options: %w", d.Id(), err)
}
// Retry reading back the modified options to deal with eventual consistency.
// Often this is to do with a delay transitioning from pending-acceptance to active.
err := resource.Retry(VPCPeeringConnectionOptionsPropagationTimeout, func() *resource.RetryError { // nosem: helper-schema-resource-Retry-without-TimeoutError-check
vpcPeeringConnection, err := FindVPCPeeringConnectionByID(conn, d.Id())
if err != nil {
return resource.NonRetryableError(err)
}
if v := vpcPeeringConnection.AccepterVpcInfo; v != nil && accepterPeeringConnectionOptions != nil {
if !vpcPeeringConnectionOptionsEqual(v.PeeringOptions, accepterPeeringConnectionOptions) {
return resource.RetryableError(errors.New("Accepter Options not stable"))
}
}
if v := vpcPeeringConnection.RequesterVpcInfo; v != nil && requesterPeeringConnectionOptions != nil {
if !vpcPeeringConnectionOptionsEqual(v.PeeringOptions, requesterPeeringConnectionOptions) {
return resource.RetryableError(errors.New("Requester Options not stable"))
}
}
return nil
})
if err != nil {
return fmt.Errorf("error waiting for EC2 VPC Peering Connection (%s) Options update: %w", d.Id(), err)
}
return nil
}
func vpcPeeringConnectionOptionsEqual(o1 *ec2.VpcPeeringConnectionOptionsDescription, o2 *ec2.PeeringConnectionOptionsRequest) bool {
return aws.BoolValue(o1.AllowDnsResolutionFromRemoteVpc) == aws.BoolValue(o2.AllowDnsResolutionFromRemoteVpc) &&
aws.BoolValue(o1.AllowEgressFromLocalClassicLinkToRemoteVpc) == aws.BoolValue(o2.AllowEgressFromLocalClassicLinkToRemoteVpc) &&
aws.BoolValue(o1.AllowEgressFromLocalVpcToRemoteClassicLink) == aws.BoolValue(o2.AllowEgressFromLocalVpcToRemoteClassicLink)
}
func expandPeeringConnectionOptionsRequest(tfMap map[string]interface{}, crossRegionPeering bool) *ec2.PeeringConnectionOptionsRequest {
if tfMap == nil {
return nil
}
apiObject := &ec2.PeeringConnectionOptionsRequest{}
if v, ok := tfMap["allow_remote_vpc_dns_resolution"].(bool); ok {
apiObject.AllowDnsResolutionFromRemoteVpc = aws.Bool(v)
}
if !crossRegionPeering {
if v, ok := tfMap["allow_classic_link_to_remote_vpc"].(bool); ok {
apiObject.AllowEgressFromLocalClassicLinkToRemoteVpc = aws.Bool(v)
}
if v, ok := tfMap["allow_vpc_to_remote_classic_link"].(bool); ok {
apiObject.AllowEgressFromLocalVpcToRemoteClassicLink = aws.Bool(v)
}
}
return apiObject
}
func flattenVPCPeeringConnectionOptionsDescription(apiObject *ec2.VpcPeeringConnectionOptionsDescription) map[string]interface{} {
if apiObject == nil {
return nil
}
tfMap := map[string]interface{}{}
if v := apiObject.AllowDnsResolutionFromRemoteVpc; v != nil {
tfMap["allow_remote_vpc_dns_resolution"] = aws.BoolValue(v)
}
if v := apiObject.AllowEgressFromLocalClassicLinkToRemoteVpc; v != nil {
tfMap["allow_classic_link_to_remote_vpc"] = aws.BoolValue(v)
}
if v := apiObject.AllowEgressFromLocalVpcToRemoteClassicLink; v != nil {
tfMap["allow_vpc_to_remote_classic_link"] = aws.BoolValue(v)
}
return tfMap
}