-
Notifications
You must be signed in to change notification settings - Fork 649
/
resource_ibm_app_config_feature.go
542 lines (495 loc) · 17.2 KB
/
resource_ibm_app_config_feature.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
// Copyright IBM Corp. 2021 All Rights Reserved.
// Licensed under the Mozilla Public License v2.0
package appconfiguration
import (
"fmt"
"log"
"strconv"
"github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex"
"github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/IBM/appconfiguration-go-admin-sdk/appconfigurationv1"
"github.com/IBM/go-sdk-core/v5/core"
)
func ResourceIBMIbmAppConfigFeature() *schema.Resource {
return &schema.Resource{
Create: resourceIbmIbmAppConfigFeatureCreate,
Read: resourceIbmIbmAppConfigFeatureRead,
Update: resourceIbmIbmAppConfigFeatureUpdate,
Delete: resourceIbmIbmAppConfigFeatureDelete,
Importer: &schema.ResourceImporter{},
Schema: map[string]*schema.Schema{
"guid": {
Type: schema.TypeString,
Required: true,
Description: "GUID of the App Configuration service. Get it from the service instance credentials section of the dashboard.",
},
"environment_id": {
Type: schema.TypeString,
Required: true,
Description: "Environment Id.",
},
"name": {
Type: schema.TypeString,
Required: true,
Description: "Feature name.",
},
"feature_id": {
Type: schema.TypeString,
Required: true,
Description: "Feature id.",
},
"type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validate.InvokeValidator("ibm_app_config_feature", "type"),
Description: "Type of the feature (BOOLEAN, STRING, NUMERIC).",
},
"enabled_value": {
Type: schema.TypeString,
Required: true,
Description: "Value of the feature when it is enabled. The value can be BOOLEAN, STRING or a NUMERIC value as per the `type` attribute.",
},
"disabled_value": {
Type: schema.TypeString,
Required: true,
Description: "Value of the feature when it is disabled. The value can be BOOLEAN, STRING or a NUMERIC value as per the `type` attribute.",
},
"description": {
Type: schema.TypeString,
Optional: true,
Description: "Feature description.",
},
"tags": {
Type: schema.TypeString,
Optional: true,
Description: "Tags associated with the feature.",
},
"rollout_percentage": {
Type: schema.TypeInt,
Optional: true,
Description: "Rollout percentage of the feature.",
},
"segment_rules": {
Type: schema.TypeList,
Optional: true,
Description: "Specify the targeting rules that is used to set different feature flag values for different segments.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"rules": {
Type: schema.TypeList,
Required: true,
Description: "Rules array.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"segments": {
Type: schema.TypeList,
Required: true,
Description: "List of segment ids that are used for targeting using the rule.",
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
"value": {
Type: schema.TypeString,
Required: true,
Description: "Value to be used for evaluation for this rule. The value can be Boolean, String or a Numeric value as per the `type` attribute.",
},
"order": {
Type: schema.TypeInt,
Required: true,
Description: "Order of the rule, used during evaluation. The evaluation is performed in the order defined and the value associated with the first matching rule is used for evaluation.",
},
"rollout_percentage": {
Type: schema.TypeInt,
Optional: true,
Description: "Rollout percentage for the segment rule.",
},
},
},
},
"collections": {
Type: schema.TypeList,
Optional: true,
Description: "List of collection id representing the collections that are associated with the specified feature flag.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"collection_id": {
Type: schema.TypeString,
Required: true,
Description: "Collection id.",
},
},
},
},
"segment_exists": {
Type: schema.TypeBool,
Computed: true,
Description: "Denotes if the targeting rules are specified for the feature flag.",
},
"enabled": {
Type: schema.TypeBool,
Computed: true,
Description: "The state of the feature flag.",
},
"created_time": {
Type: schema.TypeString,
Computed: true,
Description: "Creation time of the feature flag.",
},
"updated_time": {
Type: schema.TypeString,
Computed: true,
Description: "Last modified time of the feature flag data.",
},
"href": {
Type: schema.TypeString,
Computed: true,
Description: "Feature flag URL.",
},
},
}
}
func resourceIbmIbmAppConfigFeatureCreate(d *schema.ResourceData, meta interface{}) error {
guid := d.Get("guid").(string)
appconfigClient, err := getAppConfigClient(meta, guid)
if err != nil {
return err
}
options := &appconfigurationv1.CreateFeatureOptions{}
options.SetType(d.Get("type").(string))
options.SetName(d.Get("name").(string))
options.SetFeatureID(d.Get("feature_id").(string))
options.SetEnabledValue(d.Get("enabled_value").(string))
options.SetEnvironmentID(d.Get("environment_id").(string))
options.SetDisabledValue(d.Get("disabled_value").(string))
if _, ok := d.GetOk("rollout_percentage"); ok {
options.SetRolloutPercentage(int64(d.Get("rollout_percentage").(int)))
}
if _, ok := d.GetOk("description"); ok {
options.SetDescription(d.Get("description").(string))
}
if _, ok := d.GetOk("tags"); ok {
options.SetTags(d.Get("tags").(string))
}
if _, ok := d.GetOk("segment_rules"); ok {
var segmentRules []appconfigurationv1.FeatureSegmentRule
for _, e := range d.Get("segment_rules").([]interface{}) {
value := e.(map[string]interface{})
segmentRulesItem, err := resourceIbmAppConfigFeatureMapToSegmentRule(d, value)
if err != nil {
return err
}
segmentRules = append(segmentRules, segmentRulesItem)
}
options.SetSegmentRules(segmentRules)
}
if _, ok := d.GetOk("collections"); ok {
var collections []appconfigurationv1.CollectionRef
for _, e := range d.Get("collections").([]interface{}) {
value := e.(map[string]interface{})
collectionsItem := resourceIbmAppConfigFeatureMapToCollectionRef(value)
collections = append(collections, collectionsItem)
}
options.SetCollections(collections)
}
feature, response, err := appconfigClient.CreateFeature(options)
if err != nil {
log.Printf("CreateFeature failed %s\n%s", err, response)
return err
}
d.SetId(fmt.Sprintf("%s/%s/%s", guid, *options.EnvironmentID, *feature.FeatureID))
return resourceIbmIbmAppConfigFeatureRead(d, meta)
}
func resourceIbmIbmAppConfigFeatureUpdate(d *schema.ResourceData, meta interface{}) error {
parts, err := flex.IdParts(d.Id())
if err != nil {
return nil
}
appconfigClient, err := getAppConfigClient(meta, parts[0])
if err != nil {
return err
}
options := &appconfigurationv1.UpdateFeatureOptions{}
options.SetEnvironmentID(parts[1])
options.SetFeatureID(parts[2])
if ok := d.HasChanges("name", "enabled_value", "disabled_value", "description", "rollout_percentage", "tags", "segment_rules", "collections"); ok {
options.SetName(d.Get("name").(string))
options.SetEnabledValue(d.Get("enabled_value").(string))
options.SetDisabledValue(d.Get("disabled_value").(string))
if _, ok := d.GetOk("description"); ok {
options.SetDescription(d.Get("description").(string))
}
if _, ok := d.GetOk("rollout_percentage"); ok {
options.SetRolloutPercentage(int64(d.Get("rollout_percentage").(int)))
}
if _, ok := d.GetOk("tags"); ok {
options.SetTags(d.Get("tags").(string))
}
if _, ok := d.GetOk("segment_rules"); ok {
var segmentRules []appconfigurationv1.FeatureSegmentRule
for _, e := range d.Get("segment_rules").([]interface{}) {
value := e.(map[string]interface{})
segmentRulesItem, err := resourceIbmAppConfigFeatureMapToSegmentRule(d, value)
if err != nil {
return err
}
segmentRules = append(segmentRules, segmentRulesItem)
}
options.SetSegmentRules(segmentRules)
}
if _, ok := d.GetOk("collections"); ok {
var collections []appconfigurationv1.CollectionRef
for _, e := range d.Get("collections").([]interface{}) {
value := e.(map[string]interface{})
collectionsItem := resourceIbmAppConfigFeatureMapToCollectionRef(value)
collections = append(collections, collectionsItem)
}
options.SetCollections(collections)
}
_, response, err := appconfigClient.UpdateFeature(options)
if err != nil {
log.Printf("[DEBUG] UpdateFeature %s\n%s", err, response)
return err
}
return resourceIbmIbmAppConfigFeatureRead(d, meta)
}
return nil
}
func resourceIbmIbmAppConfigFeatureRead(d *schema.ResourceData, meta interface{}) error {
parts, err := flex.IdParts(d.Id())
if err != nil {
return nil
}
appconfigClient, err := getAppConfigClient(meta, parts[0])
if err != nil {
return err
}
options := &appconfigurationv1.GetFeatureOptions{}
options.SetEnvironmentID(parts[1])
options.SetFeatureID(parts[2])
result, response, err := appconfigClient.GetFeature(options)
if err != nil {
return fmt.Errorf("[DEBUG] GetFeature failed %s\n%s", err, response)
}
d.Set("guid", parts[0])
d.Set("environment_id", parts[1])
if result.Name != nil {
if err = d.Set("name", result.Name); err != nil {
return fmt.Errorf("[ERROR] Error setting name: %s", err)
}
}
if result.FeatureID != nil {
if err = d.Set("feature_id", result.FeatureID); err != nil {
return fmt.Errorf("[ERROR] Error setting feature_id: %s", err)
}
}
if result.Type != nil {
if err = d.Set("type", result.Type); err != nil {
return fmt.Errorf("[ERROR] Error setting type: %s", err)
}
}
if result.Description != nil {
if err = d.Set("description", result.Description); err != nil {
return fmt.Errorf("[ERROR] Error setting description: %s", err)
}
}
if result.RolloutPercentage != nil {
if err = d.Set("rollout_percentage", result.RolloutPercentage); err != nil {
return fmt.Errorf("[ERROR] Error setting rollout_percentage: %s", err)
}
}
if result.Tags != nil {
if err = d.Set("tags", result.Tags); err != nil {
return fmt.Errorf("[ERROR] Error setting tags: %s", err)
}
}
if result.SegmentRules != nil {
segmentRules := []map[string]interface{}{}
for _, segmentRulesItem := range result.SegmentRules {
segmentRulesItemMap := resourceIbmAppConfigFeatureSegmentRuleToMap(segmentRulesItem)
segmentRules = append(segmentRules, segmentRulesItemMap)
}
if err = d.Set("segment_rules", segmentRules); err != nil {
return fmt.Errorf("[ERROR] Error setting segment_rules: %s", err)
}
}
if result.Collections != nil {
collections := []map[string]interface{}{}
for _, collectionsItem := range result.Collections {
collectionsItemMap := resourceIbmAppConfigFeatureCollectionRefToMap(collectionsItem)
collections = append(collections, collectionsItemMap)
}
if err = d.Set("collections", collections); err != nil {
return fmt.Errorf("[ERROR] Error setting collections: %s", err)
}
}
if result.SegmentExists != nil {
if err = d.Set("segment_exists", result.SegmentExists); err != nil {
return fmt.Errorf("[ERROR] Error setting segment_exists: %s", err)
}
}
if result.CreatedTime != nil {
if err = d.Set("created_time", result.CreatedTime.String()); err != nil {
return fmt.Errorf("[ERROR] Error setting created_time: %s", err)
}
}
if result.UpdatedTime != nil {
if err = d.Set("updated_time", result.UpdatedTime.String()); err != nil {
return fmt.Errorf("[ERROR] Error setting updated_time: %s", err)
}
}
if result.Href != nil {
if err = d.Set("href", result.Href); err != nil {
return fmt.Errorf("[ERROR] Error setting href: %s", err)
}
}
if result.Enabled != nil {
if err = d.Set("enabled", result.Enabled); err != nil {
return fmt.Errorf("[ERROR] Error setting enabled: %s", err)
}
}
if result.EnabledValue != nil {
enabledValue := result.EnabledValue
switch enabledValue.(interface{}).(type) {
case string:
d.Set("enabled_value", enabledValue.(string))
case float64:
d.Set("enabled_value", fmt.Sprintf("%v", enabledValue))
case bool:
d.Set("enabled_value", strconv.FormatBool(enabledValue.(bool)))
}
}
if result.DisabledValue != nil {
disabledValue := result.DisabledValue
switch disabledValue.(interface{}).(type) {
case string:
d.Set("disabled_value", disabledValue.(string))
case float64:
d.Set("disabled_value", fmt.Sprintf("%v", disabledValue))
case bool:
d.Set("disabled_value", strconv.FormatBool(disabledValue.(bool)))
}
}
return nil
}
func resourceIbmIbmAppConfigFeatureDelete(d *schema.ResourceData, meta interface{}) error {
parts, err := flex.IdParts(d.Id())
if err != nil {
return nil
}
appconfigClient, err := getAppConfigClient(meta, parts[0])
if err != nil {
return err
}
options := &appconfigurationv1.DeleteFeatureOptions{}
options.SetEnvironmentID(parts[1])
options.SetFeatureID(parts[2])
response, err := appconfigClient.DeleteFeature(options)
if err != nil {
if response != nil && response.StatusCode == 404 {
d.SetId("")
return nil
}
return fmt.Errorf("[DEBUG] DeleteFeature failed %s\n%s", err, response)
}
d.SetId("")
return nil
}
func ResourceIBMAppConfigFeatureValidator() *validate.ResourceValidator {
validateSchema := make([]validate.ValidateSchema, 0)
validateSchema = append(validateSchema,
validate.ValidateSchema{
Identifier: "type",
ValidateFunctionIdentifier: validate.ValidateAllowedStringValue,
Type: validate.TypeString,
Required: true,
AllowedValues: "BOOLEAN, NUMERIC, STRING",
},
)
resourceValidator := validate.ResourceValidator{
ResourceName: "ibm_app_config_feature",
Schema: validateSchema,
}
return &resourceValidator
}
// output
func resourceIbmAppConfigFeatureSegmentRuleToMap(segmentRule appconfigurationv1.FeatureSegmentRule) map[string]interface{} {
segmentRuleMap := map[string]interface{}{}
rules := []map[string]interface{}{}
for _, rulesItem := range segmentRule.Rules {
rulesItemMap := resourceIbmAppConfigFeatureRuleToMap(rulesItem)
rules = append(rules, rulesItemMap)
}
segmentRuleMap["rules"] = rules
segmentRuleMap["order"] = flex.IntValue(segmentRule.Order)
segmentRuleMap["rollout_percentage"] = flex.IntValue(segmentRule.RolloutPercentage)
segmentValue := segmentRule.Value
switch segmentValue.(interface{}).(type) {
case string:
segmentRuleMap["value"] = segmentValue.(string)
case float64:
segmentRuleMap["value"] = fmt.Sprintf("%v", segmentValue)
case bool:
segmentRuleMap["value"] = strconv.FormatBool(segmentValue.(bool))
}
return segmentRuleMap
}
func resourceIbmAppConfigFeatureRuleToMap(rule appconfigurationv1.TargetSegments) map[string]interface{} {
ruleMap := map[string]interface{}{}
ruleMap["segments"] = rule.Segments
return ruleMap
}
func resourceIbmAppConfigFeatureCollectionRefToMap(collectionRef appconfigurationv1.CollectionRef) map[string]interface{} {
collectionRefMap := map[string]interface{}{}
collectionRefMap["collection_id"] = collectionRef.CollectionID
collectionRefMap["name"] = collectionRef.Name
return collectionRefMap
}
// input
func resourceIbmAppConfigFeatureMapToSegmentRule(d *schema.ResourceData, segmentRuleMap map[string]interface{}) (appconfigurationv1.FeatureSegmentRule, error) {
segmentRule := appconfigurationv1.FeatureSegmentRule{}
rules := []appconfigurationv1.TargetSegments{}
for _, rulesItem := range segmentRuleMap["rules"].([]interface{}) {
rulesItemModel := resourceIbmAppConfigFeatureMapToRule(rulesItem.(map[string]interface{}))
rules = append(rules, rulesItemModel)
}
segmentRule.Rules = rules
segmentRule.Order = core.Int64Ptr(int64(segmentRuleMap["order"].(int)))
segmentRule.RolloutPercentage = core.Int64Ptr(int64(segmentRuleMap["rollout_percentage"].(int)))
ruleValue := segmentRuleMap["value"].(string)
switch d.Get("type").(string) {
case "STRING":
segmentRule.Value = ruleValue
case "NUMERIC":
v, err := strconv.ParseFloat(ruleValue, 64)
if err != nil {
return segmentRule, fmt.Errorf("'value' parameter in 'segment_rules' has wrong value: %s", err)
}
segmentRule.Value = v
case "BOOLEAN":
if ruleValue == "false" {
segmentRule.Value = false
} else if ruleValue == "true" {
segmentRule.Value = true
} else {
return segmentRule, fmt.Errorf("'value' parameter in 'segment_rules' has wrong value")
}
}
return segmentRule, nil
}
func resourceIbmAppConfigFeatureMapToRule(ruleMap map[string]interface{}) appconfigurationv1.TargetSegments {
rule := appconfigurationv1.TargetSegments{}
segments := []string{}
for _, segmentsItem := range ruleMap["segments"].([]interface{}) {
segments = append(segments, segmentsItem.(string))
}
rule.Segments = segments
return rule
}
func resourceIbmAppConfigFeatureMapToCollectionRef(collectionRefMap map[string]interface{}) appconfigurationv1.CollectionRef {
collectionRef := appconfigurationv1.CollectionRef{}
collectionRef.CollectionID = core.StringPtr(collectionRefMap["collection_id"].(string))
return collectionRef
}