/
password_resource.go
488 lines (441 loc) · 17.2 KB
/
password_resource.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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package provider
import (
"context"
"fmt"
"strings"
"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/float64planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/planetscale/terraform-provider-planetscale/internal/client/planetscale"
)
// Ensure provider defined types fully satisfy framework interfaces.
var _ resource.Resource = &passwordResource{}
var _ resource.ResourceWithImportState = &passwordResource{}
func newPasswordResource() resource.Resource {
return &passwordResource{}
}
// passwordResource defines the resource implementation.
type passwordResource struct {
client *planetscale.Client
}
type passwordResourceModel struct {
Organization types.String `tfsdk:"organization"`
Database types.String `tfsdk:"database"`
Branch types.String `tfsdk:"branch"`
Id types.String `tfsdk:"id"`
Name types.String `tfsdk:"name"`
AccessHostUrl types.String `tfsdk:"access_host_url"`
Actor types.Object `tfsdk:"actor"`
CreatedAt types.String `tfsdk:"created_at"`
DatabaseBranch types.Object `tfsdk:"database_branch"`
DeletedAt types.String `tfsdk:"deleted_at"`
ExpiresAt types.String `tfsdk:"expires_at"`
Region types.Object `tfsdk:"region"`
Renewable types.Bool `tfsdk:"renewable"`
Role types.String `tfsdk:"role"`
TtlSeconds types.Float64 `tfsdk:"ttl_seconds"`
Username types.String `tfsdk:"username"`
PlainText types.String `tfsdk:"plaintext"`
// manually removed from spec because currently buggy
// Integrations types.List `tfsdk:"integrations"`
}
func passwordResourceFromClient(ctx context.Context, password *planetscale.Password, organization, database, branch, plainText types.String, diags diag.Diagnostics) *passwordResourceModel {
if password == nil {
return nil
}
actor, diags := types.ObjectValueFrom(ctx, actorResourceAttrTypes, password.Actor)
diags.Append(diags...)
databaseBranch, diags := types.ObjectValueFrom(ctx, databaseBranchResourceAttrTypes, password.DatabaseBranch)
diags.Append(diags...)
region, diags := types.ObjectValueFrom(ctx, regionResourceAttrTypes, password.Region)
diags.Append(diags...)
return &passwordResourceModel{
Organization: organization,
Database: database,
Branch: branch,
Name: types.StringValue(password.Name),
AccessHostUrl: types.StringValue(password.AccessHostUrl),
Actor: actor,
CreatedAt: types.StringValue(password.CreatedAt),
DatabaseBranch: databaseBranch,
DeletedAt: types.StringPointerValue(password.DeletedAt),
ExpiresAt: types.StringPointerValue(password.ExpiresAt),
Id: types.StringValue(password.Id),
Region: region,
Renewable: types.BoolValue(password.Renewable),
Role: types.StringValue(password.Role),
TtlSeconds: types.Float64Value(password.TtlSeconds),
Username: types.StringPointerValue(password.Username),
PlainText: plainText,
// manually removed from spec because currently buggy
// Integrations: stringsToListValue(password.Integrations, diags),
}
}
func passwordWithPlaintextResourceFromClient(ctx context.Context, password *planetscale.PasswordWithPlaintext, organization, database, branch types.String, diags diag.Diagnostics) *passwordResourceModel {
if password == nil {
return nil
}
actor, diags := types.ObjectValueFrom(ctx, actorResourceAttrTypes, password.Actor)
diags.Append(diags...)
databaseBranch, diags := types.ObjectValueFrom(ctx, databaseBranchResourceAttrTypes, password.DatabaseBranch)
diags.Append(diags...)
region, diags := types.ObjectValueFrom(ctx, regionResourceAttrTypes, password.Region)
diags.Append(diags...)
return &passwordResourceModel{
Organization: organization,
Database: database,
Branch: branch,
Name: types.StringValue(password.Name),
AccessHostUrl: types.StringValue(password.AccessHostUrl),
Actor: actor,
CreatedAt: types.StringValue(password.CreatedAt),
DatabaseBranch: databaseBranch,
DeletedAt: types.StringPointerValue(password.DeletedAt),
ExpiresAt: types.StringPointerValue(password.ExpiresAt),
Id: types.StringValue(password.Id),
Region: region,
Renewable: types.BoolValue(password.Renewable),
Role: types.StringValue(password.Role),
TtlSeconds: types.Float64Value(password.TtlSeconds),
Username: types.StringPointerValue(password.Username),
PlainText: types.StringValue(password.PlainText),
// manually removed from spec because currently buggy
// Integrations: stringsToListValue(password.Integrations, diags),
}
}
func (r *passwordResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_password"
}
func (r *passwordResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "A PlanetScale database password.",
MarkdownDescription: "A PlanetScale database password.",
Attributes: map[string]schema.Attribute{
"organization": schema.StringAttribute{
Description: "The organization this database branch password belongs to.",
Required: true, PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"database": schema.StringAttribute{
Description: "The datanase this branch password belongs to.",
Required: true, PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"branch": schema.StringAttribute{
Description: "The branch this password belongs to.",
Required: true, PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"role": schema.StringAttribute{
Description: "The role for the password.",
Optional: true,
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplaceIfConfigured(),
},
},
"ttl_seconds": schema.Float64Attribute{
Description: "Time to live (in seconds) for the password. The password will be invalid and unrenewable when TTL has passed.",
Optional: true,
Computed: true,
PlanModifiers: []planmodifier.Float64{
float64planmodifier.RequiresReplaceIfConfigured(),
},
},
// updatable
"name": schema.StringAttribute{
Description: "The display name for the password.",
Optional: true,
},
// read-only
"id": schema.StringAttribute{
Description: "The ID for the password.",
Computed: true,
},
"actor": schema.SingleNestedAttribute{
Description: "The actor that created this branch.",
Computed: true, Attributes: actorResourceSchemaAttribute,
},
"database_branch": schema.SingleNestedAttribute{
Description: "The branch this password is allowed to access.",
Computed: true, Attributes: databaseBranchResourceAttribute,
},
"region": schema.SingleNestedAttribute{
Description: "The region in which this password can be used.",
Computed: true, Attributes: regionResourceSchemaAttribute,
},
"access_host_url": schema.StringAttribute{
Description: "The host URL for the password.",
Computed: true,
},
"created_at": schema.StringAttribute{
Description: "When the password was created.",
Computed: true,
},
"deleted_at": schema.StringAttribute{
Description: "When the password was deleted.",
Computed: true,
},
"expires_at": schema.StringAttribute{
Description: "When the password will expire.",
Computed: true,
},
"renewable": schema.BoolAttribute{
Description: "Whether or not the password can be renewed.",
Computed: true,
},
"username": schema.StringAttribute{
Description: "The username for the password.",
Computed: true,
},
// read-only, sensitive
"plaintext": schema.StringAttribute{
Description: "The plaintext password, only available if the password was created by this provider.",
Sensitive: true, Computed: true},
// manually removed from spec because currently buggy
// "integrations": schema.ListAttribute{Computed: true, ElementType: types.StringType},
},
}
}
func (r *passwordResource) 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.(*planetscale.Client)
if !ok {
resp.Diagnostics.AddError(
"Unexpected Resource Configure Type",
fmt.Sprintf("Expected *planetscale.Client, got: %T. Please report this issue to the provider developers.", req.ProviderData),
)
return
}
r.client = client
}
func (r *passwordResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var data *passwordResourceModel
tflog.Info(ctx, "getting current password resource from plan")
resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}
org := data.Organization
database := data.Database
branch := data.Branch
if org.IsNull() || org.IsUnknown() || org.ValueString() == "" {
resp.Diagnostics.AddAttributeError(path.Root("organization"), "organization is required", "an organization must be provided and cannot be empty")
return
}
if database.IsNull() || database.IsUnknown() || database.ValueString() == "" {
resp.Diagnostics.AddAttributeError(path.Root("database"), "database is required", "a database must be provided and cannot be empty")
return
}
if branch.IsNull() || branch.IsUnknown() || branch.ValueString() == "" {
resp.Diagnostics.AddAttributeError(path.Root("branch"), "branch is required", "a branch must be provided and cannot be empty")
return
}
name := data.Name
role := data.Role
ttl := data.TtlSeconds
createReq := planetscale.CreatePasswordReq{
Name: name.ValueStringPointer(),
Role: role.ValueStringPointer(),
Ttl: ttl.ValueFloat64Pointer(),
}
res, err := r.client.CreatePassword(ctx, org.ValueString(), database.ValueString(), branch.ValueString(), createReq)
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to create password, got error: %s", err))
return
}
if res == nil {
resp.Diagnostics.AddError("Unable to create passwords", "no data")
return
}
data = passwordWithPlaintextResourceFromClient(
ctx,
&res.PasswordWithPlaintext,
data.Organization,
data.Database,
data.Branch,
resp.Diagnostics,
)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
}
func (r *passwordResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var data *passwordResourceModel
tflog.Info(ctx, "getting current password resource from state")
// Read Terraform prior state data into the model
resp.Diagnostics.Append(req.State.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}
org := data.Organization
database := data.Database
branch := data.Branch
id := data.Id
if org.IsNull() || org.IsUnknown() || org.ValueString() == "" {
resp.Diagnostics.AddAttributeError(path.Root("organization"), "organization is required", "an organization must be provided and cannot be empty")
return
}
if database.IsNull() || database.IsUnknown() || database.ValueString() == "" {
resp.Diagnostics.AddAttributeError(path.Root("database"), "database is required", "a database must be provided and cannot be empty")
return
}
if branch.IsNull() || branch.IsUnknown() || branch.ValueString() == "" {
resp.Diagnostics.AddAttributeError(path.Root("branch"), "branch is required", "a branch must be provided and cannot be empty")
return
}
if id.IsNull() || id.IsUnknown() || id.ValueString() == "" {
resp.Diagnostics.AddAttributeError(path.Root("id"), "id is required", "an ID must be provided and cannot be empty")
return
}
res, err := r.client.GetPassword(ctx,
org.ValueString(),
database.ValueString(),
branch.ValueString(),
id.ValueString(),
nil, // not sure why this would need a region id
)
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to read password, got error: %s", err))
return
}
data = passwordResourceFromClient(
ctx,
&res.Password,
data.Organization,
data.Database,
data.Branch,
data.PlainText,
resp.Diagnostics,
)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
}
func (r *passwordResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var (
old *passwordResourceModel
data *passwordResourceModel
)
resp.Diagnostics.Append(req.State.Get(ctx, &old)...)
resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}
org := data.Organization
database := data.Database
branch := data.Branch
id := data.Id
if org.IsNull() || org.IsUnknown() || org.ValueString() == "" {
resp.Diagnostics.AddAttributeError(path.Root("organization"), "organization is required", "an organization must be provided and cannot be empty")
return
}
if database.IsNull() || database.IsUnknown() || database.ValueString() == "" {
resp.Diagnostics.AddAttributeError(path.Root("database"), "database is required", "a database must be provided and cannot be empty")
return
}
if branch.IsNull() || branch.IsUnknown() || branch.ValueString() == "" {
resp.Diagnostics.AddAttributeError(path.Root("branch"), "branch is required", "a branch must be provided and cannot be empty")
return
}
if id.IsNull() || id.IsUnknown() || id.ValueString() == "" {
resp.Diagnostics.AddAttributeError(path.Root("id"), "id is required", "an ID must be provided and cannot be empty")
return
}
changedUpdatableSettings := false
name := stringIfDifferent(old.Name, data.Name, &changedUpdatableSettings)
var state *passwordResourceModel
if changedUpdatableSettings && name != nil {
updateReq := planetscale.UpdatePasswordReq{
Name: *name,
}
res, err := r.client.UpdatePassword(
ctx,
org.ValueString(),
database.ValueString(),
branch.ValueString(),
id.ValueString(),
updateReq,
)
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to update password settings, got error: %s", err))
return
}
state = passwordResourceFromClient(
ctx,
&res.Password,
data.Organization,
data.Database,
data.Branch,
data.PlainText,
resp.Diagnostics,
)
if resp.Diagnostics.HasError() {
return
}
}
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func (r *passwordResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var data *passwordResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}
org := data.Organization
database := data.Database
branch := data.Branch
id := data.Id
if org.IsNull() || org.IsUnknown() || org.ValueString() == "" {
resp.Diagnostics.AddAttributeError(path.Root("organization"), "organization is required", "an organization must be provided and cannot be empty")
return
}
if database.IsNull() || database.IsUnknown() || database.ValueString() == "" {
resp.Diagnostics.AddAttributeError(path.Root("database"), "database is required", "a database must be provided and cannot be empty")
return
}
if branch.IsNull() || branch.IsUnknown() || branch.ValueString() == "" {
resp.Diagnostics.AddAttributeError(path.Root("branch"), "branch is required", "a branch must be provided and cannot be empty")
return
}
if id.IsNull() || id.IsUnknown() || id.ValueString() == "" {
resp.Diagnostics.AddAttributeError(path.Root("id"), "id is required", "an ID must be provided and cannot be empty")
return
}
res, err := r.client.DeletePassword(ctx, org.ValueString(), database.ValueString(), branch.ValueString(), id.ValueString())
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to delete password, got error: %s", err))
return
}
_ = res
}
func (r *passwordResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
idParts := strings.Split(req.ID, ",")
if len(idParts) != 4 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" || idParts[3] == "" {
resp.Diagnostics.AddError(
"Unexpected Import Identifier",
fmt.Sprintf("Expected import identifier with format: organization,database,name,id. Got: %q", req.ID),
)
return
}
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("organization"), idParts[0])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("database"), idParts[1])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("branch"), idParts[2])...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), idParts[3])...)
}