-
Notifications
You must be signed in to change notification settings - Fork 630
/
resource_cloudflare_record.go
528 lines (438 loc) · 14.4 KB
/
resource_cloudflare_record.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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
package sdkv2provider
import (
"context"
"errors"
"fmt"
"net"
"strings"
"time"
"github.com/MakeNowJust/heredoc/v2"
cloudflare "github.com/cloudflare/cloudflare-go"
"github.com/cloudflare/terraform-provider-cloudflare/internal/consts"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func resourceCloudflareRecord() *schema.Resource {
return &schema.Resource{
CreateContext: resourceCloudflareRecordCreate,
ReadContext: resourceCloudflareRecordRead,
UpdateContext: resourceCloudflareRecordUpdate,
DeleteContext: resourceCloudflareRecordDelete,
Importer: &schema.ResourceImporter{
StateContext: resourceCloudflareRecordImport,
},
Description: heredoc.Doc(`Provides a Cloudflare record resource.`),
SchemaVersion: 3,
Schema: resourceCloudflareRecordSchema(),
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(30 * time.Second),
Update: schema.DefaultTimeout(30 * time.Second),
},
StateUpgraders: []schema.StateUpgrader{
{
Type: resourceCloudflareRecordV1().CoreConfigSchema().ImpliedType(),
Upgrade: resourceCloudflareRecordStateUpgradeV2,
Version: 1,
},
{
Type: resourceCloudflareRecordV2().CoreConfigSchema().ImpliedType(),
Upgrade: resourceCloudflareRecordStateUpgradeV3,
Version: 2,
},
},
}
}
func resourceCloudflareRecordCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client := meta.(*cloudflare.API)
zoneID := d.Get(consts.ZoneIDSchemaKey).(string)
newRecord := cloudflare.CreateDNSRecordParams{
Type: d.Get("type").(string),
Name: d.Get("name").(string),
}
proxied, proxiedOk := d.GetOkExists("proxied")
if proxiedOk {
newRecord.Proxied = cloudflare.BoolPtr(proxied.(bool))
}
value, valueOk := d.GetOk("value")
if valueOk {
newRecord.Content = value.(string)
}
content, contentOk := d.GetOk("content")
if contentOk {
newRecord.Content = content.(string)
}
data, dataOk := d.GetOk("data")
tflog.Debug(ctx, fmt.Sprintf("Data found in config: %#v", data))
newDataMap := make(map[string]interface{})
if dataOk {
dataMap := data.([]interface{})[0]
for id, value := range dataMap.(map[string]interface{}) {
newData, err := transformToCloudflareDNSData(newRecord.Type, id, value)
if err != nil {
return diag.FromErr(err)
} else if newData == nil {
continue
}
newDataMap[id] = newData
}
newRecord.Data = newDataMap
}
if priority, ok := d.GetOkExists("priority"); ok {
p := uint16(priority.(int))
newRecord.Priority = &p
}
if ttl, ok := d.GetOk("ttl"); ok {
if ttl.(int) != 1 && proxiedOk && *newRecord.Proxied {
return diag.FromErr(fmt.Errorf("error validating record %s: ttl must be set to 1 when `proxied` is true", newRecord.Name))
}
newRecord.TTL = ttl.(int)
}
if newRecord.Name == "" {
return diag.FromErr(fmt.Errorf("record on zone %s must not have an empty name (use @ for the zone apex)", zoneID))
}
// Validate value based on type
if err := validateRecordContent(newRecord.Type, newRecord.Content); err != nil {
return diag.FromErr(fmt.Errorf("error validating record content of %q: %w", newRecord.Name, err))
}
var proxiedVal *bool
if proxiedOk {
proxiedVal = newRecord.Proxied
} else {
proxiedVal = cloudflare.BoolPtr(false)
}
if comment, ok := d.GetOk("comment"); ok {
newRecord.Comment = comment.(string)
}
if tags, ok := d.GetOk("tags"); ok {
for _, tag := range tags.(*schema.Set).List() {
newRecord.Tags = append(newRecord.Tags, tag.(string))
}
}
// Validate type
if err := validateRecordType(newRecord.Type, *proxiedVal); err != nil {
return diag.FromErr(fmt.Errorf("error validating record type %q: %w", newRecord.Type, err))
}
tflog.Debug(ctx, fmt.Sprintf("Cloudflare Record create configuration: %#v", newRecord))
retry := retry.RetryContext(ctx, d.Timeout(schema.TimeoutCreate), func() *retry.RetryError {
r, err := client.CreateDNSRecord(ctx, cloudflare.ZoneIdentifier(zoneID), newRecord)
if err != nil {
if strings.Contains(err.Error(), "already exist") {
if d.Get("allow_overwrite").(bool) {
var r cloudflare.ListDNSRecordsParams
tflog.Debug(ctx, fmt.Sprintf("Cloudflare Record already exists however we are overwriting it"))
zone, _ := client.ZoneDetails(ctx, zoneID)
if d.Get("name").(string) == "@" || d.Get("name").(string) == zone.Name {
r = cloudflare.ListDNSRecordsParams{
Name: zone.Name,
Type: d.Get("type").(string),
}
} else {
r = cloudflare.ListDNSRecordsParams{
Name: d.Get("name").(string) + "." + zone.Name,
Type: d.Get("type").(string),
}
}
rs, _, _ := client.ListDNSRecords(ctx, cloudflare.ZoneIdentifier(zoneID), r)
if len(rs) != 1 {
return retry.RetryableError(fmt.Errorf("attempted to override existing record however didn't find an exact match"))
}
// Here we need to set the ID as the state will not have one and in order
// for Terraform to operate on it, we need an anchor.
d.SetId(rs[0].ID)
if updateErr := resourceCloudflareRecordUpdate(ctx, d, meta); updateErr != nil {
return retry.NonRetryableError(errors.New("failed to update record"))
}
return nil
}
return retry.RetryableError(fmt.Errorf("expected DNS record to not already be present but already exists"))
}
return retry.NonRetryableError(fmt.Errorf("failed to create DNS record: %w", err))
}
// In the event that the API returns an empty DNS Record, we verify that the
// ID returned is not the default ""
if r.ID == "" {
return retry.NonRetryableError(fmt.Errorf("failed to find record in Create response; Record was empty"))
}
d.SetId(r.ID)
resourceCloudflareRecordRead(ctx, d, meta)
return nil
})
if retry != nil {
return diag.FromErr(retry)
}
return nil
}
func resourceCloudflareRecordRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client := meta.(*cloudflare.API)
zoneID := d.Get(consts.ZoneIDSchemaKey).(string)
record, err := client.GetDNSRecord(ctx, cloudflare.ZoneIdentifier(zoneID), d.Id())
if err != nil {
var notFoundError *cloudflare.NotFoundError
if errors.As(err, ¬FoundError) {
tflog.Warn(ctx, fmt.Sprintf("Removing record from state because it's not found in API"))
d.SetId("")
return nil
}
return diag.FromErr(err)
}
tflog.Debug(ctx, fmt.Sprintf("Data found in config: %#v", record.Data))
readDataMap := make(map[string]interface{})
if record.Data != nil {
dataMap := record.Data.(map[string]interface{})
if dataMap != nil {
for id, value := range dataMap {
newData, err := transformToCloudflareDNSData(record.Type, id, value)
if err != nil {
return diag.FromErr(err)
} else if newData == nil {
continue
}
readDataMap[id] = newData
}
record.Data = []interface{}{readDataMap}
}
}
d.SetId(record.ID)
d.Set("hostname", record.Name)
d.Set("type", record.Type)
_, valueOk := d.GetOk("value")
if valueOk {
d.Set("value", record.Content)
}
_, contentOk := d.GetOk("content")
_, datatOk := d.GetOk("data")
if contentOk || datatOk {
d.Set("content", record.Content)
}
d.Set("ttl", record.TTL)
d.Set("proxied", record.Proxied)
d.Set("created_on", record.CreatedOn.Format(time.RFC3339Nano))
d.Set("data", record.Data)
d.Set("modified_on", record.ModifiedOn.Format(time.RFC3339Nano))
if err := d.Set("metadata", expandStringMap(record.Meta)); err != nil {
tflog.Warn(ctx, fmt.Sprintf("Error setting metadata: %s", err))
}
d.Set("proxiable", record.Proxiable)
d.Set("comment", record.Comment)
d.Set("tags", record.Tags)
if record.Priority != nil {
priority := record.Priority
p := *priority
d.Set("priority", int(p))
}
return nil
}
func resourceCloudflareRecordUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client := meta.(*cloudflare.API)
zoneID := d.Get(consts.ZoneIDSchemaKey).(string)
var contentValue string
value, valueOk := d.GetOk("value")
if valueOk {
contentValue = value.(string)
}
content, contentOk := d.GetOk("content")
if contentOk {
contentValue = content.(string)
}
updateRecord := cloudflare.UpdateDNSRecordParams{
ID: d.Id(),
Type: d.Get("type").(string),
Name: d.Get("name").(string),
Content: contentValue,
}
data, dataOk := d.GetOk("data")
tflog.Debug(ctx, fmt.Sprintf("Data found in config: %#v", data))
newDataMap := make(map[string]interface{})
if dataOk {
dataMap := data.([]interface{})[0]
for id, value := range dataMap.(map[string]interface{}) {
newData, err := transformToCloudflareDNSData(updateRecord.Type, id, value)
if err != nil {
return diag.FromErr(err)
} else if newData == nil {
continue
}
newDataMap[id] = newData
}
updateRecord.Data = newDataMap
}
if priority, ok := d.GetOkExists("priority"); ok {
p := uint16(priority.(int))
updateRecord.Priority = &p
}
proxied, proxiedOk := d.GetOkExists("proxied")
if proxiedOk {
updateRecord.Proxied = cloudflare.BoolPtr(proxied.(bool))
}
if ttl, ok := d.GetOk("ttl"); ok {
if ttl.(int) != 1 && proxiedOk && *updateRecord.Proxied {
return diag.FromErr(fmt.Errorf("error validating record %s: ttl must be set to 1 when `proxied` is true", updateRecord.Name))
}
updateRecord.TTL = ttl.(int)
}
comment, commentOk := d.GetOkExists("comment")
if commentOk {
updateRecord.Comment = cloudflare.StringPtr(comment.(string))
}
tags := []string{}
for _, tag := range d.Get("tags").(*schema.Set).List() {
tags = append(tags, tag.(string))
}
updateRecord.Tags = tags
tflog.Debug(ctx, fmt.Sprintf("Cloudflare Record update configuration: %#v", updateRecord))
retry := retry.RetryContext(ctx, d.Timeout(schema.TimeoutUpdate), func() *retry.RetryError {
updateRecord.ID = d.Id()
_, err := client.UpdateDNSRecord(ctx, cloudflare.ZoneIdentifier(zoneID), updateRecord)
if err != nil {
if strings.Contains(err.Error(), "already exist") {
return retry.RetryableError(fmt.Errorf("expected DNS record to not already be present but already exists"))
}
return retry.NonRetryableError(fmt.Errorf("failed to create DNS record: %w", err))
}
resourceCloudflareRecordRead(ctx, d, meta)
return nil
})
if retry != nil {
return diag.FromErr(retry)
}
return nil
}
func resourceCloudflareRecordDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client := meta.(*cloudflare.API)
zoneID := d.Get(consts.ZoneIDSchemaKey).(string)
tflog.Info(ctx, fmt.Sprintf("Deleting Cloudflare Record: %s, %s", zoneID, d.Id()))
err := client.DeleteDNSRecord(ctx, cloudflare.ZoneIdentifier(zoneID), d.Id())
if err != nil {
return diag.FromErr(fmt.Errorf("error deleting Cloudflare Record: %w", err))
}
return nil
}
func expandStringMap(inVal interface{}) map[string]string {
// although interface could hold anything
// we assume that it is either nil or a map of interface values
outVal := make(map[string]string)
if inVal == nil {
return outVal
}
for k, v := range inVal.(map[string]interface{}) {
strValue := fmt.Sprintf("%v", v)
outVal[k] = strValue
}
return outVal
}
func resourceCloudflareRecordImport(ctx context.Context, d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
client := meta.(*cloudflare.API)
// split the id so we can look up
idAttr := strings.SplitN(d.Id(), "/", 2)
var zoneID string
var recordID string
if len(idAttr) == 2 {
zoneID = idAttr[0]
recordID = idAttr[1]
} else {
return nil, fmt.Errorf("invalid id %q specified, should be in format \"zoneID/recordID\" for import", d.Id())
}
zone, err := client.ZoneDetails(ctx, zoneID)
if err != nil {
return nil, fmt.Errorf("failed to lookup zone details for %s: %w", zoneID, err)
}
record, err := client.GetDNSRecord(ctx, cloudflare.ZoneIdentifier(zoneID), recordID)
if err != nil {
return nil, fmt.Errorf("Unable to find record with ID %q: %w", d.Id(), err)
}
tflog.Info(ctx, fmt.Sprintf("Found record: %s", record.Name))
name := strings.TrimSuffix(record.Name, "."+zone.Name)
d.Set("name", name)
d.Set(consts.ZoneIDSchemaKey, zoneID)
d.SetId(recordID)
resourceCloudflareRecordRead(ctx, d, meta)
return []*schema.ResourceData{d}, nil
}
var dnsTypeIntFields = []string{
"algorithm",
"key_tag",
"type",
"usage",
"selector",
"matching_type",
"weight",
"priority",
"port",
"long_degrees",
"lat_degrees",
"long_minutes",
"lat_minutes",
"protocol",
"digest_type",
"order",
"preference",
}
var dnsTypeFloatFields = []string{
"size",
"altitude",
"precision_horz",
"precision_vert",
"long_seconds",
"lat_seconds",
}
func transformToCloudflareDNSData(recordType string, id string, value interface{}) (newValue interface{}, err error) {
switch {
case id == "flags":
switch {
case strings.ToUpper(recordType) == "SRV":
newValue, err = value.(string), nil
case strings.ToUpper(recordType) == "NAPTR":
newValue, err = value.(string), nil
case strings.ToUpper(recordType) == "CAA", strings.ToUpper(recordType) == "DNSKEY":
// this is required because "flags" is shared however, it comes from
// the API as a float64 but the Terraform internal type is string 😢.
switch value.(type) {
case float64:
newValue, err = fmt.Sprintf("%.0f", value.(float64)), nil
case string:
newValue, err = value.(string), nil
}
}
case contains(dnsTypeIntFields, id):
newValue, err = value, nil
case contains(dnsTypeFloatFields, id):
newValue, err = value, nil
default:
newValue, err = value.(string), nil
}
return
}
func suppressPriority(k, old, new string, d *schema.ResourceData) bool {
recordType := d.Get("type").(string)
if recordType != "MX" && recordType != "URI" {
return true
}
return false
}
func suppressTrailingDots(k, old, new string, d *schema.ResourceData) bool {
newTrimmed := strings.TrimSuffix(new, ".")
// Ensure to distinguish values consists of dots only.
if newTrimmed == "" {
return old == new
}
return strings.TrimSuffix(old, ".") == newTrimmed
}
func suppressMatchingIpv6(old, new string) bool {
oldIpv6 := net.ParseIP(old)
if oldIpv6 == nil || oldIpv6.To16() == nil {
return false
}
newIpv6 := net.ParseIP(new)
if newIpv6 == nil || newIpv6.To16() == nil {
return false
}
return oldIpv6.Equal(newIpv6)
}
func suppressContent(k, old, new string, d *schema.ResourceData) bool {
if suppressMatchingIpv6(old, new) {
return true
}
return suppressTrailingDots(k, old, new, d)
}