-
Notifications
You must be signed in to change notification settings - Fork 9.4k
/
Copy pathresource_aws_dx_gateway_association.go
385 lines (319 loc) · 13.4 KB
/
resource_aws_dx_gateway_association.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
package aws
import (
"errors"
"fmt"
"log"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/directconnect"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
const (
gatewayAssociationStateDeleted = "deleted"
)
func resourceAwsDxGatewayAssociation() *schema.Resource {
return &schema.Resource{
Create: resourceAwsDxGatewayAssociationCreate,
Read: resourceAwsDxGatewayAssociationRead,
Update: resourceAwsDxGatewayAssociationUpdate,
Delete: resourceAwsDxGatewayAssociationDelete,
Importer: &schema.ResourceImporter{
State: resourceAwsDxGatewayAssociationImport,
},
SchemaVersion: 1,
StateUpgraders: []schema.StateUpgrader{
{
Type: resourceAwsDxGatewayAssociationResourceV0().CoreConfigSchema().ImpliedType(),
Upgrade: resourceAwsDxGatewayAssociationStateUpgradeV0,
Version: 0,
},
},
Schema: map[string]*schema.Schema{
"allowed_prefixes": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"associated_gateway_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"associated_gateway_owner_account_id", "proposal_id", "vpn_gateway_id"},
},
"associated_gateway_owner_account_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validateAwsAccountId,
ConflictsWith: []string{"associated_gateway_id", "vpn_gateway_id"},
},
"associated_gateway_type": {
Type: schema.TypeString,
Computed: true,
},
"dx_gateway_association_id": {
Type: schema.TypeString,
Computed: true,
},
"dx_gateway_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"dx_gateway_owner_account_id": {
Type: schema.TypeString,
Computed: true,
},
"proposal_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ConflictsWith: []string{"associated_gateway_id", "vpn_gateway_id"},
},
"vpn_gateway_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ConflictsWith: []string{"associated_gateway_id", "associated_gateway_owner_account_id", "proposal_id"},
Deprecated: "use 'associated_gateway_id' argument instead",
},
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(15 * time.Minute),
Update: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(15 * time.Minute),
},
}
}
func resourceAwsDxGatewayAssociationCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).dxconn
dxgwId := d.Get("dx_gateway_id").(string)
gwIdRaw, gwIdOk := d.GetOk("associated_gateway_id")
vgwIdRaw, vgwIdOk := d.GetOk("vpn_gateway_id")
gwAcctIdRaw, gwAcctIdOk := d.GetOk("associated_gateway_owner_account_id")
proposalIdRaw, proposalIdOk := d.GetOk("proposal_id")
if gwAcctIdOk || proposalIdOk {
// Cross-account association.
if !(gwAcctIdOk && proposalIdOk) {
return fmt.Errorf("associated_gateway_owner_account_id and proposal_id must be configured")
}
} else if !(gwIdOk || vgwIdOk) {
return fmt.Errorf("either associated_gateway_owner_account_id and proposal_id or one of associated_gateway_id or vpn_gateway_id must be configured")
}
associationId := ""
if gwAcctIdOk {
req := &directconnect.AcceptDirectConnectGatewayAssociationProposalInput{
AssociatedGatewayOwnerAccount: aws.String(gwAcctIdRaw.(string)),
DirectConnectGatewayId: aws.String(dxgwId),
OverrideAllowedPrefixesToDirectConnectGateway: expandDxRouteFilterPrefixes(d.Get("allowed_prefixes").(*schema.Set)),
ProposalId: aws.String(proposalIdRaw.(string)),
}
log.Printf("[DEBUG] Accepting Direct Connect gateway association proposal: %#v", req)
resp, err := conn.AcceptDirectConnectGatewayAssociationProposal(req)
if err != nil {
return fmt.Errorf("error accepting Direct Connect gateway association proposal: %s", err)
}
// For historical reasons the resource ID isn't set to the association ID returned from the API.
associationId = aws.StringValue(resp.DirectConnectGatewayAssociation.AssociationId)
d.SetId(dxGatewayAssociationId(dxgwId, aws.StringValue(resp.DirectConnectGatewayAssociation.AssociatedGateway.Id)))
} else {
req := &directconnect.CreateDirectConnectGatewayAssociationInput{
AddAllowedPrefixesToDirectConnectGateway: expandDxRouteFilterPrefixes(d.Get("allowed_prefixes").(*schema.Set)),
DirectConnectGatewayId: aws.String(dxgwId),
}
gwId := ""
if gwIdOk {
gwId = gwIdRaw.(string)
req.GatewayId = aws.String(gwId)
} else {
gwId = vgwIdRaw.(string)
req.VirtualGatewayId = aws.String(gwId)
}
log.Printf("[DEBUG] Creating Direct Connect gateway association: %#v", req)
resp, err := conn.CreateDirectConnectGatewayAssociation(req)
if err != nil {
return fmt.Errorf("error creating Direct Connect gateway association: %s", err)
}
// For historical reasons the resource ID isn't set to the association ID returned from the API.
associationId = aws.StringValue(resp.DirectConnectGatewayAssociation.AssociationId)
d.SetId(dxGatewayAssociationId(dxgwId, gwId))
}
d.Set("dx_gateway_association_id", associationId)
if err := waitForDirectConnectGatewayAssociationAvailabilityOnCreate(conn, associationId, d.Timeout(schema.TimeoutCreate)); err != nil {
return fmt.Errorf("error waiting for Direct Connect gateway association (%s) to become available: %s", d.Id(), err)
}
return resourceAwsDxGatewayAssociationRead(d, meta)
}
func resourceAwsDxGatewayAssociationRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).dxconn
associationId := d.Get("dx_gateway_association_id").(string)
assocRaw, state, err := dxGatewayAssociationStateRefresh(conn, associationId)()
if err != nil {
return fmt.Errorf("error reading Direct Connect gateway association (%s): %s", d.Id(), err)
}
if state == gatewayAssociationStateDeleted {
log.Printf("[WARN] Direct Connect gateway association (%s) not found, removing from state", d.Id())
d.SetId("")
return nil
}
assoc := assocRaw.(*directconnect.GatewayAssociation)
err = d.Set("allowed_prefixes", flattenDxRouteFilterPrefixes(assoc.AllowedPrefixesToDirectConnectGateway))
if err != nil {
return fmt.Errorf("error setting allowed_prefixes: %s", err)
}
if _, ok := d.GetOk("vpn_gateway_id"); ok {
d.Set("vpn_gateway_id", assoc.VirtualGatewayId)
} else {
d.Set("associated_gateway_id", assoc.AssociatedGateway.Id)
}
d.Set("associated_gateway_owner_account_id", assoc.AssociatedGateway.OwnerAccount)
d.Set("associated_gateway_type", assoc.AssociatedGateway.Type)
d.Set("dx_gateway_association_id", assoc.AssociationId)
d.Set("dx_gateway_id", assoc.DirectConnectGatewayId)
d.Set("dx_gateway_owner_account_id", assoc.DirectConnectGatewayOwnerAccount)
return nil
}
func resourceAwsDxGatewayAssociationUpdate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).dxconn
_, gwIdOk := d.GetOk("associated_gateway_id")
_, vgwIdOk := d.GetOk("vpn_gateway_id")
if !gwIdOk && !vgwIdOk {
return errors.New("one of associated_gateway_id or vpn_gateway_id must be configured")
}
if d.HasChange("allowed_prefixes") {
associationId := d.Get("dx_gateway_association_id").(string)
oraw, nraw := d.GetChange("allowed_prefixes")
o := oraw.(*schema.Set)
n := nraw.(*schema.Set)
del := o.Difference(n)
add := n.Difference(o)
req := &directconnect.UpdateDirectConnectGatewayAssociationInput{
AddAllowedPrefixesToDirectConnectGateway: expandDxRouteFilterPrefixes(add),
AssociationId: aws.String(associationId),
RemoveAllowedPrefixesToDirectConnectGateway: expandDxRouteFilterPrefixes(del),
}
log.Printf("[DEBUG] Updating Direct Connect gateway association: %#v", req)
_, err := conn.UpdateDirectConnectGatewayAssociation(req)
if err != nil {
return fmt.Errorf("error updating Direct Connect gateway association (%s): %s", d.Id(), err)
}
if err := waitForDirectConnectGatewayAssociationAvailabilityOnUpdate(conn, associationId, d.Timeout(schema.TimeoutUpdate)); err != nil {
return fmt.Errorf("error waiting for Direct Connect gateway association (%s) to become available: %s", d.Id(), err)
}
}
return resourceAwsDxGatewayAssociationRead(d, meta)
}
func resourceAwsDxGatewayAssociationDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).dxconn
associationId := d.Get("dx_gateway_association_id").(string)
log.Printf("[DEBUG] Deleting Direct Connect gateway association: %s", d.Id())
_, err := conn.DeleteDirectConnectGatewayAssociation(&directconnect.DeleteDirectConnectGatewayAssociationInput{
AssociationId: aws.String(associationId),
})
if isAWSErr(err, directconnect.ErrCodeClientException, "No association exists") {
return nil
}
if err != nil {
return fmt.Errorf("error deleting Direct Connect gateway association: %s", err)
}
if err := waitForDirectConnectGatewayAssociationDeletion(conn, associationId, d.Timeout(schema.TimeoutDelete)); err != nil {
return fmt.Errorf("error waiting for Direct Connect gateway association (%s) to be deleted: %s", d.Id(), err)
}
return nil
}
func resourceAwsDxGatewayAssociationImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
parts := strings.Split(d.Id(), "/")
if len(parts) != 2 {
return []*schema.ResourceData{}, fmt.Errorf("Wrong format of resource: %s. Please follow 'dx-gw-id/gw-id'", d.Id())
}
dxgwId := parts[0]
gwId := parts[1]
id := dxGatewayAssociationId(dxgwId, gwId)
log.Printf("[DEBUG] Importing Direct Connect gateway association %s/%s", dxgwId, gwId)
conn := meta.(*AWSClient).dxconn
resp, err := conn.DescribeDirectConnectGatewayAssociations(&directconnect.DescribeDirectConnectGatewayAssociationsInput{
AssociatedGatewayId: aws.String(gwId),
DirectConnectGatewayId: aws.String(dxgwId),
})
if err != nil {
return nil, err
}
if n := len(resp.DirectConnectGatewayAssociations); n != 1 {
return nil, fmt.Errorf("Found %d Direct Connect gateway associations for %s, expected 1", n, id)
}
d.SetId(id)
d.Set("dx_gateway_id", resp.DirectConnectGatewayAssociations[0].DirectConnectGatewayId)
d.Set("dx_gateway_association_id", resp.DirectConnectGatewayAssociations[0].AssociationId)
return []*schema.ResourceData{d}, nil
}
func dxGatewayAssociationStateRefresh(conn *directconnect.DirectConnect, associationId string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
resp, err := conn.DescribeDirectConnectGatewayAssociations(&directconnect.DescribeDirectConnectGatewayAssociationsInput{
AssociationId: aws.String(associationId),
})
if err != nil {
return nil, "", err
}
n := len(resp.DirectConnectGatewayAssociations)
switch n {
case 0:
return "", gatewayAssociationStateDeleted, nil
case 1:
assoc := resp.DirectConnectGatewayAssociations[0]
if stateChangeError := aws.StringValue(assoc.StateChangeError); stateChangeError != "" {
id := dxGatewayAssociationId(
aws.StringValue(resp.DirectConnectGatewayAssociations[0].DirectConnectGatewayId),
aws.StringValue(resp.DirectConnectGatewayAssociations[0].AssociatedGateway.Id))
log.Printf("[INFO] Direct Connect gateway association (%s) state change error: %s", id, stateChangeError)
}
return assoc, aws.StringValue(assoc.AssociationState), nil
default:
return nil, "", fmt.Errorf("Found %d Direct Connect gateway associations for %s, expected 1", n, associationId)
}
}
}
// Terraform resource ID.
func dxGatewayAssociationId(dxgwId, gwId string) string {
return fmt.Sprintf("ga-%s%s", dxgwId, gwId)
}
func waitForDirectConnectGatewayAssociationAvailabilityOnCreate(conn *directconnect.DirectConnect, associationId string, timeout time.Duration) error {
stateConf := &resource.StateChangeConf{
Pending: []string{directconnect.GatewayAssociationStateAssociating},
Target: []string{directconnect.GatewayAssociationStateAssociated},
Refresh: dxGatewayAssociationStateRefresh(conn, associationId),
Timeout: timeout,
Delay: 10 * time.Second,
MinTimeout: 5 * time.Second,
}
_, err := stateConf.WaitForState()
return err
}
func waitForDirectConnectGatewayAssociationAvailabilityOnUpdate(conn *directconnect.DirectConnect, associationId string, timeout time.Duration) error {
stateConf := &resource.StateChangeConf{
Pending: []string{directconnect.GatewayAssociationStateUpdating},
Target: []string{directconnect.GatewayAssociationStateAssociated},
Refresh: dxGatewayAssociationStateRefresh(conn, associationId),
Timeout: timeout,
Delay: 10 * time.Second,
MinTimeout: 5 * time.Second,
}
_, err := stateConf.WaitForState()
return err
}
func waitForDirectConnectGatewayAssociationDeletion(conn *directconnect.DirectConnect, associationId string, timeout time.Duration) error {
stateConf := &resource.StateChangeConf{
Pending: []string{directconnect.GatewayAssociationStateDisassociating},
Target: []string{directconnect.GatewayAssociationStateDisassociated, gatewayAssociationStateDeleted},
Refresh: dxGatewayAssociationStateRefresh(conn, associationId),
Timeout: timeout,
Delay: 10 * time.Second,
MinTimeout: 5 * time.Second,
}
_, err := stateConf.WaitForState()
return err
}