-
Notifications
You must be signed in to change notification settings - Fork 154
/
resource_huaweicloud_rms_policy_assignment.go
559 lines (515 loc) · 18.4 KB
/
resource_huaweicloud_rms_policy_assignment.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
553
554
555
556
557
558
559
package rms
import (
"context"
"encoding/json"
"fmt"
"log"
"reflect"
"regexp"
"strings"
"time"
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/chnsz/golangsdk"
"github.com/chnsz/golangsdk/openstack/rms/v1/policyassignments"
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/common"
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/config"
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/utils"
)
const (
AssignmentTypeBuiltin = "builtin"
AssignmentTypeCustom = "custom"
AssignmentStatusDisabled = "Disabled"
AssignmentStatusEnabled = "Enabled"
AssignmentStatusEvaluating = "Evaluating"
)
// @API Config PUT /v1/resource-manager/domains/{domain_id}/policy-assignments
// @API Config GET /v1/resource-manager/domains/{domain_id}/policy-assignments/{policy_assignment_id}
// @API Config POST /v1/resource-manager/domains/{domain_id}/policy-assignments/{policy_assignment_id}/disable
// @API Config POST /v1/resource-manager/domains/{domain_id}/policy-assignments/{policy_assignment_id}/enable
// @API Config PUT /v1/resource-manager/domains/{domain_id}/policy-assignments/{policy_assignment_id}
// @API Config DELETE /v1/resource-manager/domains/{domain_id}/policy-assignments/{policy_assignment_id}
func ResourcePolicyAssignment() *schema.Resource {
return &schema.Resource{
CreateContext: resourceePolicyAssignmentCreate,
ReadContext: resourceePolicyAssignmentRead,
UpdateContext: resourceePolicyAssignmentUpdate,
DeleteContext: resourceePolicyAssignmentDelete,
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(5 * time.Minute),
Update: schema.DefaultTimeout(5 * time.Minute),
},
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.All(
validation.StringMatch(regexp.MustCompile(`^[\w-]*$`),
"Only letters, digits, hyphens and underscores are allowed."),
validation.StringLenBetween(1, 64),
),
Description: "The name of the policy assignment.",
},
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(0, 512),
Description: "The description of the policy assignment.",
},
"policy_definition_id": {
Type: schema.TypeString,
Optional: true,
Description: "The ID of the policy definition.",
ConflictsWith: []string{"custom_policy"},
},
"period": {
Type: schema.TypeString,
Optional: true,
Description: "The period of the policy rule check.",
ConflictsWith: []string{"policy_filter"},
},
"policy_filter": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"region": {
Type: schema.TypeString,
Optional: true,
Description: "The name of the region to which the filtered resources belong.",
},
"resource_provider": {
Type: schema.TypeString,
Optional: true,
Description: "The service name to which the filtered resources belong.",
},
"resource_type": {
Type: schema.TypeString,
Optional: true,
Description: "The resource type of the filtered resources.",
},
"resource_id": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"policy_filter.0.tag_key"},
Description: "The resource ID used to filter a specified resources.",
},
"tag_key": {
Type: schema.TypeString,
Optional: true,
Description: "The tag name used to filter resources.",
},
"tag_value": {
Type: schema.TypeString,
Optional: true,
RequiredWith: []string{"policy_filter.0.tag_key"},
Description: "The tag value used to filter resources.",
},
},
},
Description: "The configuration used to filter resources.",
ConflictsWith: []string{"period"},
},
"custom_policy": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"function_urn": {
Type: schema.TypeString,
Required: true,
Description: "The function URN used to create the custom policy.",
},
"auth_type": {
Type: schema.TypeString,
Required: true,
Description: "The authorization type of the custom policy.",
},
"auth_value": {
Type: schema.TypeMap,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validation.StringIsJSON,
},
Description: "The authorization value of the custom policy.",
},
},
},
Description: "The configuration of the custom policy.",
},
"parameters": {
Type: schema.TypeMap,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validation.StringIsJSON,
},
Description: "The rule definition of the policy assignment.",
},
"status": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "The expect status of the policy.",
},
"type": {
Type: schema.TypeString,
Computed: true,
Description: "The type of the policy assignment.",
},
"created_at": {
Type: schema.TypeString,
Computed: true,
Description: "The creation time.",
},
"updated_at": {
Type: schema.TypeString,
Computed: true,
Description: "The latest update time.",
},
},
}
}
func buildPolicyFilter(filters []interface{}) policyassignments.PolicyFilter {
if len(filters) < 1 {
return policyassignments.PolicyFilter{}
}
filter := filters[0].(map[string]interface{})
return policyassignments.PolicyFilter{
RegionId: filter["region"].(string),
ResourceProvider: filter["resource_provider"].(string),
ResourceType: filter["resource_type"].(string),
ResourceId: filter["resource_id"].(string),
TagKey: filter["tag_key"].(string),
TagValue: filter["tag_value"].(string),
}
}
func buildCustomPolicy(policies []interface{}) (*policyassignments.CustomPolicy, error) {
if len(policies) < 1 {
return nil, nil
}
policy := policies[0].(map[string]interface{})
result := policyassignments.CustomPolicy{
FunctionUrn: policy["function_urn"].(string),
AuthType: policy["auth_type"].(string),
}
authValues := make(map[string]interface{})
for k, jsonVal := range policy["auth_value"].(map[string]interface{}) {
var value interface{}
err := json.Unmarshal([]byte(jsonVal.(string)), &value)
if err != nil {
return &result, fmt.Errorf("error analyzing authorization value: %s", err)
}
authValues[k] = value
}
result.AuthValue = authValues
return &result, nil
}
func buildRuleParameters(parameters map[string]interface{}) (map[string]policyassignments.PolicyParameterValue, error) {
if len(parameters) < 1 {
return nil, nil
}
result := make(map[string]policyassignments.PolicyParameterValue)
for k, jsonVal := range parameters {
var value interface{}
err := json.Unmarshal([]byte(jsonVal.(string)), &value)
if err != nil {
return result, fmt.Errorf("error analyzing parameter value: %s", err)
}
result[k] = policyassignments.PolicyParameterValue{
Value: value,
}
}
return result, nil
}
func buildPolicyAssignmentCreateOpts(d *schema.ResourceData) (policyassignments.CreateOpts, error) {
result := policyassignments.CreateOpts{
Name: d.Get("name").(string),
Description: d.Get("description").(string),
Type: AssignmentTypeBuiltin,
PolicyFilter: buildPolicyFilter(d.Get("policy_filter").([]interface{})),
PolicyDefinitionId: d.Get("policy_definition_id").(string),
Period: d.Get("period").(string),
}
customPolicy, err := buildCustomPolicy(d.Get("custom_policy").([]interface{}))
if err != nil {
return result, err
}
result.CustomPolicy = customPolicy
if customPolicy != nil {
result.Type = AssignmentTypeCustom
}
parameters, err := buildRuleParameters(d.Get("parameters").(map[string]interface{}))
if err != nil {
return result, err
}
result.Parameters = parameters
return result, nil
}
func updatePolicyAssignmentStatus(client *golangsdk.ServiceClient, domainId, assignmentId,
statusConfig string) (err error) {
switch statusConfig {
case AssignmentStatusDisabled:
err = policyassignments.Disable(client, domainId, assignmentId)
case AssignmentStatusEnabled:
err = policyassignments.Enable(client, domainId, assignmentId)
}
return
}
func policyAssignmentRefreshFunc(client *golangsdk.ServiceClient, domainId,
assignmentId string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
resp, err := policyassignments.Get(client, domainId, assignmentId)
if err != nil {
return resp, "ERROR", err
}
return resp, resp.Status, nil
}
}
func resourceePolicyAssignmentCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cfg := meta.(*config.Config)
client, err := cfg.RmsV1Client(cfg.GetRegion(d))
if err != nil {
return diag.Errorf("error creating RMS v1 client: %s", err)
}
opts, err := buildPolicyAssignmentCreateOpts(d)
if err != nil {
return diag.Errorf("error creating the create option structure of the RMS policy assignment: %s", err)
}
domainId := cfg.DomainID
resp, err := policyassignments.Create(client, domainId, opts)
if err != nil {
return diag.Errorf("error creating policy assignment resource: %s", err)
}
assignmentId := resp.ID
d.SetId(assignmentId)
// it will take too long time to become enabled when the resources are very huge.
// so we wait for the enabled status only when user want to disable it during creating.
if statusConfig := d.Get("status").(string); statusConfig == AssignmentStatusDisabled {
log.Printf("[DEBUG] Waiting for the policy assignment (%s) status to become enabled, then disable it", assignmentId)
stateConf := &resource.StateChangeConf{
Pending: []string{AssignmentStatusDisabled, AssignmentStatusEvaluating},
Target: []string{AssignmentStatusEnabled},
Refresh: policyAssignmentRefreshFunc(client, domainId, assignmentId),
Timeout: d.Timeout(schema.TimeoutCreate),
Delay: 10 * time.Second,
PollInterval: 10 * time.Second,
ContinuousTargetOccurence: 2,
}
_, err = stateConf.WaitForStateContext(ctx)
if err != nil {
return diag.Errorf("error waiting for the policy assignment (%s) status to become enabled: %s",
assignmentId, err)
}
err = updatePolicyAssignmentStatus(client, domainId, assignmentId, statusConfig)
if err != nil {
return diag.Errorf("error disabling the status of the policy assignment: %s", err)
}
}
return resourceePolicyAssignmentRead(ctx, d, meta)
}
func flattenPolicyFilter(filter policyassignments.PolicyFilter) []map[string]interface{} {
if reflect.DeepEqual(filter, policyassignments.PolicyFilter{}) {
return nil
}
return []map[string]interface{}{
{
"region": filter.RegionId,
"resource_provider": filter.ResourceProvider,
"resource_type": filter.ResourceType,
"resource_id": filter.ResourceId,
"tag_key": filter.TagKey,
"tag_value": filter.TagValue,
},
}
}
func flattenCustomPolicy(customPolicy policyassignments.CustomPolicy) ([]map[string]interface{}, error) {
if reflect.DeepEqual(customPolicy, policyassignments.CustomPolicy{}) {
return nil, nil
}
authValues := make(map[string]interface{})
for k, v := range customPolicy.AuthValue {
jsonBytes, err := json.Marshal(v)
if err != nil {
return nil, fmt.Errorf("generate json string failed: %s", err)
}
authValues[k] = string(jsonBytes)
}
return []map[string]interface{}{
{
"function_urn": customPolicy.FunctionUrn,
"auth_type": customPolicy.AuthType,
"auth_value": authValues,
},
}, nil
}
func flattenPolicyParameters(parameters map[string]policyassignments.PolicyParameterValue) (map[string]interface{},
error) {
if len(parameters) < 1 {
return nil, nil
}
result := make(map[string]interface{})
for k, v := range parameters {
jsonBytes, err := json.Marshal(v.Value)
if err != nil {
return nil, fmt.Errorf("generate json string failed: %s", err)
}
result[k] = string(jsonBytes)
}
return result, nil
}
func resourceePolicyAssignmentRead(_ context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cfg := meta.(*config.Config)
client, err := cfg.RmsV1Client(cfg.GetRegion(d))
if err != nil {
return diag.Errorf("error creating RMS v1 client: %s", err)
}
assignmentId := d.Id()
resp, err := policyassignments.Get(client, cfg.DomainID, assignmentId)
if err != nil {
return common.CheckDeletedDiag(d, err, "RMS policy assignment")
}
customPolicy, err := flattenCustomPolicy(resp.CustomPolicy)
if err != nil {
return diag.FromErr(err)
}
parameters, err := flattenPolicyParameters(resp.Parameters)
if err != nil {
return diag.FromErr(err)
}
mErr := multierror.Append(nil,
d.Set("type", resp.Type),
d.Set("name", resp.Name),
d.Set("description", resp.Description),
d.Set("policy_definition_id", resp.PolicyDefinitionId),
d.Set("period", resp.Period),
d.Set("policy_filter", flattenPolicyFilter(resp.PolicyFilter)),
d.Set("custom_policy", customPolicy),
d.Set("parameters", parameters),
d.Set("status", resp.Status),
d.Set("created_at", resp.CreatedAt),
d.Set("updated_at", resp.UpdatedAt),
)
if mErr.ErrorOrNil() != nil {
return diag.Errorf("error saving policy assignment resource (%s) fields: %s", assignmentId, mErr)
}
return nil
}
func buildPolicyAssignmentUpdateOpts(d *schema.ResourceData) (policyassignments.UpdateOpts, error) {
result := policyassignments.UpdateOpts{
Name: d.Get("name").(string),
Description: utils.String(d.Get("description").(string)),
Type: AssignmentTypeBuiltin,
PolicyFilter: buildPolicyFilter(d.Get("policy_filter").([]interface{})),
PolicyDefinitionId: d.Get("policy_definition_id").(string),
Period: d.Get("period").(string),
}
customPolicy, err := buildCustomPolicy(d.Get("custom_policy").([]interface{}))
if err != nil {
return result, err
}
result.CustomPolicy = customPolicy
if customPolicy != nil {
result.Type = AssignmentTypeCustom
}
parameters, err := buildRuleParameters(d.Get("parameters").(map[string]interface{}))
if err != nil {
return result, err
}
result.Parameters = parameters
return result, nil
}
func resourceePolicyAssignmentUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cfg := meta.(*config.Config)
client, err := cfg.RmsV1Client(cfg.GetRegion(d))
if err != nil {
return diag.Errorf("error creating RMS v1 client: %s", err)
}
assignmentId := d.Id()
domainId := cfg.DomainID
if d.HasChange("status") {
oldVal, newVal := d.GetChange("status")
err = updatePolicyAssignmentStatus(client, domainId, d.Id(), d.Get("status").(string))
if err != nil {
return diag.Errorf("error updating the status of the policy assignment (%s): %s", assignmentId, err)
}
if newVal.(string) == AssignmentStatusEnabled {
log.Printf("[DEBUG] Waiting for the policy assignment (%s) status to become %s.", assignmentId,
strings.ToLower(newVal.(string)))
stateConf := &resource.StateChangeConf{
Pending: []string{oldVal.(string)},
Target: []string{AssignmentStatusEvaluating, AssignmentStatusEnabled},
Refresh: policyAssignmentRefreshFunc(client, domainId, assignmentId),
Timeout: d.Timeout(schema.TimeoutUpdate),
Delay: 10 * time.Second,
PollInterval: 10 * time.Second,
ContinuousTargetOccurence: 2,
}
_, err = stateConf.WaitForStateContext(ctx)
if err != nil {
return diag.Errorf("error waiting for the policy assignment (%s) status to become %s: %s",
assignmentId, strings.ToLower(newVal.(string)), err)
}
}
}
if d.HasChangeExcept("status") {
opts, err := buildPolicyAssignmentUpdateOpts(d)
if err != nil {
return diag.Errorf("error creating the update option structure of the RMS policy assignment: %s", err)
}
_, err = policyassignments.Update(client, domainId, assignmentId, opts)
if err != nil {
return diag.Errorf("error updating policy assignment resource (%s): %s", assignmentId, err)
}
currentStatus := d.Get("status").(string)
log.Printf("[DEBUG] Waiting for the policy assignment (%s) status to become %s.", assignmentId,
strings.ToLower(currentStatus))
stateConf := &resource.StateChangeConf{
Target: []string{currentStatus},
Refresh: policyAssignmentRefreshFunc(client, domainId, assignmentId),
Timeout: d.Timeout(schema.TimeoutUpdate),
Delay: 10 * time.Second,
PollInterval: 10 * time.Second,
ContinuousTargetOccurence: 2,
}
_, err = stateConf.WaitForStateContext(ctx)
if err != nil {
return diag.Errorf("error waiting for the policy assignment (%s) status to become %s: %s",
assignmentId, strings.ToLower(currentStatus), err)
}
}
return resourceePolicyAssignmentRead(ctx, d, meta)
}
func resourceePolicyAssignmentDelete(_ context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cfg := meta.(*config.Config)
client, err := cfg.RmsV1Client(cfg.GetRegion(d))
if err != nil {
return diag.Errorf("error creating RMS v1 client: %s", err)
}
var (
assignmentId = d.Id()
domainId = cfg.DomainID
)
if d.Get("status").(string) == AssignmentStatusEnabled {
// Before delete policy assignment, we need to disable it.
err = policyassignments.Disable(client, domainId, assignmentId)
if err != nil {
return diag.Errorf("failed to disable the policy assignment (%s): %s", assignmentId, err)
}
}
err = policyassignments.Delete(client, domainId, assignmentId)
if err != nil {
return diag.Errorf("error deleting the policy assignment (%s): %s", assignmentId, err)
}
return nil
}