This repository has been archived by the owner on Jun 9, 2023. It is now read-only.
forked from oracle/terraform-provider-oci
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dns_record_resource.go
390 lines (316 loc) · 10.5 KB
/
dns_record_resource.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
// Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved.
/*
A note to maintainers: this resource represents many different record types, indicated by the "rtype" value, the possible
rtype values dictate the format of data held in the rdata field. Many rtype's corresponding rdata values can be mutated
slightly by the service, examples are appending a "." to host-like records, or compressing AAAA IPV6 records. This can
require custom diff suppression logic per type. See "normalizeRData" function for implementation.
*/
package provider
import (
"context"
"fmt"
"github.com/hashicorp/terraform/helper/schema"
"net"
"regexp"
oci_dns "github.com/oracle/oci-go-sdk/dns"
)
func DnsRecordResource() *schema.Resource {
return &schema.Resource{
Timeouts: DefaultTimeout,
Create: createDnsRecord,
Read: readDnsRecord,
Update: updateDnsRecord,
Delete: deleteDnsRecord,
Schema: map[string]*schema.Schema{
// Required
"zone_name_or_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"compartment_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
// Optional
"domain": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"rdata": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
rtype := d.Get("rtype").(string)
return normalizeRData(rtype, new) == normalizeRData(rtype, old)
},
},
"rtype": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"ttl": {
Type: schema.TypeInt,
Optional: true,
},
// Computed
"is_protected": {
Type: schema.TypeBool,
Computed: true,
},
"record_hash": {
Type: schema.TypeString,
Computed: true,
},
"rrset_version": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func createDnsRecord(d *schema.ResourceData, m interface{}) error {
sync := &DnsRecordResourceCrud{}
sync.D = d
sync.Client = m.(*OracleClients).dnsClient
return CreateResource(d, sync)
}
func readDnsRecord(d *schema.ResourceData, m interface{}) error {
sync := &DnsRecordResourceCrud{}
sync.D = d
sync.Client = m.(*OracleClients).dnsClient
return ReadResource(sync)
}
func updateDnsRecord(d *schema.ResourceData, m interface{}) error {
sync := &DnsRecordResourceCrud{}
sync.D = d
sync.Client = m.(*OracleClients).dnsClient
return UpdateResource(d, sync)
}
func deleteDnsRecord(d *schema.ResourceData, m interface{}) error {
sync := &DnsRecordResourceCrud{}
sync.D = d
sync.Client = m.(*OracleClients).dnsClient
sync.DisableNotFoundRetries = true
return DeleteResource(d, sync)
}
type DnsRecordResourceCrud struct {
BaseCrud
Client *oci_dns.DnsClient
Res *oci_dns.Record
DisableNotFoundRetries bool
}
func (s *DnsRecordResourceCrud) ID() string {
return s.D.Get("record_hash").(string)
}
func (s *DnsRecordResourceCrud) Create() error {
request := oci_dns.PatchRRSetRequest{}
ro := oci_dns.RecordOperation{Operation: oci_dns.RecordOperationOperationAdd}
zoneNameOrId := s.D.Get("zone_name_or_id").(string)
request.ZoneNameOrId = &zoneNameOrId
domain := s.D.Get("domain").(string)
request.Domain = &domain
ro.Domain = &domain
rtype := s.D.Get("rtype").(string)
request.Rtype = &rtype
ro.Rtype = &rtype
if compartmentId, ok := s.D.GetOkExists("compartment_id"); ok {
tmp := compartmentId.(string)
request.CompartmentId = &tmp
}
if rdata, ok := s.D.GetOkExists("rdata"); ok {
tmp := rdata.(string)
ro.Rdata = &tmp
}
if ttl, ok := s.D.GetOkExists("ttl"); ok {
tmp := ttl.(int)
ro.Ttl = &tmp
}
request.Items = []oci_dns.RecordOperation{ro}
request.RequestMetadata.RetryPolicy = getRetryPolicy(s.DisableNotFoundRetries, "dns")
response, err := s.Client.PatchRRSet(context.Background(), request)
if err != nil {
return err
}
// The patch operation can add a record, but it returns ALL records, so there is no absolute way to map to this new item.
// Since there cant be duplicate records, try to match on the rType and rData that was just used
item, err := findItem(&response.Items, s.D)
if err != nil {
//PatchZoneRecords only returns 50 records we need to do a Get with pagination to make sure we can't find the item
err = s.Get()
if err == nil {
return nil
}
// Maybe there wasn't a match. That might happen if the service has transformed the rData in a way we don't support yet.
// Failing here would not write the record to the state file, but it would still exist server side. A better option
// is to write a partial statefile entry by transposing details from the RecordOperation into a new Record. This will
// include it as a new entry in the statefile, giving the user an opportunity to copy the transformed rdata value into their
// template, or for us to support that transform, after which subsequent refresh/applies will resolve the record.
// Also we don't know record hash yet, so derive a temporary id. It will get flushed when the record is resolved
tempId := *ro.Rtype + *ro.Rdata
item = &oci_dns.Record{Domain: ro.Domain, RecordHash: &tempId, Rdata: ro.Rdata, Rtype: ro.Rtype}
}
s.Res = item
return nil
}
func (s *DnsRecordResourceCrud) Get() error {
request := oci_dns.GetRRSetRequest{}
zoneNameOrId := s.D.Get("zone_name_or_id").(string)
request.ZoneNameOrId = &zoneNameOrId
domain := s.D.Get("domain").(string)
request.Domain = &domain
rtype := s.D.Get("rtype").(string)
request.Rtype = &rtype
if compartmentId, ok := s.D.GetOkExists("compartment_id"); ok {
tmp := compartmentId.(string)
request.CompartmentId = &tmp
}
request.RequestMetadata.RetryPolicy = getRetryPolicy(s.DisableNotFoundRetries, "dns")
var err error
for true {
response, err := s.Client.GetRRSet(context.Background(), request)
if err != nil {
return err
}
item, err := findItem(&response.Items, s.D)
if err == nil {
s.Res = item
return nil
}
if response.OpcNextPage == nil {
return err
}
request.Page = response.OpcNextPage
}
return err
}
func (s *DnsRecordResourceCrud) Update() error {
zoneNameOrId := s.D.Get("zone_name_or_id").(string)
domain := s.D.Get("domain").(string)
rtype := s.D.Get("rtype").(string)
request := oci_dns.PatchRRSetRequest{ZoneNameOrId: &zoneNameOrId, Domain: &domain, Rtype: &rtype}
// "Update" using PatchRRSetRequest requires removing the target record then adding the updated version.
recordHash := s.D.Get("record_hash").(string)
removeOp := oci_dns.RecordOperation{Operation: oci_dns.RecordOperationOperationRemove, RecordHash: &recordHash}
addOp := oci_dns.RecordOperation{Operation: oci_dns.RecordOperationOperationAdd}
if compartmentId, ok := s.D.GetOkExists("compartment_id"); ok {
tmp := compartmentId.(string)
request.CompartmentId = &tmp
}
addOp.Domain = &domain
addOp.Rtype = &rtype
if rdata, ok := s.D.GetOkExists("rdata"); ok {
tmp := rdata.(string)
addOp.Rdata = &tmp
}
if ttl, ok := s.D.GetOkExists("ttl"); ok {
tmp := ttl.(int)
addOp.Ttl = &tmp
}
request.Items = []oci_dns.RecordOperation{removeOp, addOp}
request.RequestMetadata.RetryPolicy = getRetryPolicy(s.DisableNotFoundRetries, "dns")
response, err := s.Client.PatchRRSet(context.Background(), request)
if err != nil {
return err
}
item, err := findItem(&response.Items, s.D)
if err != nil {
//PatchZoneRecords only returns 50 records we need to do a Get with pagination to make sure we can't find the item
err = s.Get()
if err == nil {
return nil
}
return err
}
s.Res = item
return nil
}
func (s *DnsRecordResourceCrud) Delete() error {
request := oci_dns.PatchRRSetRequest{}
ro := oci_dns.RecordOperation{Operation: oci_dns.RecordOperationOperationRemove}
zoneNameOrId := s.D.Get("zone_name_or_id").(string)
request.ZoneNameOrId = &zoneNameOrId
domain := s.D.Get("domain").(string)
request.Domain = &domain
rtype := s.D.Get("rtype").(string)
request.Rtype = &rtype
if compartmentId, ok := s.D.GetOkExists("compartment_id"); ok {
tmp := compartmentId.(string)
request.CompartmentId = &tmp
}
if recordHash, ok := s.D.GetOkExists("record_hash"); ok {
tmp := recordHash.(string)
ro.RecordHash = &tmp
}
request.Items = []oci_dns.RecordOperation{ro}
request.RequestMetadata.RetryPolicy = getRetryPolicy(s.DisableNotFoundRetries, "dns")
_, err := s.Client.PatchRRSet(context.Background(), request)
return err
}
func (s *DnsRecordResourceCrud) SetData() error {
s.D.SetId(*s.Res.RecordHash)
if s.Res.Domain != nil {
s.D.Set("domain", *s.Res.Domain)
}
if s.Res.IsProtected != nil {
s.D.Set("is_protected", *s.Res.IsProtected)
}
if s.Res.Rdata != nil {
s.D.Set("rdata", *s.Res.Rdata)
}
if s.Res.RecordHash != nil {
s.D.Set("record_hash", *s.Res.RecordHash)
}
if s.Res.RrsetVersion != nil {
s.D.Set("rrset_version", *s.Res.RrsetVersion)
}
if s.Res.Rtype != nil {
s.D.Set("rtype", *s.Res.Rtype)
}
if s.Res.Ttl != nil {
s.D.Set("ttl", *s.Res.Ttl)
}
return nil
}
func findItem(rc *[]oci_dns.Record, r *schema.ResourceData) (*oci_dns.Record, error) {
rType := r.Get("rtype").(string)
rData := r.Get("rdata").(string)
rDomain := r.Get("domain").(string)
rTtl := r.Get("ttl").(int)
rData = normalizeRData(rType, rData)
rHash, rHashOk := r.GetOk("record_hash")
for _, item := range *rc {
// prefer exact match by record hash
if rHashOk && rHash == *item.RecordHash {
return &item, nil
}
// accept match by type and data match
if *item.Rtype == rType && normalizeRData(rType, *item.Rdata) == rData && *item.Domain == rDomain && *item.Ttl == rTtl {
return &item, nil
}
}
return nil, fmt.Errorf("target %s record could not be matched against data %s\nfrom set %+v", rType, rData, rc)
}
// Match dns service transforms of rdata
func normalizeRData(rtype, rdata string) string {
switch rtype {
case "AAAA":
// IPv6 records get compressed by the service by dropping leading 0s and deduping >2 colons in different ways, ex:
// 2001:0db8:85a3:0000:0000:8a2e:0370:7334 => 2001:db8:85a3::8a2e:370:7334
// 0000:0000:8a2e:0000:0000:0370:0000:0000 => ::8a2e:0:0:370:0:0
// use net's faculties for IPv6 comprehension
return net.ParseIP(rdata).String()
case "ALIAS", "CNAME", "NS", "MX", "PTR":
// These record types return with a dot appended, remove for comparison
r := regexp.MustCompile(`\.$`)
return r.ReplaceAllString(rdata, "")
case "TXT":
// These records return each space delimited word value surrounded by quotes
r := regexp.MustCompile(`"*`)
return r.ReplaceAllString(rdata, "")
}
return rdata
}