-
Notifications
You must be signed in to change notification settings - Fork 677
/
Copy pathresource_ibm_iam_service_api_key.go
383 lines (324 loc) · 9.86 KB
/
resource_ibm_iam_service_api_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
// Copyright IBM Corp. 2017, 2021 All Rights Reserved.
// Licensed under the Mozilla Public License v2.0
package iamidentity
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"strconv"
"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/iamidentityv1"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
homedir "github.com/mitchellh/go-homedir"
)
func ResourceIBMIAMServiceAPIKey() *schema.Resource {
return &schema.Resource{
Create: resourceIBMIAMServiceAPIkeyCreate,
Read: resourceIBMIAMServiceAPIKeyRead,
Update: resourceIBMIAMServiceAPIKeyUpdate,
Delete: resourceIBMIAMServiceAPIKeyDelete,
Exists: resourceIBMIAMServiceAPIKeyExists,
Importer: &schema.ResourceImporter{},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
Description: "Name of the Service API key",
},
"description": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: " description of the API key",
},
"iam_service_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "The service iam_id that this API key authenticates",
ValidateFunc: validate.InvokeValidator("ibm_iam_service_api_key",
"iam_service_id"),
},
"account_id": {
Type: schema.TypeString,
Computed: true,
Description: "The account ID of the API key",
},
"apikey": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Sensitive: true,
ForceNew: true,
Description: "API key value for this API key",
},
"locked": {
Type: schema.TypeBool,
Optional: true,
DiffSuppressFunc: flex.ApplyOnce,
Description: "The API key cannot be changed if set to true",
},
"store_value": {
Type: schema.TypeBool,
Optional: true,
DiffSuppressFunc: flex.ApplyOnce,
Description: "Boolean value deciding whether API key value is retrievable in the future",
},
"file": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: flex.ApplyOnce,
Description: "File where api key is to be stored",
},
"crn": {
Type: schema.TypeString,
Computed: true,
Description: "crn of the Service API Key",
},
"entity_tag": {
Type: schema.TypeString,
Computed: true,
Description: "Version of the API Key details object",
},
"created_by": {
Type: schema.TypeString,
Computed: true,
Description: "IAM ID of the service which created the API key",
},
"created_at": {
Type: schema.TypeString,
Computed: true,
Description: "The date and time Service API Key was created",
},
"modified_at": {
Type: schema.TypeString,
Computed: true,
Description: "The date and time Service API Key was modified",
},
},
}
}
func ResourceIBMIAMServiceAPIKeyValidator() *validate.ResourceValidator {
validateSchema := make([]validate.ValidateSchema, 0)
validateSchema = append(validateSchema,
validate.ValidateSchema{
Identifier: "iam_service_id",
ValidateFunctionIdentifier: validate.ValidateCloudData,
Type: validate.TypeString,
CloudDataType: "iam",
CloudDataRange: []string{"service:service_id", "resolved_to:id"},
Required: true})
iBMIAMServiceAPIKeyValidator := validate.ResourceValidator{ResourceName: "ibm_iam_service_api_key", Schema: validateSchema}
return &iBMIAMServiceAPIKeyValidator
}
type APIKey struct {
Name string
Description string
Apikey string
CreatedAt string
Locked bool
}
func resourceIBMIAMServiceAPIkeyCreate(d *schema.ResourceData, meta interface{}) error {
iamIdentityClient, err := meta.(conns.ClientSession).IAMIdentityV1API()
if err != nil {
return err
}
name := d.Get("name").(string)
iamID := d.Get("iam_service_id").(string)
createAPIKeyOptions := &iamidentityv1.CreateAPIKeyOptions{
Name: &name,
IamID: &iamID,
}
if des, ok := d.GetOk("description"); ok {
desString := des.(string)
createAPIKeyOptions.Description = &desString
}
userDetails, err := meta.(conns.ClientSession).BluemixUserDetails()
if err != nil {
return err
}
createAPIKeyOptions.AccountID = &userDetails.UserAccount
if key, ok := d.GetOk("apikey"); ok {
apikeyString := key.(string)
createAPIKeyOptions.Apikey = &apikeyString
}
if strvalue, ok := d.GetOk("store_value"); ok {
value := strvalue.(bool)
createAPIKeyOptions.StoreValue = &value
}
if lock, ok := d.GetOk("locked"); ok {
elockstr := strconv.FormatBool(lock.(bool))
createAPIKeyOptions.EntityLock = &elockstr
}
apiKey, response, err := iamIdentityClient.CreateAPIKey(createAPIKeyOptions)
if err != nil || apiKey == nil {
return fmt.Errorf("[DEBUG] Service API Key creation Error: %s\n%s", err, response)
}
d.SetId(*apiKey.ID)
d.Set("apikey", *apiKey.Apikey)
if keyfile, ok := d.GetOk("file"); ok {
if err := saveToFile(apiKey, keyfile.(string)); err != nil {
log.Printf("Error writing API Key Details to file: %s", err)
}
}
return resourceIBMIAMServiceAPIKeyRead(d, meta)
}
func resourceIBMIAMServiceAPIKeyRead(d *schema.ResourceData, meta interface{}) error {
iamIdentityClient, err := meta.(conns.ClientSession).IAMIdentityV1API()
if err != nil {
return err
}
apiKeyID := d.Id()
getAPIKeyOptions := &iamidentityv1.GetAPIKeyOptions{
ID: &apiKeyID,
}
apiKey, response, err := iamIdentityClient.GetAPIKey(getAPIKeyOptions)
if err != nil || apiKey == nil {
if response != nil && response.StatusCode == 404 {
d.SetId("")
return nil
}
return fmt.Errorf("[DEBUG] Error retrieving Service API Key: %s\n%s", err, response)
}
if apiKey.Name != nil {
d.Set("name", *apiKey.Name)
}
if apiKey.IamID != nil {
d.Set("iam_service_id", *apiKey.IamID)
}
if apiKey.Description != nil {
d.Set("description", *apiKey.Description)
}
if apiKey.AccountID != nil {
d.Set("account_id", *apiKey.AccountID)
}
if *apiKey.Apikey != "" {
d.Set("apikey", *apiKey.Apikey)
}
if apiKey.CRN != nil {
d.Set("crn", *apiKey.CRN)
}
if apiKey.EntityTag != nil {
d.Set("entity_tag", *apiKey.EntityTag)
}
if apiKey.Locked != nil {
d.Set("locked", *apiKey.Locked)
}
if apiKey.CreatedBy != nil {
d.Set("created_by", *apiKey.CreatedBy)
}
if apiKey.CreatedAt != nil {
d.Set("created_at", apiKey.CreatedAt.String())
}
if apiKey.ModifiedAt != nil {
d.Set("modified_at", apiKey.ModifiedAt.String())
}
return nil
}
func resourceIBMIAMServiceAPIKeyUpdate(d *schema.ResourceData, meta interface{}) error {
iamIdentityClient, err := meta.(conns.ClientSession).IAMIdentityV1API()
if err != nil {
return err
}
apiKeyID := d.Id()
getAPIKeyOptions := &iamidentityv1.GetAPIKeyOptions{
ID: &apiKeyID,
}
apiKey, resp, err := iamIdentityClient.GetAPIKey(getAPIKeyOptions)
if err != nil || apiKey == nil {
return fmt.Errorf("[DEBUG] Error retrieving Service API Key: %s\n%s", err, resp)
}
updateAPIKeyOptions := &iamidentityv1.UpdateAPIKeyOptions{
ID: &apiKeyID,
IfMatch: apiKey.EntityTag,
}
hasChange := false
if d.HasChange("name") {
namestr := d.Get("name").(string)
updateAPIKeyOptions.Name = &namestr
hasChange = true
}
if d.HasChange("description") {
desc := d.Get("description").(string)
updateAPIKeyOptions.Description = &desc
hasChange = true
}
if hasChange {
_, response, err := iamIdentityClient.UpdateAPIKey(updateAPIKeyOptions)
if err != nil {
return fmt.Errorf("[DEBUG] Error updating Service API Key: %s\n%s", err, response)
}
}
return resourceIBMIAMServiceAPIKeyRead(d, meta)
}
func resourceIBMIAMServiceAPIKeyDelete(d *schema.ResourceData, meta interface{}) error {
iamIdentityClient, err := meta.(conns.ClientSession).IAMIdentityV1API()
if err != nil {
return err
}
apiKeyID := d.Id()
getAPIKeyOptions := &iamidentityv1.GetAPIKeyOptions{
ID: &apiKeyID,
}
_, response, err := iamIdentityClient.GetAPIKey(getAPIKeyOptions)
if err != nil {
if response != nil && response.StatusCode == 404 {
d.SetId("")
return nil
}
return fmt.Errorf("[DEBUG] Error retrieving Service API Key: %s\n%s", err, response)
}
deleteAPIKeyOptions := &iamidentityv1.DeleteAPIKeyOptions{
ID: &apiKeyID,
}
resp, err := iamIdentityClient.DeleteAPIKey(deleteAPIKeyOptions)
if err != nil {
return fmt.Errorf("[DEBUG] Error deleting Service API Key: %s\n%s", err, resp)
}
d.SetId("")
return nil
}
func resourceIBMIAMServiceAPIKeyExists(d *schema.ResourceData, meta interface{}) (bool, error) {
iamIdentityClient, err := meta.(conns.ClientSession).IAMIdentityV1API()
if err != nil {
return false, err
}
apiKeyID := d.Id()
getAPIKeyOptions := &iamidentityv1.GetAPIKeyOptions{
ID: &apiKeyID,
}
apiKey, response, err := iamIdentityClient.GetAPIKey(getAPIKeyOptions)
if err != nil {
if response != nil && response.StatusCode == 404 {
return false, nil
}
return false, fmt.Errorf("[ERROR] Error retrieving Service API Key: %s\n%s", err, response)
}
return *apiKey.ID == apiKeyID, nil
}
func saveToFile(apiKey *iamidentityv1.APIKey, filePath string) error {
outputFilePath, err := homedir.Expand(filePath)
if err != nil {
return fmt.Errorf("[ERROR] Error generating API Key file path: %s", err)
}
key := &APIKey{
Name: *apiKey.Name,
Apikey: *apiKey.Apikey,
CreatedAt: apiKey.CreatedAt.String(),
Locked: *apiKey.Locked,
}
if apiKey.Description != nil {
key.Description = *apiKey.Description
} else {
key.Description = ""
}
out, _ := json.MarshalIndent(key, "", "\t")
err = ioutil.WriteFile(outputFilePath, out, 0666)
if err == nil {
log.Println("Successfully save API key information to ", outputFilePath)
}
return err
}