forked from hashicorp/terraform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_aws_route53_zone.go
316 lines (269 loc) · 7.92 KB
/
resource_aws_route53_zone.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
package aws
import (
"fmt"
"log"
"sort"
"strings"
"time"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/route53"
)
func resourceAwsRoute53Zone() *schema.Resource {
return &schema.Resource{
Create: resourceAwsRoute53ZoneCreate,
Read: resourceAwsRoute53ZoneRead,
Update: resourceAwsRoute53ZoneUpdate,
Delete: resourceAwsRoute53ZoneDelete,
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"comment": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Default: "Managed by Terraform",
},
"vpc_id": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"vpc_region": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"zone_id": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"delegation_set_id": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"name_servers": &schema.Schema{
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"tags": tagsSchema(),
},
}
}
func resourceAwsRoute53ZoneCreate(d *schema.ResourceData, meta interface{}) error {
r53 := meta.(*AWSClient).r53conn
req := &route53.CreateHostedZoneInput{
Name: aws.String(d.Get("name").(string)),
HostedZoneConfig: &route53.HostedZoneConfig{Comment: aws.String(d.Get("comment").(string))},
CallerReference: aws.String(time.Now().Format(time.RFC3339Nano)),
}
if v := d.Get("vpc_id"); v != "" {
req.VPC = &route53.VPC{
VPCId: aws.String(v.(string)),
VPCRegion: aws.String(meta.(*AWSClient).region),
}
if w := d.Get("vpc_region"); w != "" {
req.VPC.VPCRegion = aws.String(w.(string))
}
d.Set("vpc_region", req.VPC.VPCRegion)
}
if v, ok := d.GetOk("delegation_set_id"); ok {
req.DelegationSetId = aws.String(v.(string))
}
log.Printf("[DEBUG] Creating Route53 hosted zone: %s", *req.Name)
var err error
resp, err := r53.CreateHostedZone(req)
if err != nil {
return err
}
// Store the zone_id
zone := cleanZoneID(*resp.HostedZone.Id)
d.Set("zone_id", zone)
d.SetId(zone)
// Wait until we are done initializing
wait := resource.StateChangeConf{
Delay: 30 * time.Second,
Pending: []string{"PENDING"},
Target: []string{"INSYNC"},
Timeout: 10 * time.Minute,
MinTimeout: 2 * time.Second,
Refresh: func() (result interface{}, state string, err error) {
changeRequest := &route53.GetChangeInput{
Id: aws.String(cleanChangeID(*resp.ChangeInfo.Id)),
}
return resourceAwsGoRoute53Wait(r53, changeRequest)
},
}
_, err = wait.WaitForState()
if err != nil {
return err
}
return resourceAwsRoute53ZoneUpdate(d, meta)
}
func resourceAwsRoute53ZoneRead(d *schema.ResourceData, meta interface{}) error {
r53 := meta.(*AWSClient).r53conn
zone, err := r53.GetHostedZone(&route53.GetHostedZoneInput{Id: aws.String(d.Id())})
if err != nil {
// Handle a deleted zone
if r53err, ok := err.(awserr.Error); ok && r53err.Code() == "NoSuchHostedZone" {
d.SetId("")
return nil
}
return err
}
// In the import case this will be empty
if _, ok := d.GetOk("zone_id"); !ok {
d.Set("zone_id", d.Id())
}
if _, ok := d.GetOk("name"); !ok {
d.Set("name", zone.HostedZone.Name)
}
if !*zone.HostedZone.Config.PrivateZone {
ns := make([]string, len(zone.DelegationSet.NameServers))
for i := range zone.DelegationSet.NameServers {
ns[i] = *zone.DelegationSet.NameServers[i]
}
sort.Strings(ns)
if err := d.Set("name_servers", ns); err != nil {
return fmt.Errorf("[DEBUG] Error setting name servers for: %s, error: %#v", d.Id(), err)
}
} else {
ns, err := getNameServers(d.Id(), d.Get("name").(string), r53)
if err != nil {
return err
}
if err := d.Set("name_servers", ns); err != nil {
return fmt.Errorf("[DEBUG] Error setting name servers for: %s, error: %#v", d.Id(), err)
}
// In the import case we just associate it with the first VPC
if _, ok := d.GetOk("vpc_id"); !ok {
if len(zone.VPCs) > 1 {
return fmt.Errorf(
"Can't import a route53_zone with more than one VPC attachment")
}
if len(zone.VPCs) > 0 {
d.Set("vpc_id", zone.VPCs[0].VPCId)
d.Set("vpc_region", zone.VPCs[0].VPCRegion)
}
}
var associatedVPC *route53.VPC
for _, vpc := range zone.VPCs {
if *vpc.VPCId == d.Get("vpc_id") {
associatedVPC = vpc
break
}
}
if associatedVPC == nil {
return fmt.Errorf("[DEBUG] VPC: %v is not associated with Zone: %v", d.Get("vpc_id"), d.Id())
}
}
if zone.DelegationSet != nil && zone.DelegationSet.Id != nil {
d.Set("delegation_set_id", cleanDelegationSetId(*zone.DelegationSet.Id))
}
if zone.HostedZone != nil && zone.HostedZone.Config != nil && zone.HostedZone.Config.Comment != nil {
d.Set("comment", zone.HostedZone.Config.Comment)
}
// get tags
req := &route53.ListTagsForResourceInput{
ResourceId: aws.String(d.Id()),
ResourceType: aws.String("hostedzone"),
}
resp, err := r53.ListTagsForResource(req)
if err != nil {
return err
}
var tags []*route53.Tag
if resp.ResourceTagSet != nil {
tags = resp.ResourceTagSet.Tags
}
if err := d.Set("tags", tagsToMapR53(tags)); err != nil {
return err
}
return nil
}
func resourceAwsRoute53ZoneUpdate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).r53conn
d.Partial(true)
if d.HasChange("comment") {
zoneInput := route53.UpdateHostedZoneCommentInput{
Id: aws.String(d.Id()),
Comment: aws.String(d.Get("comment").(string)),
}
_, err := conn.UpdateHostedZoneComment(&zoneInput)
if err != nil {
return err
} else {
d.SetPartial("comment")
}
}
if err := setTagsR53(conn, d, "hostedzone"); err != nil {
return err
} else {
d.SetPartial("tags")
}
d.Partial(false)
return resourceAwsRoute53ZoneRead(d, meta)
}
func resourceAwsRoute53ZoneDelete(d *schema.ResourceData, meta interface{}) error {
r53 := meta.(*AWSClient).r53conn
log.Printf("[DEBUG] Deleting Route53 hosted zone: %s (ID: %s)",
d.Get("name").(string), d.Id())
_, err := r53.DeleteHostedZone(&route53.DeleteHostedZoneInput{Id: aws.String(d.Id())})
if err != nil {
if r53err, ok := err.(awserr.Error); ok && r53err.Code() == "NoSuchHostedZone" {
log.Printf("[DEBUG] No matching Route 53 Zone found for: %s, removing from state file", d.Id())
d.SetId("")
return nil
}
return err
}
return nil
}
func resourceAwsGoRoute53Wait(r53 *route53.Route53, ref *route53.GetChangeInput) (result interface{}, state string, err error) {
status, err := r53.GetChange(ref)
if err != nil {
return nil, "UNKNOWN", err
}
return true, *status.ChangeInfo.Status, nil
}
// cleanChangeID is used to remove the leading /change/
func cleanChangeID(ID string) string {
return cleanPrefix(ID, "/change/")
}
// cleanZoneID is used to remove the leading /hostedzone/
func cleanZoneID(ID string) string {
return cleanPrefix(ID, "/hostedzone/")
}
// cleanPrefix removes a string prefix from an ID
func cleanPrefix(ID, prefix string) string {
if strings.HasPrefix(ID, prefix) {
ID = strings.TrimPrefix(ID, prefix)
}
return ID
}
func getNameServers(zoneId string, zoneName string, r53 *route53.Route53) ([]string, error) {
resp, err := r53.ListResourceRecordSets(&route53.ListResourceRecordSetsInput{
HostedZoneId: aws.String(zoneId),
StartRecordName: aws.String(zoneName),
StartRecordType: aws.String("NS"),
})
if err != nil {
return nil, err
}
if len(resp.ResourceRecordSets) == 0 {
return nil, nil
}
ns := make([]string, len(resp.ResourceRecordSets[0].ResourceRecords))
for i := range resp.ResourceRecordSets[0].ResourceRecords {
ns[i] = *resp.ResourceRecordSets[0].ResourceRecords[i].Value
}
sort.Strings(ns)
return ns, nil
}