/
resource_huaweicloud_cfw_domain_name_group.go
552 lines (473 loc) · 18 KB
/
resource_huaweicloud_cfw_domain_name_group.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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
// ---------------------------------------------------------------
// *** AUTO GENERATED CODE ***
// @Product CFW
// ---------------------------------------------------------------
package cfw
import (
"context"
"fmt"
"strings"
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/jmespath/go-jmespath"
"github.com/chnsz/golangsdk"
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/common"
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/config"
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/utils"
)
// @API CFW POST /v1/{project_id}/domain-set
// @API CFW GET /v1/{project_id}/domain-sets
// @API CFW GET /v1/{project_id}/domain-set/domains/{id}
// @API CFW PUT /v1/{project_id}/domain-set/{id}
// @API CFW DELETE /v1/{project_id}/domain-set/domains/{id}
// @API CFW POST /v1/{project_id}/domain-set/domains/{id}
// @API CFW DELETE /v1/{project_id}/domain-set/{id}
func ResourceDomainNameGroup() *schema.Resource {
return &schema.Resource{
CreateContext: resourceDomainNameGroupCreate,
ReadContext: resourceDomainNameGroupRead,
UpdateContext: resourceDomainNameGroupUpdate,
DeleteContext: resourceDomainNameGroupDelete,
Importer: &schema.ResourceImporter{
StateContext: resourceDomainNameGroupImportState,
},
Schema: map[string]*schema.Schema{
"region": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"fw_instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: `Specifies the firewall instance ID.`,
},
"object_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: `Specifies the protected object ID.`,
},
"name": {
Type: schema.TypeString,
Required: true,
Description: `Specifies the name of the domain name group.`,
},
"type": {
Type: schema.TypeInt,
Required: true,
ForceNew: true,
Description: `Specifies the type of the domain name group.`,
},
"domain_names": {
Type: schema.TypeList,
Elem: domainNameGroupDomainNamesSchema(),
Optional: true,
Computed: true,
Description: `Specifies the list of domain names.`,
},
"description": {
Type: schema.TypeString,
Optional: true,
Description: `Specifies the description of the domain name group.`,
},
"config_status": {
Type: schema.TypeInt,
Computed: true,
Description: `The config status of the domain name group.`,
},
"ref_count": {
Type: schema.TypeInt,
Computed: true,
Description: `The reference count of the domain name group.`,
},
"message": {
Type: schema.TypeString,
Computed: true,
Description: `The message of the domain name group.`,
},
},
}
}
func domainNameGroupDomainNamesSchema() *schema.Resource {
sc := schema.Resource{
Schema: map[string]*schema.Schema{
"domain_name": {
Type: schema.TypeString,
Required: true,
Description: `Specifies the domain name.`,
},
"description": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: `Specifies the description.`,
},
"domain_address_id": {
Type: schema.TypeString,
Computed: true,
Description: `The domain address ID.`,
},
"dns_ips": {
Type: schema.TypeString,
Computed: true,
Description: `The DNS IP list.`,
},
},
}
return &sc
}
func resourceDomainNameGroupCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cfg := meta.(*config.Config)
region := cfg.GetRegion(d)
// createDomainNameGroup: Create a CFW domain name group.
var (
createDomainNameGroupHttpUrl = "v1/{project_id}/domain-set"
createDomainNameGroupProduct = "cfw"
)
createDomainNameGroupClient, err := cfg.NewServiceClient(createDomainNameGroupProduct, region)
if err != nil {
return diag.Errorf("error creating CFW client: %s", err)
}
createDomainNameGroupPath := createDomainNameGroupClient.Endpoint + createDomainNameGroupHttpUrl
createDomainNameGroupPath = strings.ReplaceAll(createDomainNameGroupPath, "{project_id}", createDomainNameGroupClient.ProjectID)
createDomainNameGroupOpt := golangsdk.RequestOpts{
KeepResponseBody: true,
OkCodes: []int{
200,
},
MoreHeaders: map[string]string{"Content-Type": "application/json"},
}
// domain_names is required in API but can be an empty list, so RemoveNil is not used here
createDomainNameGroupOpt.JSONBody = buildCreateDomainNameGroupBodyParams(d)
createDomainNameGroupResp, err := createDomainNameGroupClient.Request("POST", createDomainNameGroupPath, &createDomainNameGroupOpt)
if err != nil {
return diag.Errorf("error creating DomainNameGroup: %s", err)
}
createDomainNameGroupRespBody, err := utils.FlattenResponse(createDomainNameGroupResp)
if err != nil {
return diag.FromErr(err)
}
id, err := jmespath.Search("data.id", createDomainNameGroupRespBody)
if err != nil {
return diag.Errorf("error creating DomainNameGroup: ID is not found in API response")
}
d.SetId(id.(string))
return resourceDomainNameGroupRead(ctx, d, meta)
}
func buildCreateDomainNameGroupBodyParams(d *schema.ResourceData) map[string]interface{} {
bodyParams := map[string]interface{}{
"fw_instance_id": d.Get("fw_instance_id"),
"object_id": d.Get("object_id"),
"name": d.Get("name"),
"domain_set_type": d.Get("type"),
"domain_names": buildCreateDomainNameGroupRequestBodyDomainNames(d.Get("domain_names")),
"description": utils.ValueIngoreEmpty(d.Get("description")),
}
return bodyParams
}
func buildCreateDomainNameGroupRequestBodyDomainNames(rawParams interface{}) []map[string]interface{} {
if rawArray, ok := rawParams.([]interface{}); ok {
rst := make([]map[string]interface{}, len(rawArray))
for i, v := range rawArray {
raw := v.(map[string]interface{})
rst[i] = map[string]interface{}{
"domain_name": raw["domain_name"],
"description": utils.ValueIngoreEmpty(raw["description"]),
}
}
return rst
}
return nil
}
func resourceDomainNameGroupRead(_ context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cfg := meta.(*config.Config)
region := cfg.GetRegion(d)
id := d.Id()
var mErr *multierror.Error
// getDomainNameGroup: Query the CFW domain name group detail
var (
getDomainNameGroupHttpUrl = "v1/{project_id}/domain-sets"
getDomainNameListHttpUrl = "v1/{project_id}/domain-set/domains/{id}"
getDomainNameGroupProduct = "cfw"
)
getDomainNameGroupClient, err := cfg.NewServiceClient(getDomainNameGroupProduct, region)
if err != nil {
return diag.Errorf("error creating CFW client: %s", err)
}
getDomainNameGroupPath := getDomainNameGroupClient.Endpoint + getDomainNameGroupHttpUrl
getDomainNameGroupPath = strings.ReplaceAll(getDomainNameGroupPath, "{project_id}", getDomainNameGroupClient.ProjectID)
getDomainNameGroupQueryParams := buildGetDomainNameGroupQueryParams(d)
getDomainNameGroupPath += getDomainNameGroupQueryParams
getDomainNameGroupOpt := golangsdk.RequestOpts{
KeepResponseBody: true,
OkCodes: []int{
200,
},
MoreHeaders: map[string]string{"Content-Type": "application/json"},
}
getDomainNameGroupResp, err := getDomainNameGroupClient.Request("GET", getDomainNameGroupPath, &getDomainNameGroupOpt)
if err != nil {
return common.CheckDeletedDiag(d, err, "error retrieving DomainNameGroup")
}
getDomainNameGroupRespBody, err := utils.FlattenResponse(getDomainNameGroupResp)
if err != nil {
return diag.FromErr(err)
}
jsonPath := fmt.Sprintf("data.records[?set_id=='%s']|[0]", id)
getDomainNameGroupRespBody = utils.PathSearch(jsonPath, getDomainNameGroupRespBody, nil)
if getDomainNameGroupRespBody == nil {
return common.CheckDeletedDiag(d, golangsdk.ErrDefault404{}, "no data found")
}
mErr = multierror.Append(
mErr,
d.Set("region", region),
d.Set("name", utils.PathSearch("name", getDomainNameGroupRespBody, nil)),
d.Set("type", utils.PathSearch("domain_set_type", getDomainNameGroupRespBody, nil)),
d.Set("description", utils.PathSearch("description", getDomainNameGroupRespBody, nil)),
d.Set("config_status", utils.PathSearch("config_status", getDomainNameGroupRespBody, nil)),
d.Set("ref_count", utils.PathSearch("ref_count", getDomainNameGroupRespBody, nil)),
d.Set("message", utils.PathSearch("message", getDomainNameGroupRespBody, nil)),
)
// getDomainNameList: Query the domain list of the CFW domain name group
getDomainNameListClient, err := cfg.NewServiceClient(getDomainNameGroupProduct, region)
if err != nil {
return diag.Errorf("error creating CFW client: %s", err)
}
getDomainNameListPath := getDomainNameListClient.Endpoint + getDomainNameListHttpUrl
getDomainNameListPath = strings.ReplaceAll(getDomainNameListPath, "{project_id}", getDomainNameListClient.ProjectID)
getDomainNameListPath = strings.ReplaceAll(getDomainNameListPath, "{id}", id)
getDomainNameListQueryParams := buildGetDomainNameListQueryParams(d)
getDomainNameListPath += getDomainNameListQueryParams
getDomainNameListOpt := golangsdk.RequestOpts{
KeepResponseBody: true,
OkCodes: []int{
200,
},
MoreHeaders: map[string]string{"Content-Type": "application/json"},
}
getDomainNameListResp, err := getDomainNameListClient.Request("GET", getDomainNameListPath, &getDomainNameListOpt)
if err != nil {
return diag.Errorf("error retrieving domain name list of domain group(%s): %s", id, err)
}
getDomainNameListRespBody, err := utils.FlattenResponse(getDomainNameListResp)
if err != nil {
return diag.FromErr(err)
}
domainNameList := utils.PathSearch("data.records", getDomainNameListRespBody, nil)
if domainNameList == nil {
return diag.Errorf("can not find records in response: %s", getDomainNameListRespBody)
}
mErr = multierror.Append(
mErr,
d.Set("domain_names", flattenDomainNames(domainNameList.([]interface{}))),
)
return diag.FromErr(mErr.ErrorOrNil())
}
func buildGetDomainNameGroupQueryParams(d *schema.ResourceData) string {
res := fmt.Sprintf("?limit=1024&offset=0&fw_instance_id=%v&object_id=%v",
d.Get("fw_instance_id"), d.Get("object_id"))
if v, ok := d.GetOk("name"); ok {
res += fmt.Sprintf("&key_word=%v", v)
}
return res
}
func buildGetDomainNameListQueryParams(d *schema.ResourceData) string {
res := fmt.Sprintf("?limit=1024&offset=0&fw_instance_id=%v", d.Get("fw_instance_id"))
return res
}
func flattenDomainNames(domainNameList []interface{}) []map[string]interface{} {
res := make([]map[string]interface{}, len(domainNameList))
for i, v := range domainNameList {
raw := v.(map[string]interface{})
res[i] = map[string]interface{}{
"domain_name": raw["domain_name"],
"description": raw["description"],
"domain_address_id": raw["domain_address_id"],
"dns_ips": raw["dns_ips"],
}
}
return res
}
func resourceDomainNameGroupUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cfg := meta.(*config.Config)
region := cfg.GetRegion(d)
updateDomainNameGroupProduct := "cfw"
updateDomainNameGroupClient, err := cfg.NewServiceClient(updateDomainNameGroupProduct, region)
if err != nil {
return diag.Errorf("error creating CFW client: %s", err)
}
updateDomainNameGroupChanges := []string{
"name",
"description",
}
if d.HasChanges(updateDomainNameGroupChanges...) {
// updateDomainNameGroup: Update the configuration of CFW domain name group
updateDomainNameGroupHttpUrl := "v1/{project_id}/domain-set/{id}"
updateDomainNameGroupPath := updateDomainNameGroupClient.Endpoint + updateDomainNameGroupHttpUrl
updateDomainNameGroupPath = strings.ReplaceAll(updateDomainNameGroupPath, "{project_id}", updateDomainNameGroupClient.ProjectID)
updateDomainNameGroupPath = strings.ReplaceAll(updateDomainNameGroupPath, "{id}", d.Id())
updateDomainNameGroupPath += fmt.Sprintf("?fw_instance_id=%v", d.Get("fw_instance_id"))
updateDomainNameGroupOpt := golangsdk.RequestOpts{
KeepResponseBody: true,
OkCodes: []int{
200,
},
MoreHeaders: map[string]string{"Content-Type": "application/json"},
}
updateDomainNameGroupOpt.JSONBody = utils.RemoveNil(buildUpdateDomainNameGroupBodyParams(d))
_, err = updateDomainNameGroupClient.Request("PUT", updateDomainNameGroupPath, &updateDomainNameGroupOpt)
if err != nil {
return diag.Errorf("error updating DomainNameGroup: %s", err)
}
}
if d.HasChange("domain_names") {
oldRaws, newRaws := d.GetChange("domain_names")
if len(oldRaws.([]interface{})) != 0 {
err := removeDomainNames(updateDomainNameGroupClient, d, oldRaws.([]interface{}))
if err != nil {
return diag.FromErr(err)
}
}
if len(newRaws.([]interface{})) != 0 {
err := addDomainNames(updateDomainNameGroupClient, d, newRaws.([]interface{}))
if err != nil {
return diag.FromErr(err)
}
}
}
return resourceDomainNameGroupRead(ctx, d, meta)
}
func buildUpdateDomainNameGroupBodyParams(d *schema.ResourceData) map[string]interface{} {
bodyParams := map[string]interface{}{
"name": d.Get("name"),
"description": d.Get("description"),
}
return bodyParams
}
func removeDomainNames(client *golangsdk.ServiceClient, d *schema.ResourceData, domainNameList []interface{}) error {
if len(domainNameList) == 0 {
return nil
}
id := d.Id()
updateDomainNameGroupHttpUrl := "v1/{project_id}/domain-set/domains/{id}"
removeDomainNamesPath := client.Endpoint + updateDomainNameGroupHttpUrl
removeDomainNamesPath = strings.ReplaceAll(removeDomainNamesPath, "{project_id}", client.ProjectID)
removeDomainNamesPath = strings.ReplaceAll(removeDomainNamesPath, "{id}", id)
updateDomainNameGroupOpt := golangsdk.RequestOpts{
KeepResponseBody: true,
OkCodes: []int{
200,
},
MoreHeaders: map[string]string{"Content-Type": "application/json"},
}
updateDomainNameGroupOpt.JSONBody = utils.RemoveNil(buildDemoveDomainNamesBodyParams(d, domainNameList))
_, err := client.Request("DELETE", removeDomainNamesPath, &updateDomainNameGroupOpt)
if err != nil {
return fmt.Errorf("error removing domain names from domain name group(%s): %s", id, err)
}
return nil
}
func addDomainNames(client *golangsdk.ServiceClient, d *schema.ResourceData, domainNameList []interface{}) error {
if len(domainNameList) == 0 {
return nil
}
id := d.Id()
updateDomainNameGroupHttpUrl := "v1/{project_id}/domain-set/domains/{id}"
removeDomainNamesPath := client.Endpoint + updateDomainNameGroupHttpUrl
removeDomainNamesPath = strings.ReplaceAll(removeDomainNamesPath, "{project_id}", client.ProjectID)
removeDomainNamesPath = strings.ReplaceAll(removeDomainNamesPath, "{id}", id)
updateDomainNameGroupOpt := golangsdk.RequestOpts{
KeepResponseBody: true,
OkCodes: []int{
200,
},
MoreHeaders: map[string]string{"Content-Type": "application/json"},
}
updateDomainNameGroupOpt.JSONBody = utils.RemoveNil(buildAddDomainNamesBodyParams(d, domainNameList))
_, err := client.Request("POST", removeDomainNamesPath, &updateDomainNameGroupOpt)
if err != nil {
return fmt.Errorf("error adding domain names to domain name group(%s): %s", id, err)
}
return nil
}
func buildDemoveDomainNamesBodyParams(d *schema.ResourceData, domainNameList []interface{}) map[string]interface{} {
if len(domainNameList) == 0 {
return nil
}
domainAddressIds := make([]string, len(domainNameList))
for i, v := range domainNameList {
raw := v.(map[string]interface{})
domainAddressIds[i] = raw["domain_address_id"].(string)
}
return map[string]interface{}{
"object_id": d.Get("object_id"),
"domain_address_ids": domainAddressIds,
}
}
func buildAddDomainNamesBodyParams(d *schema.ResourceData, domainNameList []interface{}) map[string]interface{} {
if len(domainNameList) == 0 {
return nil
}
domainNames := make([]map[string]interface{}, len(domainNameList))
for i, v := range domainNameList {
raw := v.(map[string]interface{})
domainNames[i] = map[string]interface{}{
"domain_name": raw["domain_name"],
"description": raw["description"],
}
}
return map[string]interface{}{
"fw_instance_id": d.Get("fw_instance_id"),
"object_id": d.Get("object_id"),
"domain_names": domainNames,
}
}
func resourceDomainNameGroupDelete(_ context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cfg := meta.(*config.Config)
region := cfg.GetRegion(d)
// deleteDomainNameGroup: Delete an existing CFW domain name group
var (
deleteDomainNameGroupHttpUrl = "v1/{project_id}/domain-set/{id}"
deleteDomainNameGroupProduct = "cfw"
)
deleteDomainNameGroupClient, err := cfg.NewServiceClient(deleteDomainNameGroupProduct, region)
if err != nil {
return diag.Errorf("error creating CFW client: %s", err)
}
deleteDomainNameGroupPath := deleteDomainNameGroupClient.Endpoint + deleteDomainNameGroupHttpUrl
deleteDomainNameGroupPath = strings.ReplaceAll(deleteDomainNameGroupPath, "{project_id}", deleteDomainNameGroupClient.ProjectID)
deleteDomainNameGroupPath = strings.ReplaceAll(deleteDomainNameGroupPath, "{id}", d.Id())
deleteDomainNameGroupPath += fmt.Sprintf("?fw_instance_id=%v", d.Get("fw_instance_id"))
deleteDomainNameGroupOpt := golangsdk.RequestOpts{
KeepResponseBody: true,
OkCodes: []int{
200,
},
MoreHeaders: map[string]string{"Content-Type": "application/json"},
}
_, err = deleteDomainNameGroupClient.Request("DELETE", deleteDomainNameGroupPath, &deleteDomainNameGroupOpt)
if err != nil {
return diag.Errorf("error deleting DomainNameGroup: %s", err)
}
return nil
}
func resourceDomainNameGroupImportState(_ context.Context, d *schema.ResourceData, _ interface{}) ([]*schema.ResourceData, error) {
parts := strings.Split(d.Id(), "/")
if len(parts) != 3 {
return nil, fmt.Errorf("invalid format specified for import id, must be <fw_instance_id>/<object_id>/<id>")
}
mErr := multierror.Append(nil,
d.Set("fw_instance_id", parts[0]),
d.Set("object_id", parts[1]),
)
err := mErr.ErrorOrNil()
if err != nil {
return nil, err
}
d.SetId(parts[2])
return []*schema.ResourceData{d}, nil
}