forked from hashicorp/terraform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_aws_vpc.go
407 lines (353 loc) · 9.84 KB
/
resource_aws_vpc.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
package aws
import (
"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/resource"
"github.com/hashicorp/terraform/helper/schema"
)
func resourceAwsVpc() *schema.Resource {
return &schema.Resource{
Create: resourceAwsVpcCreate,
Read: resourceAwsVpcRead,
Update: resourceAwsVpcUpdate,
Delete: resourceAwsVpcDelete,
Schema: map[string]*schema.Schema{
"cidr_block": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validateCIDRNetworkAddress,
},
"instance_tenancy": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"enable_dns_hostnames": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"enable_dns_support": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"enable_classiclink": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"main_route_table_id": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"default_network_acl_id": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"dhcp_options_id": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"default_security_group_id": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchema(),
},
}
}
func resourceAwsVpcCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
instance_tenancy := "default"
if v, ok := d.GetOk("instance_tenancy"); ok {
instance_tenancy = v.(string)
}
// Create the VPC
createOpts := &ec2.CreateVpcInput{
CidrBlock: aws.String(d.Get("cidr_block").(string)),
InstanceTenancy: aws.String(instance_tenancy),
}
log.Printf("[DEBUG] VPC create config: %#v", *createOpts)
vpcResp, err := conn.CreateVpc(createOpts)
if err != nil {
return fmt.Errorf("Error creating VPC: %s", err)
}
// Get the ID and store it
vpc := vpcResp.Vpc
d.SetId(*vpc.VpcId)
log.Printf("[INFO] VPC ID: %s", d.Id())
// Set partial mode and say that we setup the cidr block
d.Partial(true)
d.SetPartial("cidr_block")
// Wait for the VPC to become available
log.Printf(
"[DEBUG] Waiting for VPC (%s) to become available",
d.Id())
stateConf := &resource.StateChangeConf{
Pending: []string{"pending"},
Target: []string{"available"},
Refresh: VPCStateRefreshFunc(conn, d.Id()),
Timeout: 10 * time.Minute,
}
if _, err := stateConf.WaitForState(); err != nil {
return fmt.Errorf(
"Error waiting for VPC (%s) to become available: %s",
d.Id(), err)
}
// Update our attributes and return
return resourceAwsVpcUpdate(d, meta)
}
func resourceAwsVpcRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
// Refresh the VPC state
vpcRaw, _, err := VPCStateRefreshFunc(conn, d.Id())()
if err != nil {
return err
}
if vpcRaw == nil {
d.SetId("")
return nil
}
// VPC stuff
vpc := vpcRaw.(*ec2.Vpc)
vpcid := d.Id()
d.Set("cidr_block", vpc.CidrBlock)
d.Set("dhcp_options_id", vpc.DhcpOptionsId)
// Tags
d.Set("tags", tagsToMap(vpc.Tags))
// Attributes
attribute := "enableDnsSupport"
DescribeAttrOpts := &ec2.DescribeVpcAttributeInput{
Attribute: aws.String(attribute),
VpcId: aws.String(vpcid),
}
resp, err := conn.DescribeVpcAttribute(DescribeAttrOpts)
if err != nil {
return err
}
d.Set("enable_dns_support", *resp.EnableDnsSupport)
attribute = "enableDnsHostnames"
DescribeAttrOpts = &ec2.DescribeVpcAttributeInput{
Attribute: &attribute,
VpcId: &vpcid,
}
resp, err = conn.DescribeVpcAttribute(DescribeAttrOpts)
if err != nil {
return err
}
d.Set("enable_dns_hostnames", *resp.EnableDnsHostnames)
DescribeClassiclinkOpts := &ec2.DescribeVpcClassicLinkInput{
VpcIds: []*string{&vpcid},
}
// Classic Link is only available in regions that support EC2 Classic
respClassiclink, err := conn.DescribeVpcClassicLink(DescribeClassiclinkOpts)
if err != nil {
if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "UnsupportedOperation" {
log.Printf("[WARN] VPC Classic Link is not supported in this region")
} else {
return err
}
} else {
classiclink_enabled := false
for _, v := range respClassiclink.Vpcs {
if *v.VpcId == vpcid {
if v.ClassicLinkEnabled != nil {
classiclink_enabled = *v.ClassicLinkEnabled
}
break
}
}
d.Set("enable_classiclink", classiclink_enabled)
}
// Get the main routing table for this VPC
// Really Ugly need to make this better - rmenn
filter1 := &ec2.Filter{
Name: aws.String("association.main"),
Values: []*string{aws.String("true")},
}
filter2 := &ec2.Filter{
Name: aws.String("vpc-id"),
Values: []*string{aws.String(d.Id())},
}
DescribeRouteOpts := &ec2.DescribeRouteTablesInput{
Filters: []*ec2.Filter{filter1, filter2},
}
routeResp, err := conn.DescribeRouteTables(DescribeRouteOpts)
if err != nil {
return err
}
if v := routeResp.RouteTables; len(v) > 0 {
d.Set("main_route_table_id", *v[0].RouteTableId)
}
resourceAwsVpcSetDefaultNetworkAcl(conn, d)
resourceAwsVpcSetDefaultSecurityGroup(conn, d)
return nil
}
func resourceAwsVpcUpdate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
// Turn on partial mode
d.Partial(true)
vpcid := d.Id()
if d.HasChange("enable_dns_hostnames") {
val := d.Get("enable_dns_hostnames").(bool)
modifyOpts := &ec2.ModifyVpcAttributeInput{
VpcId: &vpcid,
EnableDnsHostnames: &ec2.AttributeBooleanValue{
Value: &val,
},
}
log.Printf(
"[INFO] Modifying enable_dns_support vpc attribute for %s: %#v",
d.Id(), modifyOpts)
if _, err := conn.ModifyVpcAttribute(modifyOpts); err != nil {
return err
}
d.SetPartial("enable_dns_support")
}
if d.HasChange("enable_dns_support") {
val := d.Get("enable_dns_support").(bool)
modifyOpts := &ec2.ModifyVpcAttributeInput{
VpcId: &vpcid,
EnableDnsSupport: &ec2.AttributeBooleanValue{
Value: &val,
},
}
log.Printf(
"[INFO] Modifying enable_dns_support vpc attribute for %s: %#v",
d.Id(), modifyOpts)
if _, err := conn.ModifyVpcAttribute(modifyOpts); err != nil {
return err
}
d.SetPartial("enable_dns_support")
}
if d.HasChange("enable_classiclink") {
val := d.Get("enable_classiclink").(bool)
if val {
modifyOpts := &ec2.EnableVpcClassicLinkInput{
VpcId: &vpcid,
}
log.Printf(
"[INFO] Modifying enable_classiclink vpc attribute for %s: %#v",
d.Id(), modifyOpts)
if _, err := conn.EnableVpcClassicLink(modifyOpts); err != nil {
return err
}
} else {
modifyOpts := &ec2.DisableVpcClassicLinkInput{
VpcId: &vpcid,
}
log.Printf(
"[INFO] Modifying enable_classiclink vpc attribute for %s: %#v",
d.Id(), modifyOpts)
if _, err := conn.DisableVpcClassicLink(modifyOpts); err != nil {
return err
}
}
d.SetPartial("enable_classiclink")
}
if err := setTags(conn, d); err != nil {
return err
} else {
d.SetPartial("tags")
}
d.Partial(false)
return resourceAwsVpcRead(d, meta)
}
func resourceAwsVpcDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
vpcID := d.Id()
DeleteVpcOpts := &ec2.DeleteVpcInput{
VpcId: &vpcID,
}
log.Printf("[INFO] Deleting VPC: %s", d.Id())
return resource.Retry(5*time.Minute, func() *resource.RetryError {
_, err := conn.DeleteVpc(DeleteVpcOpts)
if err == nil {
return nil
}
ec2err, ok := err.(awserr.Error)
if !ok {
return resource.NonRetryableError(err)
}
switch ec2err.Code() {
case "InvalidVpcID.NotFound":
return nil
case "DependencyViolation":
return resource.RetryableError(err)
}
return resource.NonRetryableError(fmt.Errorf("Error deleting VPC: %s", err))
})
}
// VPCStateRefreshFunc returns a resource.StateRefreshFunc that is used to watch
// a VPC.
func VPCStateRefreshFunc(conn *ec2.EC2, id string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
DescribeVpcOpts := &ec2.DescribeVpcsInput{
VpcIds: []*string{aws.String(id)},
}
resp, err := conn.DescribeVpcs(DescribeVpcOpts)
if err != nil {
if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidVpcID.NotFound" {
resp = nil
} else {
log.Printf("Error on VPCStateRefresh: %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
}
vpc := resp.Vpcs[0]
return vpc, *vpc.State, nil
}
}
func resourceAwsVpcSetDefaultNetworkAcl(conn *ec2.EC2, d *schema.ResourceData) error {
filter1 := &ec2.Filter{
Name: aws.String("default"),
Values: []*string{aws.String("true")},
}
filter2 := &ec2.Filter{
Name: aws.String("vpc-id"),
Values: []*string{aws.String(d.Id())},
}
DescribeNetworkACLOpts := &ec2.DescribeNetworkAclsInput{
Filters: []*ec2.Filter{filter1, filter2},
}
networkAclResp, err := conn.DescribeNetworkAcls(DescribeNetworkACLOpts)
if err != nil {
return err
}
if v := networkAclResp.NetworkAcls; len(v) > 0 {
d.Set("default_network_acl_id", v[0].NetworkAclId)
}
return nil
}
func resourceAwsVpcSetDefaultSecurityGroup(conn *ec2.EC2, d *schema.ResourceData) error {
filter1 := &ec2.Filter{
Name: aws.String("group-name"),
Values: []*string{aws.String("default")},
}
filter2 := &ec2.Filter{
Name: aws.String("vpc-id"),
Values: []*string{aws.String(d.Id())},
}
DescribeSgOpts := &ec2.DescribeSecurityGroupsInput{
Filters: []*ec2.Filter{filter1, filter2},
}
securityGroupResp, err := conn.DescribeSecurityGroups(DescribeSgOpts)
if err != nil {
return err
}
if v := securityGroupResp.SecurityGroups; len(v) > 0 {
d.Set("default_security_group_id", v[0].GroupId)
}
return nil
}