-
Notifications
You must be signed in to change notification settings - Fork 645
/
resource_ibm_resource_key.go
505 lines (434 loc) · 14.6 KB
/
resource_ibm_resource_key.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
// Copyright IBM Corp. 2017, 2021 All Rights Reserved.
// Licensed under the Mozilla Public License v2.0
package resourcecontroller
import (
"encoding/json"
"fmt"
"log"
"strconv"
"strings"
"time"
rc "github.com/IBM/platform-services-go-sdk/resourcecontrollerv2"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns"
"github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex"
"github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate"
"github.com/IBM/platform-services-go-sdk/iampolicymanagementv1"
)
func ResourceIBMResourceKey() *schema.Resource {
return &schema.Resource{
Create: resourceIBMResourceKeyCreate,
Read: resourceIBMResourceKeyRead,
Update: resourceIBMResourceKeyUpdate,
Delete: resourceIBMResourceKeyDelete,
Exists: resourceIBMResourceKeyExists,
Importer: &schema.ResourceImporter{},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "The name of the resource key",
},
"role": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: "Name of the user role.Valid roles are Writer, Reader, Manager, Administrator, Operator, Viewer, Editor and Custom Roles.",
// ValidateFunc: validateRole,
},
"resource_instance_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: "The id of the resource instance for which to create resource key",
ConflictsWith: []string{"resource_alias_id"},
ValidateFunc: validate.InvokeValidator("ibm_resource_key",
"resource_instance_id"),
},
"resource_alias_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: "The id of the resource alias for which to create resource key",
ConflictsWith: []string{"resource_instance_id"},
},
"parameters": {
Type: schema.TypeMap,
Optional: true,
DiffSuppressFunc: flex.ApplyOnce,
Description: "Arbitrary parameters to pass. Must be a JSON object",
},
"credentials": {
Description: "Credentials asociated with the key",
Type: schema.TypeMap,
Sensitive: true,
Computed: true,
},
"credentials_json": {
Description: "Credentials asociated with the key in json string",
Type: schema.TypeString,
Sensitive: true,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
Description: "Status of resource key",
},
"tags": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
"crn": {
Type: schema.TypeString,
Computed: true,
Description: "crn of resource key",
},
"guid": {
Type: schema.TypeString,
Computed: true,
Description: "When you create a new key, a globally unique identifier (GUID) is assigned.",
},
"url": {
Type: schema.TypeString,
Computed: true,
Description: "When you created a new key, a relative URL path is created identifying the location of the key.",
},
"account_id": {
Type: schema.TypeString,
Computed: true,
Description: "An alpha-numeric value identifying the account ID.",
},
"resource_group_id": {
Type: schema.TypeString,
Computed: true,
Description: "The short ID of the resource group.",
},
"source_crn": {
Type: schema.TypeString,
Computed: true,
Description: "The CRN of resource instance or alias associated to the key.",
},
"state": {
Type: schema.TypeString,
Computed: true,
Description: "The state of the key.",
},
"iam_compatible": {
Type: schema.TypeBool,
Computed: true,
Description: "Specifies whether the key's credentials support IAM.",
},
"resource_instance_url": {
Type: schema.TypeString,
Computed: true,
Description: "The relative path to the resource.",
},
"created_at": {
Type: schema.TypeString,
Computed: true,
Description: "The date when the key was created.",
},
"updated_at": {
Type: schema.TypeString,
Computed: true,
Description: "The date when the key was last updated.",
},
"deleted_at": {
Type: schema.TypeString,
Computed: true,
Description: "The date when the key was deleted.",
},
"created_by": {
Type: schema.TypeString,
Computed: true,
Description: "The subject who created the key.",
},
"updated_by": {
Type: schema.TypeString,
Computed: true,
Description: "The subject who updated the key.",
},
"deleted_by": {
Type: schema.TypeString,
Computed: true,
Description: "The subject who deleted the key.",
},
},
}
}
func ResourceIBMResourceKeyValidator() *validate.ResourceValidator {
validateSchema := make([]validate.ValidateSchema, 0)
validateSchema = append(validateSchema,
validate.ValidateSchema{
Identifier: "resource_instance_id",
ValidateFunctionIdentifier: validate.ValidateCloudData,
Type: validate.TypeString,
CloudDataType: "resource_instance",
CloudDataRange: []string{"service:%s"},
Optional: true})
ibmResourceKeyResourceValidator := validate.ResourceValidator{ResourceName: "ibm_resource_key", Schema: validateSchema}
return &ibmResourceKeyResourceValidator
}
func resourceIBMResourceKeyCreate(d *schema.ResourceData, meta interface{}) error {
rsContClient, err := meta.(conns.ClientSession).ResourceControllerV2API()
if err != nil {
return err
}
name := d.Get("name").(string)
var instanceID, aliasID string
if insID, ok := d.GetOk("resource_instance_id"); ok {
instanceID = insID.(string)
}
if aliID, ok := d.GetOk("resource_alias_id"); ok {
aliasID = aliID.(string)
}
if instanceID == "" && aliasID == "" {
return fmt.Errorf("[ERROR] Provide either `resource_instance_id` or `resource_alias_id`")
}
keyParameters := rc.ResourceKeyPostParameters{}
if parameters, ok := d.GetOk("parameters"); ok {
temp := parameters.(map[string]interface{})
for k, v := range temp {
if v == "true" || v == "false" {
b, _ := strconv.ParseBool(v.(string))
keyParameters.SetProperty(k, b)
} else {
keyParameters.SetProperty(k, v)
}
}
}
resourceInstance, sourceCRN, err := getResourceInstanceAndCRN(d, meta)
if err != nil {
return fmt.Errorf("[ERROR] Error creating resource key when get instance and CRN: %s", err)
}
serviceID := resourceInstance.ResourceID
rsCatClient, err := meta.(conns.ClientSession).ResourceCatalogAPI()
if err != nil {
return fmt.Errorf("[ERROR] Error creating resource key when get ResourceCatalogAPI: %s", err)
}
service, err := rsCatClient.ResourceCatalog().Get(*serviceID, true)
if err != nil {
return fmt.Errorf("[ERROR] Error creating resource key when get service: %s", err)
}
resourceKeyCreate := rc.CreateResourceKeyOptions{
Name: &name,
Source: sourceCRN,
Parameters: &keyParameters,
}
if r, ok := d.GetOk("role"); ok {
role := r.(string)
serviceRole, err := getRoleFromName(role, service.Name, meta)
if err != nil {
return fmt.Errorf("[ERROR] Error creating resource key when get role: %s", err)
}
keyParameters.SetProperty("role_crn", serviceRole.RoleID)
resourceKeyCreate.Role = serviceRole.RoleID
}
resourceKey, resp, err := rsContClient.CreateResourceKey(&resourceKeyCreate)
if err != nil {
return fmt.Errorf("[ERROR] Error creating resource key: %s with resp code: %s", err, resp)
}
d.SetId(*resourceKey.ID)
return resourceIBMResourceKeyRead(d, meta)
}
func resourceIBMResourceKeyUpdate(d *schema.ResourceData, meta interface{}) error {
return nil
}
func resourceIBMResourceKeyRead(d *schema.ResourceData, meta interface{}) error {
rsContClient, err := meta.(conns.ClientSession).ResourceControllerV2API()
if err != nil {
return err
}
resourceKeyID := d.Id()
resourceKeyGet := rc.GetResourceKeyOptions{
ID: &resourceKeyID,
}
resourceKey, resp, err := rsContClient.GetResourceKey(&resourceKeyGet)
if err != nil || resourceKey == nil {
return fmt.Errorf("[ERROR] Error retrieving resource key: %s with resp : %s", err, resp)
}
var credInterface map[string]interface{}
cred, _ := json.Marshal(resourceKey.Credentials)
json.Unmarshal(cred, &credInterface)
d.Set("credentials", flex.Flatten(credInterface))
creds, err := json.Marshal(resourceKey.Credentials)
if err != nil {
return fmt.Errorf("[ERROR] Error marshalling resource key credentials: %s", err)
}
if err = d.Set("credentials_json", string(creds)); err != nil {
return fmt.Errorf("[ERROR] Error setting the credentials json: %s", err)
}
d.Set("name", *resourceKey.Name)
d.Set("status", *resourceKey.State)
if resourceKey.Credentials != nil && resourceKey.Credentials.Redacted != nil {
log.Printf("Credentials are redacted with code: %s.The User doesn't have the correct access to view the credentials. Refer to the API documentation for additional details.", *resourceKey.Credentials.Redacted)
}
if resourceKey.Credentials != nil && resourceKey.Credentials.IamRoleCRN != nil {
roleCrn := *resourceKey.Credentials.IamRoleCRN
iamPolicyManagementClient, err := meta.(conns.ClientSession).IAMPolicyManagementV1API()
if err == nil {
var resourceCRN string
if resourceKey.CRN != nil {
serviceName := strings.Split(*resourceKey.CRN, ":")
if len(serviceName) > 4 {
resourceCRN = serviceName[4]
}
}
listRoleOptions := &iampolicymanagementv1.ListRolesOptions{
AccountID: resourceKey.AccountID,
ServiceName: &resourceCRN,
}
roleList, resp, err := iamPolicyManagementClient.ListRoles(listRoleOptions)
roles := flex.MapRoleListToPolicyRoles(*roleList)
if err == nil && len(roles) > 0 {
for _, role := range roles {
if *role.RoleID == roleCrn {
RoleName := role.DisplayName
d.Set("role", RoleName)
}
}
}
if err != nil {
log.Printf("[ERROR] Error listing IAM Roles %s, %s", err, resp)
}
}
}
sCrn := *resourceKey.SourceCRN
if sCrn != "" {
d.Set("resource_instance_id", sCrn)
}
d.Set("crn", *resourceKey.CRN)
d.Set("guid", *resourceKey.GUID)
d.Set("url", *resourceKey.URL)
d.Set("account_id", *resourceKey.AccountID)
d.Set("resource_group_id", *resourceKey.ResourceGroupID)
d.Set("source_crn", *resourceKey.SourceCRN)
d.Set("state", *resourceKey.State)
d.Set("iam_compatible", *resourceKey.IamCompatible)
d.Set("resource_instance_url", *resourceKey.ResourceInstanceURL)
if resourceKey.CreatedAt != nil {
d.Set("created_at", resourceKey.CreatedAt.String())
} else {
d.Set("created_at", "")
}
if resourceKey.UpdatedAt != nil {
d.Set("updated_at", resourceKey.UpdatedAt.String())
} else {
d.Set("updated_at", "")
}
if resourceKey.DeletedAt != nil {
d.Set("deleted_at", resourceKey.DeletedAt.String())
} else {
d.Set("deleted_at", "")
}
d.Set("created_by", *resourceKey.CreatedBy)
d.Set("updated_by", *resourceKey.UpdatedBy)
d.Set("deleted_by", *resourceKey.DeletedBy)
return nil
}
func resourceIBMResourceKeyDelete(d *schema.ResourceData, meta interface{}) error {
rsContClient, err := meta.(conns.ClientSession).ResourceControllerV2API()
if err != nil {
return err
}
resourceKeyID := d.Id()
resourceKeyDelete := rc.DeleteResourceKeyOptions{
ID: &resourceKeyID,
}
resp, err := rsContClient.DeleteResourceKey(&resourceKeyDelete)
if err != nil {
return fmt.Errorf("[ERROR] Error deleting resource key: %s with resp code: %s", err, resp)
}
d.SetId("")
return nil
}
func resourceIBMResourceKeyExists(d *schema.ResourceData, meta interface{}) (bool, error) {
rsContClient, err := meta.(conns.ClientSession).ResourceControllerV2API()
if err != nil {
return false, err
}
resourceKeyID := d.Id()
resourceKeyGet := rc.GetResourceKeyOptions{
ID: &resourceKeyID,
}
resourceKey, resp, err := rsContClient.GetResourceKey(&resourceKeyGet)
if err != nil {
if resp != nil && (resp.StatusCode == 404 || resp.StatusCode == 410) {
return false, nil
}
return false, fmt.Errorf("[ERROR] Error getting resource key: %s with resp code: %s", err, resp)
}
if err == nil && *resourceKey.State == "removed" {
return false, nil
}
return *resourceKey.ID == resourceKeyID, nil
}
func getResourceInstanceAndCRN(d *schema.ResourceData, meta interface{}) (*rc.ResourceInstance, *string, error) {
rsContClient, err := meta.(conns.ClientSession).ResourceControllerV2API()
if err != nil {
return nil, nil, err
}
if insID, ok := d.GetOk("resource_instance_id"); ok {
insIdString := insID.(string)
resourceInstanceGet := rc.GetResourceInstanceOptions{
ID: &insIdString,
}
instance, resp, err := rsContClient.GetResourceInstance(&resourceInstanceGet)
if err != nil {
log.Printf("Error when get resource instance in getResourceInstanceAndCRN: %s with resp code: %s", err, resp)
return nil, nil, err
}
return instance, instance.CRN, nil
}
aliasID := d.Get("resource_alias_id").(string)
resourceAliasGet := rc.GetResourceAliasOptions{
ID: &aliasID,
}
alias, resp, err := rsContClient.GetResourceAlias(&resourceAliasGet)
if err != nil {
log.Printf("Error when get resource alias in getResourceInstanceAndCRN: %s with resp code: %s", err, resp)
return nil, nil, err
}
resourceInstanceGet := rc.GetResourceInstanceOptions{
ID: alias.ResourceInstanceID,
}
instance, resp, err := rsContClient.GetResourceInstance(&resourceInstanceGet)
if err != nil {
log.Printf("Error when get resource instance in getResourceInstanceAndCRN: %s with resp code: %s", err, resp)
return nil, nil, err
}
return instance, instance.CRN, nil
}
func getRoleFromName(roleName, serviceName string, meta interface{}) (iampolicymanagementv1.PolicyRole, error) {
role := iampolicymanagementv1.PolicyRole{}
iamPolicyManagementClient, err := meta.(conns.ClientSession).IAMPolicyManagementV1API()
if err != nil {
return role, err
}
userDetails, err := meta.(conns.ClientSession).BluemixUserDetails()
if err != nil {
return role, err
}
listRoleOptions := &iampolicymanagementv1.ListRolesOptions{
AccountID: &userDetails.UserAccount,
ServiceName: &serviceName,
}
roleList, _, err := iamPolicyManagementClient.ListRoles(listRoleOptions)
if err != nil {
return role, err
}
roles := flex.MapRoleListToPolicyRoles(*roleList)
role, err = flex.FindRoleByName(roles, roleName)
if err != nil {
return iampolicymanagementv1.PolicyRole{}, err
}
return role, nil
}