/
resource_ibm_cd_toolchain_tool_hashicorpvault.go
402 lines (365 loc) · 16.4 KB
/
resource_ibm_cd_toolchain_tool_hashicorpvault.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
// Copyright IBM Corp. 2023 All Rights Reserved.
// Licensed under the Mozilla Public License v2.0
package cdtoolchain
import (
"context"
"fmt"
"log"
"time"
"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/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/continuous-delivery-go-sdk/cdtoolchainv2"
"github.com/IBM/go-sdk-core/v5/core"
)
func ResourceIBMCdToolchainToolHashicorpvault() *schema.Resource {
return &schema.Resource{
CreateContext: resourceIBMCdToolchainToolHashicorpvaultCreate,
ReadContext: resourceIBMCdToolchainToolHashicorpvaultRead,
UpdateContext: resourceIBMCdToolchainToolHashicorpvaultUpdate,
DeleteContext: resourceIBMCdToolchainToolHashicorpvaultDelete,
Importer: &schema.ResourceImporter{},
Schema: map[string]*schema.Schema{
"toolchain_id": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_hashicorpvault", "toolchain_id"),
Description: "ID of the toolchain to bind the tool to.",
},
"name": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ValidateFunc: validate.InvokeValidator("ibm_cd_toolchain_tool_hashicorpvault", "name"),
Description: "Name of the tool.",
},
"parameters": &schema.Schema{
Type: schema.TypeList,
MinItems: 1,
MaxItems: 1,
Required: true,
Description: "Unique key-value pairs representing parameters to be used to create the tool. A list of parameters for each tool integration can be found in the <a href=\"https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-integrations\">Configuring tool integrations page</a>.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
Description: "The name used to identify this tool integration. Secret references include this name to identify the secrets store where the secrets reside. All secrets store tools integrated into a toolchain should have a unique name to allow secret resolution to function properly.",
},
"server_url": &schema.Schema{
Type: schema.TypeString,
Required: true,
Description: "The server URL for your HashiCorp Vault instance.",
},
"authentication_method": &schema.Schema{
Type: schema.TypeString,
Required: true,
Description: "The authentication method for your HashiCorp Vault instance.",
},
"token": &schema.Schema{
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: flex.SuppressHashedRawSecret,
Sensitive: true,
Description: "The authentication token for your HashiCorp Vault instance when using the 'github' and 'token' authentication methods. This parameter is ignored for other authentication methods. You can use a toolchain secret reference for this parameter. For more information, see [Protecting your sensitive data in Continuous Delivery](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-cd_data_security#cd_secure_credentials).",
},
"role_id": &schema.Schema{
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: flex.SuppressHashedRawSecret,
Sensitive: true,
Description: "The authentication role ID for your HashiCorp Vault instance when using the 'approle' authentication method. This parameter is ignored for other authentication methods. Note, 'role_id' should be treated as a secret and should not be shared in plaintext. You can use a toolchain secret reference for this parameter. For more information, see [Protecting your sensitive data in Continuous Delivery](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-cd_data_security#cd_secure_credentials).",
},
"secret_id": &schema.Schema{
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: flex.SuppressHashedRawSecret,
Sensitive: true,
Description: "The authentication secret ID for your HashiCorp Vault instance when using the 'approle' authentication method. This parameter is ignored for other authentication methods. You can use a toolchain secret reference for this parameter. For more information, see [Protecting your sensitive data in Continuous Delivery](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-cd_data_security#cd_secure_credentials).",
},
"dashboard_url": &schema.Schema{
Type: schema.TypeString,
Required: true,
Description: "The URL of the HashiCorp Vault server dashboard for this integration. In the graphical UI, this is the dashboard that the browser will navigate to when you click the HashiCorp Vault integration tile.",
},
"path": &schema.Schema{
Type: schema.TypeString,
Required: true,
Description: "The mount path where your secrets are stored in your HashiCorp Vault instance.",
},
"secret_filter": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Description: "A regular expression to filter the list of secret names returned from your HashiCorp Vault instance.",
},
"default_secret": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Description: "A default secret name that will be selected or used if no list of secret names are returned from your HashiCorp Vault instance.",
},
"username": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Description: "The authentication username for your HashiCorp Vault instance when using the 'userpass' authentication method. This parameter is ignored for other authentication methods.",
},
"password": &schema.Schema{
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: flex.SuppressHashedRawSecret,
Sensitive: true,
Description: "The authentication password for your HashiCorp Vault instance when using the 'userpass' authentication method. This parameter is ignored for other authentication methods. You can use a toolchain secret reference for this parameter. For more information, see [Protecting your sensitive data in Continuous Delivery](https://cloud.ibm.com/docs/ContinuousDelivery?topic=ContinuousDelivery-cd_data_security#cd_secure_credentials).",
},
},
},
},
"resource_group_id": &schema.Schema{
Type: schema.TypeString,
Computed: true,
Description: "Resource group where the tool is located.",
},
"crn": &schema.Schema{
Type: schema.TypeString,
Computed: true,
Description: "Tool CRN.",
},
"toolchain_crn": &schema.Schema{
Type: schema.TypeString,
Computed: true,
Description: "CRN of toolchain which the tool is bound to.",
},
"href": &schema.Schema{
Type: schema.TypeString,
Computed: true,
Description: "URI representing the tool.",
},
"referent": &schema.Schema{
Type: schema.TypeList,
Computed: true,
Description: "Information on URIs to access this resource through the UI or API.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"ui_href": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Description: "URI representing this resource through the UI.",
},
"api_href": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Description: "URI representing this resource through an API.",
},
},
},
},
"updated_at": &schema.Schema{
Type: schema.TypeString,
Computed: true,
Description: "Latest tool update timestamp.",
},
"state": &schema.Schema{
Type: schema.TypeString,
Computed: true,
Description: "Current configuration state of the tool.",
},
"tool_id": &schema.Schema{
Type: schema.TypeString,
Computed: true,
Description: "Tool ID.",
},
},
}
}
func ResourceIBMCdToolchainToolHashicorpvaultValidator() *validate.ResourceValidator {
validateSchema := make([]validate.ValidateSchema, 0)
validateSchema = append(validateSchema,
validate.ValidateSchema{
Identifier: "toolchain_id",
ValidateFunctionIdentifier: validate.ValidateRegexpLen,
Type: validate.TypeString,
Required: true,
Regexp: `^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$`,
MinValueLength: 36,
MaxValueLength: 36,
},
validate.ValidateSchema{
Identifier: "name",
ValidateFunctionIdentifier: validate.ValidateRegexpLen,
Type: validate.TypeString,
Optional: true,
Regexp: `^([^\x00-\x7F]|[a-zA-Z0-9-._ ])+$`,
MinValueLength: 0,
MaxValueLength: 128,
},
)
resourceValidator := validate.ResourceValidator{ResourceName: "ibm_cd_toolchain_tool_hashicorpvault", Schema: validateSchema}
return &resourceValidator
}
func resourceIBMCdToolchainToolHashicorpvaultCreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cdToolchainClient, err := meta.(conns.ClientSession).CdToolchainV2()
if err != nil {
return diag.FromErr(err)
}
createToolOptions := &cdtoolchainv2.CreateToolOptions{}
createToolOptions.SetToolchainID(d.Get("toolchain_id").(string))
createToolOptions.SetToolTypeID("hashicorpvault")
parametersModel := GetParametersForCreate(d, ResourceIBMCdToolchainToolHashicorpvault(), nil)
createToolOptions.SetParameters(parametersModel)
if _, ok := d.GetOk("name"); ok {
createToolOptions.SetName(d.Get("name").(string))
}
toolchainToolPost, response, err := cdToolchainClient.CreateToolWithContext(context, createToolOptions)
if err != nil {
log.Printf("[DEBUG] CreateToolWithContext failed %s\n%s", err, response)
return diag.FromErr(fmt.Errorf("CreateToolWithContext failed %s\n%s", err, response))
}
d.SetId(fmt.Sprintf("%s/%s", *createToolOptions.ToolchainID, *toolchainToolPost.ID))
return resourceIBMCdToolchainToolHashicorpvaultRead(context, d, meta)
}
func resourceIBMCdToolchainToolHashicorpvaultRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cdToolchainClient, err := meta.(conns.ClientSession).CdToolchainV2()
if err != nil {
return diag.FromErr(err)
}
getToolByIDOptions := &cdtoolchainv2.GetToolByIDOptions{}
parts, err := flex.SepIdParts(d.Id(), "/")
if err != nil {
return diag.FromErr(err)
}
getToolByIDOptions.SetToolchainID(parts[0])
getToolByIDOptions.SetToolID(parts[1])
var toolchainTool *cdtoolchainv2.ToolchainTool
var response *core.DetailedResponse
err = resource.RetryContext(context, 10*time.Second, func() *resource.RetryError {
toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions)
if err != nil || toolchainTool == nil {
if response != nil && response.StatusCode == 404 {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if conns.IsResourceTimeoutError(err) {
toolchainTool, response, err = cdToolchainClient.GetToolByIDWithContext(context, getToolByIDOptions)
}
if err != nil {
if response != nil && response.StatusCode == 404 {
d.SetId("")
return nil
}
log.Printf("[DEBUG] GetToolByIDWithContext failed %s\n%s", err, response)
return diag.FromErr(fmt.Errorf("GetToolByIDWithContext failed %s\n%s", err, response))
}
if err = d.Set("toolchain_id", toolchainTool.ToolchainID); err != nil {
return diag.FromErr(fmt.Errorf("Error setting toolchain_id: %s", err))
}
if !core.IsNil(toolchainTool.Name) {
if err = d.Set("name", toolchainTool.Name); err != nil {
return diag.FromErr(fmt.Errorf("Error setting name: %s", err))
}
}
parametersMap := GetParametersFromRead(toolchainTool.Parameters, ResourceIBMCdToolchainToolHashicorpvault(), nil)
if err = d.Set("parameters", []map[string]interface{}{parametersMap}); err != nil {
return diag.FromErr(fmt.Errorf("Error setting parameters: %s", err))
}
if err = d.Set("resource_group_id", toolchainTool.ResourceGroupID); err != nil {
return diag.FromErr(fmt.Errorf("Error setting resource_group_id: %s", err))
}
if err = d.Set("crn", toolchainTool.CRN); err != nil {
return diag.FromErr(fmt.Errorf("Error setting crn: %s", err))
}
if err = d.Set("toolchain_crn", toolchainTool.ToolchainCRN); err != nil {
return diag.FromErr(fmt.Errorf("Error setting toolchain_crn: %s", err))
}
if err = d.Set("href", toolchainTool.Href); err != nil {
return diag.FromErr(fmt.Errorf("Error setting href: %s", err))
}
referentMap, err := resourceIBMCdToolchainToolHashicorpvaultToolModelReferentToMap(toolchainTool.Referent)
if err != nil {
return diag.FromErr(err)
}
if err = d.Set("referent", []map[string]interface{}{referentMap}); err != nil {
return diag.FromErr(fmt.Errorf("Error setting referent: %s", err))
}
if err = d.Set("updated_at", flex.DateTimeToString(toolchainTool.UpdatedAt)); err != nil {
return diag.FromErr(fmt.Errorf("Error setting updated_at: %s", err))
}
if err = d.Set("state", toolchainTool.State); err != nil {
return diag.FromErr(fmt.Errorf("Error setting state: %s", err))
}
if err = d.Set("tool_id", toolchainTool.ID); err != nil {
return diag.FromErr(fmt.Errorf("Error setting tool_id: %s", err))
}
return nil
}
func resourceIBMCdToolchainToolHashicorpvaultUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cdToolchainClient, err := meta.(conns.ClientSession).CdToolchainV2()
if err != nil {
return diag.FromErr(err)
}
updateToolOptions := &cdtoolchainv2.UpdateToolOptions{}
parts, err := flex.SepIdParts(d.Id(), "/")
if err != nil {
return diag.FromErr(err)
}
updateToolOptions.SetToolchainID(parts[0])
updateToolOptions.SetToolID(parts[1])
hasChange := false
patchVals := &cdtoolchainv2.ToolchainToolPrototypePatch{}
if d.HasChange("toolchain_id") {
return diag.FromErr(fmt.Errorf("Cannot update resource property \"%s\" with the ForceNew annotation."+
" The resource must be re-created to update this property.", "toolchain_id"))
}
if d.HasChange("name") {
newName := d.Get("name").(string)
patchVals.Name = &newName
hasChange = true
}
if d.HasChange("parameters") {
parameters := GetParametersForUpdate(d, ResourceIBMCdToolchainToolHashicorpvault(), nil)
patchVals.Parameters = parameters
hasChange = true
}
if hasChange {
updateToolOptions.ToolchainToolPrototypePatch, _ = patchVals.AsPatch()
_, response, err := cdToolchainClient.UpdateToolWithContext(context, updateToolOptions)
if err != nil {
log.Printf("[DEBUG] UpdateToolWithContext failed %s\n%s", err, response)
return diag.FromErr(fmt.Errorf("UpdateToolWithContext failed %s\n%s", err, response))
}
}
return resourceIBMCdToolchainToolHashicorpvaultRead(context, d, meta)
}
func resourceIBMCdToolchainToolHashicorpvaultDelete(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cdToolchainClient, err := meta.(conns.ClientSession).CdToolchainV2()
if err != nil {
return diag.FromErr(err)
}
deleteToolOptions := &cdtoolchainv2.DeleteToolOptions{}
parts, err := flex.SepIdParts(d.Id(), "/")
if err != nil {
return diag.FromErr(err)
}
deleteToolOptions.SetToolchainID(parts[0])
deleteToolOptions.SetToolID(parts[1])
response, err := cdToolchainClient.DeleteToolWithContext(context, deleteToolOptions)
if err != nil {
log.Printf("[DEBUG] DeleteToolWithContext failed %s\n%s", err, response)
return diag.FromErr(fmt.Errorf("DeleteToolWithContext failed %s\n%s", err, response))
}
d.SetId("")
return nil
}
func resourceIBMCdToolchainToolHashicorpvaultToolModelReferentToMap(model *cdtoolchainv2.ToolModelReferent) (map[string]interface{}, error) {
modelMap := make(map[string]interface{})
if model.UIHref != nil {
modelMap["ui_href"] = model.UIHref
}
if model.APIHref != nil {
modelMap["api_href"] = model.APIHref
}
return modelMap, nil
}