/
resource_credential.go
497 lines (426 loc) · 16.7 KB
/
resource_credential.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
// Copyright 2023 Canonical Ltd.
// Licensed under the Apache License, Version 2.0, see LICENCE file for details.
package provider
import (
"context"
"fmt"
"strconv"
"strings"
"github.com/hashicorp/terraform-plugin-framework-validators/listvalidator"
"github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/booldefault"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/listplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/juju/terraform-provider-juju/internal/juju"
)
// Ensure provider defined types fully satisfy framework interfaces.
var _ resource.Resource = &credentialResource{}
var _ resource.ResourceWithConfigure = &credentialResource{}
var _ resource.ResourceWithImportState = &credentialResource{}
func NewCredentialResource() resource.Resource {
return &credentialResource{}
}
type credentialResource struct {
client *juju.Client
// subCtx is the context created with the new tflog subsystem for applications.
subCtx context.Context
}
type credentialResourceModel struct {
Cloud types.List `tfsdk:"cloud"`
Attributes types.Map `tfsdk:"attributes"`
AuthType types.String `tfsdk:"auth_type"`
ClientCredential types.Bool `tfsdk:"client_credential"`
ControllerCredential types.Bool `tfsdk:"controller_credential"`
Name types.String `tfsdk:"name"`
// ID required by the testing framework
ID types.String `tfsdk:"id"`
}
func (c *credentialResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_credential"
}
func (c *credentialResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "A resource that represent a credential for a cloud.",
Blocks: map[string]schema.Block{
"cloud": schema.ListNestedBlock{
NestedObject: schema.NestedBlockObject{
Attributes: map[string]schema.Attribute{
"name": schema.StringAttribute{
Description: "The name of the cloud",
Required: true,
},
},
},
Description: "JuJu Cloud where the credentials will be used to access",
PlanModifiers: []planmodifier.List{
listplanmodifier.RequiresReplace(),
},
Validators: []validator.List{
listvalidator.SizeAtMost(1),
},
},
},
Attributes: map[string]schema.Attribute{
"attributes": schema.MapAttribute{
Description: "Credential attributes accordingly to the cloud",
ElementType: types.StringType,
Optional: true,
Sensitive: true,
},
"auth_type": schema.StringAttribute{
Description: "Credential authorization type",
Required: true,
},
"client_credential": schema.BoolAttribute{
Description: "Add credentials to the client",
Optional: true,
Computed: true,
Default: booldefault.StaticBool(false),
},
"controller_credential": schema.BoolAttribute{
Description: "Add credentials to the controller",
Optional: true,
Computed: true,
Default: booldefault.StaticBool(true),
},
"name": schema.StringAttribute{
Description: "The name to be assigned to the credential",
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
// ID required by the testing framework
"id": schema.StringAttribute{
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
},
}
}
func (c *credentialResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
// Check first if the client is configured
if c.client == nil {
addClientNotConfiguredError(&resp.Diagnostics, "credential", "create")
return
}
var data credentialResourceModel
// Read Terraform configuration from the request into the resource model
resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}
// Access the fields
// attributes
var attributes map[string]string
resp.Diagnostics.Append(data.Attributes.ElementsAs(ctx, &attributes, false)...)
if resp.Diagnostics.HasError() {
return
}
// auth_type
authType := data.AuthType.ValueString()
// cloud.name
cloudName, errDiag := cloudNameFromCredentialCloud(ctx, data.Cloud.Elements()[0], resp.Diagnostics)
resp.Diagnostics.Append(errDiag...)
if resp.Diagnostics.HasError() {
return
}
// client_credential
clientCredential := data.ClientCredential.ValueBool()
// controller_credential
controllerCredential := data.ControllerCredential.ValueBool()
// name
credentialName := data.Name.ValueString()
// Perform logic or external calls
response, err := c.client.Credentials.CreateCredential(juju.CreateCredentialInput{
Attributes: attributes,
AuthType: authType,
ClientCredential: clientCredential,
CloudName: cloudName,
ControllerCredential: controllerCredential,
Name: credentialName,
})
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to create credential resource, got error: %s", err))
return
}
c.trace(fmt.Sprintf("created credential resource %q", credentialName))
data.ID = types.StringValue(newCredentialIDFrom(credentialName, response.CloudName, clientCredential, controllerCredential))
// Write the state data into the Response.State
resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
}
func (c *credentialResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
// Check first if the client is configured
if c.client == nil {
addClientNotConfiguredError(&resp.Diagnostics, "credential", "read")
return
}
var data credentialResourceModel
// Read Terraform configuration from the request into the resource model
resp.Diagnostics.Append(req.State.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}
// Access prior state data
credentialName, cloudName, clientCredential, controllerCredential := retrieveCredentialDataFromID(data.ID.ValueString(), &resp.Diagnostics,
"read")
if resp.Diagnostics.HasError() {
return
}
// Retrieve updated resource state from upstream
response, err := c.client.Credentials.ReadCredential(juju.ReadCredentialInput{
ClientCredential: clientCredential,
CloudName: cloudName,
ControllerCredential: controllerCredential,
Name: credentialName,
})
if err != nil {
// TODO (cderici): call resp.State.RemoveResource() if NotFound
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to read credential resource, got error: %s", err))
return
}
c.trace(fmt.Sprintf("read credential resource %q", credentialName))
// cloud
cloud, errDiag := newCredentialCloudFromCloudName(ctx, cloudName, resp.Diagnostics)
resp.Diagnostics.Append(errDiag...)
if resp.Diagnostics.HasError() {
return
}
data.Cloud = cloud
// client_credential & controller_credential
data.ClientCredential = types.BoolValue(clientCredential)
data.ControllerCredential = types.BoolValue(controllerCredential)
// retrieve name & auth_type
data.Name = types.StringValue(response.CloudCredential.Label)
data.AuthType = types.StringValue(string(response.CloudCredential.AuthType()))
// retrieve the attributes
receivedAttributes := response.CloudCredential.Attributes()
if len(receivedAttributes) > 0 {
var configuredAttributes map[string]string
resp.Diagnostics.Append(data.Attributes.ElementsAs(ctx, &configuredAttributes, false)...)
if resp.Diagnostics.HasError() {
return
}
for configAtr := range configuredAttributes {
if receivedValue, exists := receivedAttributes[configAtr]; exists {
configuredAttributes[configAtr] = attributeEntryToString(receivedValue)
}
}
if len(configuredAttributes) != 0 {
data.Attributes, errDiag = types.MapValueFrom(ctx, types.StringType, configuredAttributes)
resp.Diagnostics.Append(errDiag...)
if resp.Diagnostics.HasError() {
return
}
}
}
// Write the state data into the Response.State
resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
}
func (c *credentialResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
// Check first if the client is configured
if c.client == nil {
addClientNotConfiguredError(&resp.Diagnostics, "credential", "update")
return
}
var data, state credentialResourceModel
// Read current state of resource prior to the update into the 'state' model
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
// Read desired state of resource after the update into the 'data' model
resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}
// Return early if no change
// No need to check the name and cloud.name because they can't be updated in-place without recreating the resource
// i.e. their change will force recreation of the resource (see the schema)
if data.AuthType.Equal(state.AuthType) &&
data.ClientCredential.Equal(state.ClientCredential) &&
data.ControllerCredential.Equal(state.ControllerCredential) &&
data.Attributes.Equal(state.Attributes) {
return
}
// Extract fields from the ID for the UpdateCredentialInput call
// name & cloud.name fields
credentialName, cloudName, _, _ := retrieveCredentialDataFromID(data.ID.ValueString(), &resp.Diagnostics, "update")
if resp.Diagnostics.HasError() {
return
}
// auth_type
newAuthType := data.AuthType.ValueString()
// client_credential & controller_credential
newClientCredential := data.ClientCredential.ValueBool()
newControllerCredential := data.ControllerCredential.ValueBool()
// attributes
var newAttributes map[string]string
resp.Diagnostics.Append(data.Attributes.ElementsAs(ctx, &newAttributes, false)...)
if resp.Diagnostics.HasError() {
return
}
// Perform external call to modify resource
err := c.client.Credentials.UpdateCredential(juju.UpdateCredentialInput{
Attributes: newAttributes,
AuthType: newAuthType,
ClientCredential: newClientCredential,
CloudName: cloudName,
ControllerCredential: newControllerCredential,
Name: credentialName,
})
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to update credential resource, got error: %s", err))
return
}
c.trace(fmt.Sprintf("updated credential resource %q", credentialName))
data.ID = types.StringValue(newCredentialIDFrom(credentialName, cloudName, newClientCredential, newControllerCredential))
// Write the updated state data into the Response.State
resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
}
func (c *credentialResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
// Check first if the client is configured
if c.client == nil {
addClientNotConfiguredError(&resp.Diagnostics, "credential", "delete")
return
}
var data credentialResourceModel
// Read Terraform configuration from the request into the resource model
resp.Diagnostics.Append(req.State.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}
// Access prior state data
// extract : name & cloud.name, client_credential, controller_credential
credentialName, cloudName, clientCredential, controllerCredential := retrieveCredentialDataFromID(data.ID.ValueString(), &resp.Diagnostics,
"update")
if resp.Diagnostics.HasError() {
return
}
// Perform external call to destroy the resource
err := c.client.Credentials.DestroyCredential(juju.DestroyCredentialInput{
ClientCredential: clientCredential,
CloudName: cloudName,
ControllerCredential: controllerCredential,
Name: credentialName,
})
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to delete credential resource, got error: %s", err))
}
c.trace(fmt.Sprintf("deleted credential resource %q", credentialName))
}
func (c *credentialResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
// Prevent panic if the provider has not been configured.
if req.ProviderData == nil {
return
}
client, ok := req.ProviderData.(*juju.Client)
if !ok {
resp.Diagnostics.AddError(
"Unexpected Resource Configure Type",
fmt.Sprintf("Expected *juju.Client, got: %T. Please report this issue to the provider developers.", req.ProviderData),
)
return
}
c.client = client
// Create the local logging subsystem here, using the TF context when creating it.
c.subCtx = tflog.NewSubsystem(ctx, LogResourceCredential)
}
func (c credentialResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp)
}
func (c *credentialResource) trace(msg string, additionalFields ...map[string]interface{}) {
if c.subCtx == nil {
return
}
//SubsystemTrace(subCtx, "my-subsystem", "hello, world", map[string]interface{}{"foo": 123})
// Output:
// {"@level":"trace","@message":"hello, world","@module":"provider.my-subsystem","foo":123}
tflog.SubsystemTrace(c.subCtx, LogResourceCredential, msg, additionalFields...)
}
func cloudNameFromCredentialCloud(ctx context.Context, element attr.Value, diag diag.Diagnostics) (string,
diag.Diagnostics) {
blockAttributeType := map[string]attr.Type{
"name": types.StringType,
}
cloudObj, errDiag := types.ObjectValueFrom(ctx, blockAttributeType, element)
diag.Append(errDiag...)
if diag.HasError() {
return "", diag
}
return cloudObj.Attributes()["name"].(types.String).ValueString(), diag
}
func newCredentialCloudFromCloudName(ctx context.Context, cloudName string, diag diag.Diagnostics) (types.List, diag.Diagnostics) {
cloudAttributes := map[string]attr.Value{
"name": types.StringValue(cloudName),
}
blockAttributeType := map[string]attr.Type{
"name": types.StringType,
}
cloudBlock, errDiag := types.ObjectValue(blockAttributeType, cloudAttributes)
diag.Append(errDiag...)
if diag.HasError() {
return types.ListNull(types.StringType), diag
}
attrType := types.ObjectType{AttrTypes: blockAttributeType}
cloud, errDiag := types.ListValueFrom(ctx, attrType, []attr.Value{cloudBlock})
diag.Append(errDiag...)
if diag.HasError() {
return types.ListNull(types.StringType), diag
}
return cloud, diag
}
func newCredentialIDFrom(credentialName string, cloudName string, clientCredential bool, controllerCredential bool) string {
return fmt.Sprintf("%s:%s:%t:%t", credentialName, cloudName, clientCredential, controllerCredential)
}
func retrieveCredentialDataFromID(idStr string, diag *diag.Diagnostics, method string) (string, string, bool, bool) {
resID := strings.Split(idStr, ":")
if len(resID) != 4 {
diag.AddError("Provider Error",
fmt.Sprintf("unable to %s credential resource, invalid ID, expected {credentialName, cloudName, "+
"isClient, isController} - given : %q",
method, resID))
return "", "", false, false
}
credentialName, cloudName, clientCredentialStr, controllerCredentialStr := resID[0], resID[1], resID[2], resID[3]
clientCredential, controllerCredential, err := convertOptionsBool(clientCredentialStr, controllerCredentialStr)
if err != nil {
diag.AddError("Provider Error",
fmt.Sprintf("Unable to %s credential resource, got error: %s", method, err))
return "", "", false, false
}
return credentialName, cloudName, clientCredential, controllerCredential
}
func attributeEntryToString(input interface{}) string {
switch t := input.(type) {
case bool:
return strconv.FormatBool(t)
case int64:
return strconv.FormatInt(t, 10)
case float64:
return strconv.FormatFloat(t, 'f', 0, 64)
default:
return input.(string)
}
}
func convertOptionsBool(clientCredentialStr, controllerCredentialStr string) (bool, bool, error) {
clientCredentialBool, err := strconv.ParseBool(clientCredentialStr)
if err != nil {
return false, false, fmt.Errorf("unable to parse client credential from provided ID")
}
controllerCredentialBool, err := strconv.ParseBool(controllerCredentialStr)
if err != nil {
return false, false, fmt.Errorf("unable to parse controller credential from provided ID")
}
return clientCredentialBool, controllerCredentialBool, nil
}