-
Notifications
You must be signed in to change notification settings - Fork 9.2k
/
resource_aws_vpn_gateway.go
340 lines (285 loc) · 8.39 KB
/
resource_aws_vpn_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
package aws
import (
"fmt"
"log"
"strconv"
"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 resourceAwsVpnGateway() *schema.Resource {
return &schema.Resource{
Create: resourceAwsVpnGatewayCreate,
Read: resourceAwsVpnGatewayRead,
Update: resourceAwsVpnGatewayUpdate,
Delete: resourceAwsVpnGatewayDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"availability_zone": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"amazon_side_asn": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
ValidateFunc: validateAmazonSideAsn,
},
"vpc_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"tags": tagsSchema(),
},
}
}
func resourceAwsVpnGatewayCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
createOpts := &ec2.CreateVpnGatewayInput{
AvailabilityZone: aws.String(d.Get("availability_zone").(string)),
Type: aws.String("ipsec.1"),
}
if asn, ok := d.GetOk("amazon_side_asn"); ok {
i, err := strconv.ParseInt(asn.(string), 10, 64)
if err != nil {
return err
}
createOpts.AmazonSideAsn = aws.Int64(i)
}
// Create the VPN gateway
log.Printf("[DEBUG] Creating VPN gateway")
resp, err := conn.CreateVpnGateway(createOpts)
if err != nil {
return fmt.Errorf("Error creating VPN gateway: %s", err)
}
// Get the ID and store it
vpnGateway := resp.VpnGateway
d.SetId(*vpnGateway.VpnGatewayId)
log.Printf("[INFO] VPN Gateway ID: %s", *vpnGateway.VpnGatewayId)
// Attach the VPN gateway to the correct VPC
return resourceAwsVpnGatewayUpdate(d, meta)
}
func resourceAwsVpnGatewayRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
resp, err := conn.DescribeVpnGateways(&ec2.DescribeVpnGatewaysInput{
VpnGatewayIds: []*string{aws.String(d.Id())},
})
if err != nil {
if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidVpnGatewayID.NotFound" {
d.SetId("")
return nil
} else {
log.Printf("[ERROR] Error finding VpnGateway: %s", err)
return err
}
}
vpnGateway := resp.VpnGateways[0]
if vpnGateway == nil || *vpnGateway.State == "deleted" {
// Seems we have lost our VPN gateway
d.SetId("")
return nil
}
vpnAttachment := vpnGatewayGetAttachment(vpnGateway)
if len(vpnGateway.VpcAttachments) == 0 || *vpnAttachment.State == "detached" {
// Gateway exists but not attached to the VPC
d.Set("vpc_id", "")
} else {
d.Set("vpc_id", *vpnAttachment.VpcId)
}
if vpnGateway.AvailabilityZone != nil && *vpnGateway.AvailabilityZone != "" {
d.Set("availability_zone", vpnGateway.AvailabilityZone)
}
d.Set("amazon_side_asn", strconv.FormatInt(aws.Int64Value(vpnGateway.AmazonSideAsn), 10))
d.Set("tags", tagsToMap(vpnGateway.Tags))
return nil
}
func resourceAwsVpnGatewayUpdate(d *schema.ResourceData, meta interface{}) error {
if d.HasChange("vpc_id") {
// If we're already attached, detach it first
if err := resourceAwsVpnGatewayDetach(d, meta); err != nil {
return err
}
// Attach the VPN gateway to the new vpc
if err := resourceAwsVpnGatewayAttach(d, meta); err != nil {
return err
}
}
conn := meta.(*AWSClient).ec2conn
if err := setTags(conn, d); err != nil {
return err
}
d.SetPartial("tags")
return resourceAwsVpnGatewayRead(d, meta)
}
func resourceAwsVpnGatewayDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
// Detach if it is attached
if err := resourceAwsVpnGatewayDetach(d, meta); err != nil {
return err
}
log.Printf("[INFO] Deleting VPN gateway: %s", d.Id())
return resource.Retry(5*time.Minute, func() *resource.RetryError {
_, err := conn.DeleteVpnGateway(&ec2.DeleteVpnGatewayInput{
VpnGatewayId: aws.String(d.Id()),
})
if err == nil {
return nil
}
ec2err, ok := err.(awserr.Error)
if !ok {
return resource.RetryableError(err)
}
switch ec2err.Code() {
case "InvalidVpnGatewayID.NotFound":
return nil
case "IncorrectState":
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
})
}
func resourceAwsVpnGatewayAttach(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
if d.Get("vpc_id").(string) == "" {
log.Printf(
"[DEBUG] Not attaching VPN Gateway '%s' as no VPC ID is set",
d.Id())
return nil
}
log.Printf(
"[INFO] Attaching VPN Gateway '%s' to VPC '%s'",
d.Id(),
d.Get("vpc_id").(string))
req := &ec2.AttachVpnGatewayInput{
VpnGatewayId: aws.String(d.Id()),
VpcId: aws.String(d.Get("vpc_id").(string)),
}
err := resource.Retry(1*time.Minute, func() *resource.RetryError {
_, err := conn.AttachVpnGateway(req)
if err != nil {
if isAWSErr(err, "InvalidVpnGatewayID.NotFound", "") {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return err
}
// Wait for it to be fully attached before continuing
log.Printf("[DEBUG] Waiting for VPN gateway (%s) to attach", d.Id())
stateConf := &resource.StateChangeConf{
Pending: []string{"detached", "attaching"},
Target: []string{"attached"},
Refresh: vpnGatewayAttachStateRefreshFunc(conn, d.Id(), "available"),
Timeout: 10 * time.Minute,
}
if _, err := stateConf.WaitForState(); err != nil {
return fmt.Errorf(
"Error waiting for VPN gateway (%s) to attach: %s",
d.Id(), err)
}
return nil
}
func resourceAwsVpnGatewayDetach(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 VPN Gateway '%s' as no VPC ID is set",
d.Id())
return nil
}
log.Printf(
"[INFO] Detaching VPN Gateway '%s' from VPC '%s'",
d.Id(),
vpcID.(string))
wait := true
_, err := conn.DetachVpnGateway(&ec2.DetachVpnGatewayInput{
VpnGatewayId: aws.String(d.Id()),
VpcId: aws.String(vpcID.(string)),
})
if err != nil {
ec2err, ok := err.(awserr.Error)
if ok {
if ec2err.Code() == "InvalidVpnGatewayID.NotFound" {
err = nil
wait = false
} else if ec2err.Code() == "InvalidVpnGatewayAttachment.NotFound" {
err = nil
wait = false
}
}
if err != nil {
return err
}
}
if !wait {
return nil
}
// Wait for it to be fully detached before continuing
log.Printf("[DEBUG] Waiting for VPN gateway (%s) to detach", d.Id())
stateConf := &resource.StateChangeConf{
Pending: []string{"attached", "detaching", "available"},
Target: []string{"detached"},
Refresh: vpnGatewayAttachStateRefreshFunc(conn, d.Id(), "detached"),
Timeout: 10 * time.Minute,
}
if _, err := stateConf.WaitForState(); err != nil {
return fmt.Errorf(
"Error waiting for vpn gateway (%s) to detach: %s",
d.Id(), err)
}
return nil
}
// vpnGatewayAttachStateRefreshFunc returns a resource.StateRefreshFunc that is used to watch
// the state of a VPN gateway's attachment
func vpnGatewayAttachStateRefreshFunc(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.DescribeVpnGateways(&ec2.DescribeVpnGatewaysInput{
VpnGatewayIds: []*string{aws.String(id)},
})
if err != nil {
if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidVpnGatewayID.NotFound" {
resp = nil
} else {
log.Printf("[ERROR] Error on VpnGatewayStateRefresh: %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
}
vpnGateway := resp.VpnGateways[0]
if len(vpnGateway.VpcAttachments) == 0 {
// No attachments, we're detached
return vpnGateway, "detached", nil
}
vpnAttachment := vpnGatewayGetAttachment(vpnGateway)
return vpnGateway, *vpnAttachment.State, nil
}
}
func vpnGatewayGetAttachment(vgw *ec2.VpnGateway) *ec2.VpcAttachment {
for _, v := range vgw.VpcAttachments {
if *v.State == "attached" {
return v
}
}
return &ec2.VpcAttachment{State: aws.String("detached")}
}