forked from hashicorp/terraform
-
Notifications
You must be signed in to change notification settings - Fork 8
/
resource_aws_vpn_connection.go
357 lines (302 loc) · 9.71 KB
/
resource_aws_vpn_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
package aws
import (
"bytes"
"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/hashcode"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
)
func resourceAwsVpnConnection() *schema.Resource {
return &schema.Resource{
Create: resourceAwsVpnConnectionCreate,
Read: resourceAwsVpnConnectionRead,
Update: resourceAwsVpnConnectionUpdate,
Delete: resourceAwsVpnConnectionDelete,
Schema: map[string]*schema.Schema{
"vpn_gateway_id": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"customer_gateway_id": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"type": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"static_routes_only": &schema.Schema{
Type: schema.TypeBool,
Required: true,
ForceNew: true,
},
"tags": tagsSchema(),
// Begin read only attributes
"customer_gateway_configuration": &schema.Schema{
Type: schema.TypeString,
Computed: true,
Optional: true,
},
"routes": &schema.Schema{
Type: schema.TypeSet,
Computed: true,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"destination_cidr_block": &schema.Schema{
Type: schema.TypeString,
Computed: true,
Optional: true,
},
"source": &schema.Schema{
Type: schema.TypeString,
Computed: true,
Optional: true,
},
"state": &schema.Schema{
Type: schema.TypeString,
Computed: true,
Optional: true,
},
},
},
Set: func(v interface{}) int {
var buf bytes.Buffer
m := v.(map[string]interface{})
buf.WriteString(fmt.Sprintf("%s-", m["destination_cidr_block"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["source"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["state"].(string)))
return hashcode.String(buf.String())
},
},
"vgw_telemetry": &schema.Schema{
Type: schema.TypeSet,
Computed: true,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"accepted_route_count": &schema.Schema{
Type: schema.TypeInt,
Computed: true,
Optional: true,
},
"last_status_change": &schema.Schema{
Type: schema.TypeString,
Computed: true,
Optional: true,
},
"outside_ip_address": &schema.Schema{
Type: schema.TypeString,
Computed: true,
Optional: true,
},
"status": &schema.Schema{
Type: schema.TypeString,
Computed: true,
Optional: true,
},
"status_message": &schema.Schema{
Type: schema.TypeString,
Computed: true,
Optional: true,
},
},
},
Set: func(v interface{}) int {
var buf bytes.Buffer
m := v.(map[string]interface{})
buf.WriteString(fmt.Sprintf("%s-", m["outside_ip_address"].(string)))
return hashcode.String(buf.String())
},
},
},
}
}
func resourceAwsVpnConnectionCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
connectOpts := &ec2.VPNConnectionOptionsSpecification{
StaticRoutesOnly: aws.Bool(d.Get("static_routes_only").(bool)),
}
createOpts := &ec2.CreateVPNConnectionInput{
CustomerGatewayID: aws.String(d.Get("customer_gateway_id").(string)),
Options: connectOpts,
Type: aws.String(d.Get("type").(string)),
VPNGatewayID: aws.String(d.Get("vpn_gateway_id").(string)),
}
// Create the VPN Connection
log.Printf("[DEBUG] Creating vpn connection")
resp, err := conn.CreateVPNConnection(createOpts)
if err != nil {
return fmt.Errorf("Error creating vpn connection: %s", err)
}
// Store the ID
vpnConnection := resp.VPNConnection
d.SetId(*vpnConnection.VPNConnectionID)
log.Printf("[INFO] VPN connection ID: %s", *vpnConnection.VPNConnectionID)
// Wait for the connection to become available. This has an obscenely
// high default timeout because AWS VPN connections are notoriously
// slow at coming up or going down. There's also no point in checking
// more frequently than every ten seconds.
stateConf := &resource.StateChangeConf{
Pending: []string{"pending"},
Target: "available",
Refresh: vpnConnectionRefreshFunc(conn, *vpnConnection.VPNConnectionID),
Timeout: 30 * time.Minute,
Delay: 10 * time.Second,
MinTimeout: 10 * time.Second,
}
_, stateErr := stateConf.WaitForState()
if stateErr != nil {
return fmt.Errorf(
"Error waiting for VPN connection (%s) to become ready: %s",
*vpnConnection.VPNConnectionID, err)
}
// Create tags.
if err := setTags(conn, d); err != nil {
return err
}
// Read off the API to populate our RO fields.
return resourceAwsVpnConnectionRead(d, meta)
}
func vpnConnectionRefreshFunc(conn *ec2.EC2, connectionId string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
resp, err := conn.DescribeVPNConnections(&ec2.DescribeVPNConnectionsInput{
VPNConnectionIDs: []*string{aws.String(connectionId)},
})
if err != nil {
if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidVpnConnectionID.NotFound" {
resp = nil
} else {
log.Printf("Error on VPNConnectionRefresh: %s", err)
return nil, "", err
}
}
if resp == nil || len(resp.VPNConnections) == 0 {
return nil, "", nil
}
connection := resp.VPNConnections[0]
return connection, *connection.State, nil
}
}
func resourceAwsVpnConnectionRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
resp, err := conn.DescribeVPNConnections(&ec2.DescribeVPNConnectionsInput{
VPNConnectionIDs: []*string{aws.String(d.Id())},
})
if err != nil {
if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidVpnConnectionID.NotFound" {
d.SetId("")
return nil
} else {
log.Printf("[ERROR] Error finding VPN connection: %s", err)
return err
}
}
if len(resp.VPNConnections) != 1 {
return fmt.Errorf("[ERROR] Error finding VPN connection: %s", d.Id())
}
vpnConnection := resp.VPNConnections[0]
// Set attributes under the user's control.
d.Set("vpn_gateway_id", vpnConnection.VPNGatewayID)
d.Set("customer_gateway_id", vpnConnection.CustomerGatewayID)
d.Set("type", vpnConnection.Type)
d.Set("tags", tagsToMap(vpnConnection.Tags))
if vpnConnection.Options != nil {
if err := d.Set("static_routes_only", vpnConnection.Options.StaticRoutesOnly); err != nil {
return err
}
}
// Set read only attributes.
d.Set("customer_gateway_configuration", vpnConnection.CustomerGatewayConfiguration)
if err := d.Set("vgw_telemetry", telemetryToMapList(vpnConnection.VGWTelemetry)); err != nil {
return err
}
if vpnConnection.Routes != nil {
if err := d.Set("routes", routesToMapList(vpnConnection.Routes)); err != nil {
return err
}
}
return nil
}
func resourceAwsVpnConnectionUpdate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
// Update tags if required.
if err := setTags(conn, d); err != nil {
return err
}
d.SetPartial("tags")
return resourceAwsVpnConnectionRead(d, meta)
}
func resourceAwsVpnConnectionDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
_, err := conn.DeleteVPNConnection(&ec2.DeleteVPNConnectionInput{
VPNConnectionID: aws.String(d.Id()),
})
if err != nil {
if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidVpnConnectionID.NotFound" {
d.SetId("")
return nil
} else {
log.Printf("[ERROR] Error deleting VPN connection: %s", err)
return err
}
}
// These things can take quite a while to tear themselves down and any
// attempt to modify resources they reference (e.g. CustomerGateways or
// VPN Gateways) before deletion will result in an error. Furthermore,
// they don't just disappear. The go into "deleted" state. We need to
// wait to ensure any other modifications the user might make to their
// VPC stack can safely run.
stateConf := &resource.StateChangeConf{
Pending: []string{"deleting"},
Target: "deleted",
Refresh: vpnConnectionRefreshFunc(conn, d.Id()),
Timeout: 30 * time.Minute,
Delay: 10 * time.Second,
MinTimeout: 10 * time.Second,
}
_, stateErr := stateConf.WaitForState()
if stateErr != nil {
return fmt.Errorf(
"Error waiting for VPN connection (%s) to delete: %s", d.Id(), err)
}
return nil
}
// routesToMapList turns the list of routes into a list of maps.
func routesToMapList(routes []*ec2.VPNStaticRoute) []map[string]interface{} {
result := make([]map[string]interface{}, 0, len(routes))
for _, r := range routes {
staticRoute := make(map[string]interface{})
staticRoute["destination_cidr_block"] = *r.DestinationCIDRBlock
staticRoute["state"] = *r.State
if r.Source != nil {
staticRoute["source"] = *r.Source
}
result = append(result, staticRoute)
}
return result
}
// telemetryToMapList turns the VGW telemetry into a list of maps.
func telemetryToMapList(telemetry []*ec2.VGWTelemetry) []map[string]interface{} {
result := make([]map[string]interface{}, 0, len(telemetry))
for _, t := range telemetry {
vgw := make(map[string]interface{})
vgw["accepted_route_count"] = *t.AcceptedRouteCount
vgw["outside_ip_address"] = *t.OutsideIPAddress
vgw["status"] = *t.Status
vgw["status_message"] = *t.StatusMessage
// LastStatusChange is a time.Time(). Convert it into a string
// so it can be handled by schema's type system.
vgw["last_status_change"] = t.LastStatusChange.String()
result = append(result, vgw)
}
return result
}