-
Notifications
You must be signed in to change notification settings - Fork 127
/
Copy pathrecord.go
534 lines (493 loc) · 15.5 KB
/
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
529
530
531
532
533
534
package domain
import (
"context"
"errors"
"fmt"
"strings"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
domain "github.com/scaleway/scaleway-sdk-go/api/domain/v2beta1"
"github.com/scaleway/scaleway-sdk-go/scw"
"github.com/scaleway/terraform-provider-scaleway/v2/internal/httperrors"
"github.com/scaleway/terraform-provider-scaleway/v2/internal/locality"
"github.com/scaleway/terraform-provider-scaleway/v2/internal/services/account"
"github.com/scaleway/terraform-provider-scaleway/v2/internal/verify"
)
var changeKeys = []string{
"geo_ip",
"name",
"data",
"priority",
"ttl",
"type",
"http_service",
"weighted",
"view",
"dns_zone",
"keep_empty_zone",
}
func ResourceRecord() *schema.Resource {
return &schema.Resource{
CreateContext: resourceRecordCreate,
ReadContext: resourceDomainRecordRead,
UpdateContext: resourceDomainRecordUpdate,
DeleteContext: resourceDomainRecordDelete,
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(defaultDomainRecordTimeout),
Read: schema.DefaultTimeout(defaultDomainRecordTimeout),
Update: schema.DefaultTimeout(defaultDomainRecordTimeout),
Delete: schema.DefaultTimeout(defaultDomainRecordTimeout),
Default: schema.DefaultTimeout(defaultDomainRecordTimeout),
},
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
},
SchemaVersion: 0,
Schema: map[string]*schema.Schema{
"dns_zone": {
Type: schema.TypeString,
Description: "The zone you want to add the record in",
Required: true,
ForceNew: true,
},
"keep_empty_zone": {
Type: schema.TypeBool,
Description: "When destroy a resource record, if a zone have only NS, delete the zone",
Optional: true,
Default: false,
},
"root_zone": {
Type: schema.TypeBool,
Description: "Does the DNS zone is the root zone or not",
Computed: true,
},
"name": {
Type: schema.TypeString,
Description: "The name of the record",
ForceNew: true,
Optional: true,
StateFunc: func(val interface{}) string {
value := val.(string)
if value == "@" {
return ""
}
return value
},
},
"type": {
Type: schema.TypeString,
Description: "The type of the record",
ValidateDiagFunc: verify.ValidateEnum[domain.RecordType](),
ForceNew: true,
Required: true,
},
"data": {
Type: schema.TypeString,
Description: "The data of the record",
Required: true,
},
"ttl": {
Type: schema.TypeInt,
Description: "The ttl of the record",
Optional: true,
Default: 3600,
ValidateFunc: validation.IntBetween(60, 2592000),
},
"priority": {
Type: schema.TypeInt,
Description: "The priority of the record",
Optional: true,
Computed: true,
ValidateFunc: validation.IntAtLeast(0),
},
"geo_ip": {
Type: schema.TypeList,
Description: "Return record based on client localisation",
Optional: true,
MaxItems: 1,
ConflictsWith: []string{"view", "http_service", "weighted"},
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"matches": {
Type: schema.TypeList,
Description: "The list of matches",
MinItems: 1,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"countries": {
Type: schema.TypeList,
Optional: true,
MinItems: 1,
Description: "List of countries (eg: FR for France, US for the United States, GB for Great Britain...). List of all countries code: https://api.scaleway.com/domain-private/v2beta1/countries",
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validation.StringLenBetween(2, 2),
},
},
"continents": {
Type: schema.TypeList,
Optional: true,
MinItems: 1,
Description: "List of continents (eg: EU for Europe, NA for North America, AS for Asia...). List of all continents code: https://api.scaleway.com/domain-private/v2beta1/continents",
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validation.StringLenBetween(2, 2),
},
},
"data": {
Type: schema.TypeString,
Description: "The data of the match result",
Required: true,
},
},
},
},
},
},
},
"http_service": {
Type: schema.TypeList,
Description: "Return record based on client localisation",
Optional: true,
MaxItems: 1,
ConflictsWith: []string{"geo_ip", "view", "weighted"},
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"ips": {
Type: schema.TypeList,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validation.IsIPAddress,
},
Required: true,
MinItems: 1,
Description: "IPs to check",
},
"must_contain": {
Type: schema.TypeString,
Required: true,
Description: "Text to search",
},
"url": {
Type: schema.TypeString,
ValidateFunc: validation.IsURLWithHTTPorHTTPS,
Required: true,
Description: "URL to match the must_contain text to validate an IP",
},
"user_agent": {
Type: schema.TypeString,
Optional: true,
Description: "User-agent used when checking the URL",
},
"strategy": {
Type: schema.TypeString,
Required: true,
Description: "Strategy to return an IP from the IPs list",
ValidateDiagFunc: verify.ValidateEnum[domain.RecordHTTPServiceConfigStrategy](),
},
},
},
},
"view": {
Type: schema.TypeList,
Description: "Return record based on client subnet",
Optional: true,
ConflictsWith: []string{"geo_ip", "http_service", "weighted"},
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"subnet": {
Type: schema.TypeString,
Description: "The subnet of the view",
Required: true,
ValidateFunc: validation.IsCIDR,
},
"data": {
Type: schema.TypeString,
Description: "The data of the view record",
Required: true,
},
},
},
},
"weighted": {
Type: schema.TypeList,
Description: "Return record based on weight",
Optional: true,
ConflictsWith: []string{"geo_ip", "http_service", "view"},
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"ip": {
Type: schema.TypeString,
Description: "The weighted IP",
Required: true,
ValidateFunc: validation.IsIPAddress,
},
"weight": {
Type: schema.TypeInt,
Description: "The weight of the IP",
Required: true,
ValidateFunc: validation.IntAtLeast(0),
},
},
},
},
"fqdn": {
Type: schema.TypeString,
Description: "The FQDN of the record",
Computed: true,
},
"project_id": account.ProjectIDSchema(),
},
}
}
func resourceRecordCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
domainAPI := NewDomainAPI(m)
dnsZone := d.Get("dns_zone").(string)
geoIP, okGeoIP := d.GetOk("geo_ip")
recordType := domain.RecordType(d.Get("type").(string))
recordData := d.Get("data").(string)
record := &domain.Record{
Data: recordData,
Name: d.Get("name").(string),
TTL: uint32(d.Get("ttl").(int)),
Type: recordType,
Priority: uint32(d.Get("priority").(int)),
GeoIPConfig: expandDomainGeoIPConfig(d.Get("data").(string), geoIP, okGeoIP),
HTTPServiceConfig: expandDomainHTTPService(d.GetOk("http_service")),
WeightedConfig: expandDomainWeighted(d.GetOk("weighted")),
ViewConfig: expandDomainView(d.GetOk("view")),
Comment: nil,
}
_, err := domainAPI.UpdateDNSZoneRecords(&domain.UpdateDNSZoneRecordsRequest{
DNSZone: dnsZone,
Changes: []*domain.RecordChange{
{
Add: &domain.RecordChangeAdd{
Records: []*domain.Record{record},
},
},
},
ReturnAllRecords: scw.BoolPtr(false),
})
if err != nil {
return diag.FromErr(err)
}
record, err = waitForDNSRecordExist(ctx, domainAPI, dnsZone, record.Name, record.Type, d.Timeout(schema.TimeoutCreate))
if err != nil {
return diag.FromErr(err)
}
tflog.Debug(ctx, fmt.Sprintf("DNS ZONE domain: %s record: %s, type: %s",
dnsZone,
record.Name,
record.Type))
dnsZoneData, err := domainAPI.ListDNSZoneRecords(&domain.ListDNSZoneRecordsRequest{
DNSZone: dnsZone,
Name: d.Get("name").(string),
Type: recordType,
}, scw.WithAllPages(), scw.WithContext(ctx))
if err != nil {
return diag.FromErr(err)
}
currentRecord, err := getRecordFromTypeAndData(recordType, recordData, dnsZoneData.Records)
if err != nil {
return diag.FromErr(err)
}
recordID := fmt.Sprintf("%s/%s", dnsZone, currentRecord.ID)
d.SetId(recordID)
tflog.Debug(ctx, fmt.Sprintf("record ID[%s]", recordID))
return resourceDomainRecordRead(ctx, d, m)
}
func resourceDomainRecordRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
domainAPI := NewDomainAPI(m)
var record *domain.Record
var dnsZone string
var projectID string
var err error
currentData := d.Get("data")
// check if this is an inline import. Like: "terraform import scaleway_domain_record.www subdomain.domain.tld/11111111-1111-1111-1111-111111111111"
if strings.Contains(d.Id(), "/") {
tab := strings.Split(d.Id(), "/")
if len(tab) != 2 {
return diag.FromErr(fmt.Errorf("cant parse record id: %s", d.Id()))
}
dnsZone = tab[0]
recordID := tab[1]
res, err := domainAPI.ListDNSZoneRecords(&domain.ListDNSZoneRecordsRequest{
DNSZone: dnsZone,
ID: &recordID,
}, scw.WithAllPages(), scw.WithContext(ctx))
if err != nil {
if httperrors.Is404(err) || httperrors.Is403(err) {
d.SetId("")
return nil
}
return diag.FromErr(err)
}
if len(res.Records) > 0 {
record = res.Records[0]
}
} else {
dnsZone = d.Get("dns_zone").(string)
recordTypeRaw, recordTypeExist := d.GetOk("type")
if !recordTypeExist {
return diag.FromErr(errors.New("record type not found"))
}
recordType := domain.RecordType(recordTypeRaw.(string))
if recordType == domain.RecordTypeUnknown {
return diag.FromErr(errors.New("record type unknow"))
}
idRecord := locality.ExpandID(d.Id())
res, err := domainAPI.ListDNSZoneRecords(&domain.ListDNSZoneRecordsRequest{
DNSZone: dnsZone,
Name: d.Get("name").(string),
Type: recordType,
ID: &idRecord,
}, scw.WithAllPages(), scw.WithContext(ctx))
if err != nil {
if httperrors.Is404(err) || httperrors.Is403(err) {
d.SetId("")
return nil
}
return diag.FromErr(err)
}
if len(res.Records) > 0 {
record = res.Records[0]
}
}
if record == nil {
d.SetId("")
return nil
}
dnsZones, err := domainAPI.ListDNSZones(&domain.ListDNSZonesRequest{DNSZones: []string{dnsZone}}, scw.WithAllPages(), scw.WithContext(ctx))
if err != nil {
if httperrors.Is404(err) || httperrors.Is403(err) {
d.SetId("")
return nil
}
return diag.FromErr(err)
}
// get the default first record
projectID = dnsZones.DNSZones[0].ProjectID
_ = d.Set("root_zone", dnsZones.DNSZones[0].Subdomain == "")
// retrieve data from record
if len(currentData.(string)) == 0 {
currentData = flattenDomainData(record.Data, record.Type).(string)
}
d.SetId(record.ID)
_ = d.Set("dns_zone", dnsZone)
_ = d.Set("name", record.Name)
_ = d.Set("type", record.Type.String())
_ = d.Set("data", currentData.(string))
_ = d.Set("ttl", int(record.TTL))
_ = d.Set("priority", int(record.Priority))
_ = d.Set("geo_ip", flattenDomainGeoIP(record.GeoIPConfig))
_ = d.Set("http_service", flattenDomainHTTPService(record.HTTPServiceConfig))
_ = d.Set("weighted", flattenDomainWeighted(record.WeightedConfig))
_ = d.Set("view", flattenDomainView(record.ViewConfig))
_ = d.Set("project_id", projectID)
if record.Name == "" || record.Name == "@" {
_ = d.Set("fqdn", dnsZone)
} else {
_ = d.Set("fqdn", fmt.Sprintf("%s.%s", record.Name, dnsZone))
}
return nil
}
func resourceDomainRecordUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
if !d.HasChanges(changeKeys...) {
return resourceDomainRecordRead(ctx, d, m)
}
domainAPI := NewDomainAPI(m)
req := &domain.UpdateDNSZoneRecordsRequest{
DNSZone: d.Get("dns_zone").(string),
ReturnAllRecords: scw.BoolPtr(false),
}
geoIP, okGeoIP := d.GetOk("geo_ip")
record := &domain.Record{
Name: d.Get("name").(string),
Data: d.Get("data").(string),
Priority: uint32(d.Get("priority").(int)),
TTL: uint32(d.Get("ttl").(int)),
Type: domain.RecordType(d.Get("type").(string)),
GeoIPConfig: expandDomainGeoIPConfig(d.Get("data").(string), geoIP, okGeoIP),
HTTPServiceConfig: expandDomainHTTPService(d.GetOk("http_service")),
WeightedConfig: expandDomainWeighted(d.GetOk("weighted")),
ViewConfig: expandDomainView(d.GetOk("view")),
}
req.Changes = []*domain.RecordChange{
{
Set: &domain.RecordChangeSet{
ID: scw.StringPtr(locality.ExpandID(d.Id())),
Records: []*domain.Record{record},
},
},
}
_, err := domainAPI.UpdateDNSZoneRecords(req)
if err != nil {
return diag.FromErr(err)
}
_, err = waitForDNSRecordExist(ctx, domainAPI, d.Get("dns_zone").(string), record.Name, record.Type, d.Timeout(schema.TimeoutUpdate))
if err != nil {
return diag.FromErr(err)
}
return resourceDomainRecordRead(ctx, d, m)
}
func resourceDomainRecordDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
domainAPI := NewDomainAPI(m)
recordID := locality.ExpandID(d.Id())
_, err := domainAPI.UpdateDNSZoneRecords(&domain.UpdateDNSZoneRecordsRequest{
DNSZone: d.Get("dns_zone").(string),
Changes: []*domain.RecordChange{
{
Delete: &domain.RecordChangeDelete{
ID: &recordID,
},
},
},
ReturnAllRecords: scw.BoolPtr(false),
})
if err != nil {
return diag.FromErr(err)
}
d.SetId("")
// for non-root zone, if the zone have only NS records, then delete the zone
if d.Get("keep_empty_zone").(bool) || d.Get("root_zone").(bool) {
return nil
}
res, err := domainAPI.ListDNSZoneRecords(&domain.ListDNSZoneRecordsRequest{
DNSZone: d.Get("dns_zone").(string),
})
if err != nil {
if httperrors.Is404(err) || httperrors.Is403(err) {
return nil
}
return diag.FromErr(err)
}
for _, r := range res.Records {
if r.Type != domain.RecordTypeNS {
// The zone isn't empty, keep it
return nil
}
tflog.Debug(ctx, fmt.Sprintf("record [%s], type [%s]", r.Name, r.Type))
}
_, err = waitForDNSZone(ctx, domainAPI, d.Get("dns_zone").(string), d.Timeout(schema.TimeoutDelete))
if err != nil {
if httperrors.Is404(err) || httperrors.Is403(err) {
return nil
}
return diag.FromErr(err)
}
_, err = domainAPI.DeleteDNSZone(&domain.DeleteDNSZoneRequest{
DNSZone: d.Get("dns_zone").(string),
ProjectID: d.Get("project_id").(string),
})
if err != nil {
if httperrors.Is404(err) || httperrors.Is403(err) {
return nil
}
return diag.FromErr(err)
}
return nil
}