generated from hashicorp/terraform-provider-scaffolding-framework
-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathresource_project.go
612 lines (516 loc) · 19.9 KB
/
resource_project.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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
package provider
import (
"context"
"fmt"
"net/http"
"github.com/hashicorp/terraform-plugin-framework-validators/float64validator"
"github.com/hashicorp/terraform-plugin-framework-validators/int64validator"
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
"github.com/hashicorp/terraform-plugin-framework/attr"
"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/float64default"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/int64default"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/int64planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/objectdefault"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringdefault"
"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-framework/types/basetypes"
"github.com/hashicorp/terraform-plugin-log/tflog"
"golang.org/x/exp/slices"
)
var _ resource.Resource = &ProjectResource{}
var _ resource.ResourceWithImportState = &ProjectResource{}
func NewProjectResource() resource.Resource {
return &ProjectResource{}
}
type ProjectResource struct {
client *http.Client
}
type ProjectResourceBranchEndpointModel struct {
Id types.String `tfsdk:"id"`
Host types.String `tfsdk:"host"`
MinCu types.Float64 `tfsdk:"min_cu"`
MaxCu types.Float64 `tfsdk:"max_cu"`
ComputeProvisioner types.String `tfsdk:"compute_provisioner"`
SuspendTimeout types.Int64 `tfsdk:"suspend_timeout"`
}
var branchEndpointAttrTypes = map[string]attr.Type{
"id": types.StringType,
"host": types.StringType,
"min_cu": types.Float64Type,
"max_cu": types.Float64Type,
"compute_provisioner": types.StringType,
"suspend_timeout": types.Int64Type,
}
type ProjectResourceBranchModel struct {
Id types.String `tfsdk:"id"`
Name types.String `tfsdk:"name"`
Endpoint types.Object `tfsdk:"endpoint"`
}
var branchAttrTypes = map[string]attr.Type{
"id": types.StringType,
"name": types.StringType,
"endpoint": types.ObjectType{
AttrTypes: branchEndpointAttrTypes,
},
}
type ProjectResourceModel struct {
Id types.String `tfsdk:"id"`
Name types.String `tfsdk:"name"`
PlatformId types.String `tfsdk:"platform_id"`
RegionId types.String `tfsdk:"region_id"`
OrgId types.String `tfsdk:"org_id"`
PgVersion types.Int64 `tfsdk:"pg_version"`
Branch types.Object `tfsdk:"branch"`
}
func (r *ProjectResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_project"
}
func (r *ProjectResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
MarkdownDescription: "Neon project.",
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
MarkdownDescription: "Identifier of the project.",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"name": schema.StringAttribute{
MarkdownDescription: "Name of the project.",
Required: true,
Validators: []validator.String{
stringvalidator.UTF8LengthAtLeast(1),
stringvalidator.UTF8LengthAtMost(64),
},
},
"platform_id": schema.StringAttribute{
MarkdownDescription: "Platform of the project.",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"region_id": schema.StringAttribute{
MarkdownDescription: "Region of the project.",
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
Validators: []validator.String{
stringvalidator.UTF8LengthAtLeast(1),
},
},
"org_id": schema.StringAttribute{
MarkdownDescription: "Organization of the project.",
Optional: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"pg_version": schema.Int64Attribute{
MarkdownDescription: "PostgreSQL version of the project. **Default** `15`.",
Computed: true,
Optional: true,
Default: int64default.StaticInt64(15),
PlanModifiers: []planmodifier.Int64{
int64planmodifier.RequiresReplace(),
},
Validators: []validator.Int64{
int64validator.OneOf(14, 15, 16, 17),
},
},
"branch": schema.SingleNestedAttribute{
MarkdownDescription: "Primary branch settings of the project.",
Optional: true,
Computed: true,
Default: objectdefault.StaticValue(
types.ObjectValueMust(
branchAttrTypes,
map[string]attr.Value{
"id": types.StringUnknown(),
"name": types.StringValue("main"),
"endpoint": types.ObjectValueMust(
branchEndpointAttrTypes,
map[string]attr.Value{
"id": types.StringUnknown(),
"host": types.StringUnknown(),
"min_cu": types.Float64Value(0.25),
"max_cu": types.Float64Value(0.25),
"compute_provisioner": types.StringValue("k8s-neonvm"),
"suspend_timeout": types.Int64Value(0),
},
),
},
),
),
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
MarkdownDescription: "Identifier of the branch.",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"name": schema.StringAttribute{
MarkdownDescription: "Name of the branch.",
Optional: true,
Computed: true,
Default: stringdefault.StaticString("main"),
Validators: []validator.String{
stringvalidator.UTF8LengthAtLeast(1),
},
},
"endpoint": schema.SingleNestedAttribute{
MarkdownDescription: "Read-write compute endpoint settings of the branch.",
Optional: true,
Computed: true,
Default: objectdefault.StaticValue(
types.ObjectValueMust(
branchEndpointAttrTypes,
map[string]attr.Value{
"id": types.StringUnknown(),
"host": types.StringUnknown(),
"min_cu": types.Float64Value(0.25),
"max_cu": types.Float64Value(0.25),
"compute_provisioner": types.StringValue("k8s-neonvm"),
"suspend_timeout": types.Int64Value(0),
},
),
),
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
MarkdownDescription: "Identifier of the endpoint.",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"host": schema.StringAttribute{
MarkdownDescription: "Host of the endpoint.",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"min_cu": schema.Float64Attribute{
MarkdownDescription: "Minimum number of compute units for the endpoint. **Default** `0.25`.",
Optional: true,
Computed: true,
Default: float64default.StaticFloat64(0.25),
Validators: []validator.Float64{
float64validator.OneOf(0.25, 0.5, 1, 2, 3, 4, 5, 6, 7),
},
},
"max_cu": schema.Float64Attribute{
MarkdownDescription: "Maximum number of compute units for the endpoint. **Default** `0.25`.",
Optional: true,
Computed: true,
Default: float64default.StaticFloat64(0.25),
Validators: []validator.Float64{
float64validator.OneOf(0.25, 0.5, 1, 2, 3, 4, 5, 6, 7),
},
},
"compute_provisioner": schema.StringAttribute{
MarkdownDescription: "Provisioner of the endpoint.",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"suspend_timeout": schema.Int64Attribute{
MarkdownDescription: "Suspend timeout of the endpoint. **Default** `0`.",
Optional: true,
Computed: true,
Default: int64default.StaticInt64(0),
Validators: []validator.Int64{
int64validator.Between(-1, 604800),
},
},
},
},
},
},
},
}
}
func (r *ProjectResource) 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.(*http.Client)
if !ok {
resp.Diagnostics.AddError(
"Unexpected Resource Configure Type",
fmt.Sprintf("Expected *http.Client, got: %T. Please report this issue to the provider developers.", req.ProviderData),
)
return
}
r.client = client
}
func (r *ProjectResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var data *ProjectResourceModel
var branchData *ProjectResourceBranchModel
var branchEndpointData *ProjectResourceBranchEndpointModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}
input := ProjectCreateInput{
Project: ProjectCreateInputProject{
Name: data.Name.ValueString(),
RegionId: data.RegionId.ValueString(),
OrgId: data.OrgId.ValueStringPointer(),
PgVersion: data.PgVersion.ValueInt64(),
StorePasswords: true,
},
}
resp.Diagnostics.Append(data.Branch.As(ctx, &branchData, basetypes.ObjectAsOptions{})...)
if resp.Diagnostics.HasError() {
return
}
input.Project.Branch = ProjectCreateInputProjectBranch{
Name: branchData.Name.ValueString(),
}
resp.Diagnostics.Append(branchData.Endpoint.As(ctx, &branchEndpointData, basetypes.ObjectAsOptions{})...)
if resp.Diagnostics.HasError() {
return
}
input.Project.DefaultEndpointSettings = ProjectCreateInputProjectDefaultEndpointSettings{
AutoscalingLimitMinCu: branchEndpointData.MinCu.ValueFloat64(),
AutoscalingLimitMaxCu: branchEndpointData.MaxCu.ValueFloat64(),
SuspendTimeoutSeconds: branchEndpointData.SuspendTimeout.ValueInt64(),
}
var project ProjectCreateOutput
err := call(r.client, http.MethodPost, "/projects", input, &project)
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to create project, got error: %s", err))
return
}
tflog.Trace(ctx, "created a project")
// Delete the default database.
err = databaseDelete(r.client, project.Project.Id, project.Branch.Id, project.Databases[0].Name)
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to delete default database, got error: %s", err))
return
}
// Delete the default role.
err = roleDelete(r.client, project.Project.Id, project.Branch.Id, project.Roles[0].Name)
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to delete default role, got error: %s", err))
return
}
data.Id = types.StringValue(project.Project.Id)
data.Name = types.StringValue(project.Project.Name)
data.PlatformId = types.StringValue(project.Project.PlatformId)
data.RegionId = types.StringValue(project.Project.RegionId)
data.PgVersion = types.Int64Value(project.Project.PgVersion)
if project.Project.OrgId != "" {
data.OrgId = types.StringValue(project.Project.OrgId)
}
data.Branch = types.ObjectValueMust(
branchAttrTypes,
map[string]attr.Value{
"id": types.StringValue(project.Branch.Id),
"name": types.StringValue(project.Branch.Name),
"endpoint": types.ObjectValueMust(
branchEndpointAttrTypes,
map[string]attr.Value{
"id": types.StringValue(project.Endpoints[0].Id),
"host": types.StringValue(project.Endpoints[0].Host),
"min_cu": types.Float64Value(project.Endpoints[0].AutoscalingLimitMinCu),
"max_cu": types.Float64Value(project.Endpoints[0].AutoscalingLimitMaxCu),
"compute_provisioner": types.StringValue(project.Endpoints[0].ComputeProvisioner),
"suspend_timeout": types.Int64Value(project.Endpoints[0].SuspendTimeoutSeconds),
},
),
},
)
resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
}
func (r *ProjectResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var data *ProjectResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}
var project ProjectOutput
err := get(r.client, fmt.Sprintf("/projects/%s", data.Id.ValueString()), &project)
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to read project, got error: %s", err))
return
}
// Get the primary branch for the project
branch, err := readPrimaryBranch(r.client, project.Project.Id)
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to read primary branch of the project, got error: %s", err))
return
}
// Get the endpoint for the primary branch
endpoint, err := branchEndpoint(r.client, project.Project.Id, branch.Id, true)
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to read endpoint of the primary branch, got error: %s", err))
return
}
data.Id = types.StringValue(project.Project.Id)
data.Name = types.StringValue(project.Project.Name)
data.PlatformId = types.StringValue(project.Project.PlatformId)
data.RegionId = types.StringValue(project.Project.RegionId)
data.PgVersion = types.Int64Value(project.Project.PgVersion)
if project.Project.OrgId != "" {
data.OrgId = types.StringValue(project.Project.OrgId)
}
data.Branch = types.ObjectValueMust(
branchAttrTypes,
map[string]attr.Value{
"id": types.StringValue(branch.Id),
"name": types.StringValue(branch.Name),
"endpoint": types.ObjectValueMust(
branchEndpointAttrTypes,
map[string]attr.Value{
"id": types.StringValue(endpoint.Id),
"host": types.StringValue(endpoint.Host),
"min_cu": types.Float64Value(endpoint.AutoscalingLimitMinCu),
"max_cu": types.Float64Value(endpoint.AutoscalingLimitMaxCu),
"compute_provisioner": types.StringValue(endpoint.ComputeProvisioner),
"suspend_timeout": types.Int64Value(endpoint.SuspendTimeoutSeconds),
},
),
},
)
resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
}
func (r *ProjectResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var data *ProjectResourceModel
var branchData *ProjectResourceBranchModel
var branchEndpointData *ProjectResourceBranchEndpointModel
var state *ProjectResourceModel
var branchState *ProjectResourceBranchModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
input := ProjectUpdateInput{
Project: ProjectUpdateInputProject{
Name: data.Name.ValueString(),
},
}
var project ProjectOutput
err := call(r.client, http.MethodPatch, fmt.Sprintf("/projects/%s", data.Id.ValueString()), input, &project)
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to update project, got error: %s", err))
return
}
tflog.Trace(ctx, "updated a project")
resp.Diagnostics.Append(data.Branch.As(ctx, &branchData, basetypes.ObjectAsOptions{})...)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(state.Branch.As(ctx, &branchState, basetypes.ObjectAsOptions{})...)
if resp.Diagnostics.HasError() {
return
}
branch := Branch{
Id: branchState.Id.ValueString(),
Name: branchState.Name.ValueString(),
}
// Need to do this check because we can't update the branch with the same name
if branchData.Name.ValueString() != branchState.Name.ValueString() {
branchInput := BranchUpdateInput{
Branch: BranchUpdateInputBranch{
Name: branchData.Name.ValueString(),
},
}
branchOutput, err := branchUpdate(r.client, data.Id.ValueString(), branchData.Id.ValueString(), branchInput)
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to update branch, got error: %s", err))
return
}
tflog.Trace(ctx, "updated a branch")
branch = branchOutput.Branch
}
resp.Diagnostics.Append(branchData.Endpoint.As(ctx, &branchEndpointData, basetypes.ObjectAsOptions{})...)
if resp.Diagnostics.HasError() {
return
}
endpointInput := EndpointUpdateInput{
Endpoint: EndpointUpdateInputEndpoint{
AutoscalingLimitMinCu: branchEndpointData.MinCu.ValueFloat64(),
AutoscalingLimitMaxCu: branchEndpointData.MaxCu.ValueFloat64(),
SuspendTimeoutSeconds: branchEndpointData.SuspendTimeout.ValueInt64(),
},
}
endpoint, err := endpointUpdate(r.client, data.Id.ValueString(), branchEndpointData.Id.ValueString(), endpointInput)
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to update endpoint, got error: %s", err))
return
}
tflog.Trace(ctx, "updated an endpoint")
data.Id = types.StringValue(project.Project.Id)
data.Name = types.StringValue(project.Project.Name)
data.PlatformId = types.StringValue(project.Project.PlatformId)
data.RegionId = types.StringValue(project.Project.RegionId)
data.PgVersion = types.Int64Value(project.Project.PgVersion)
if project.Project.OrgId != "" {
data.OrgId = types.StringValue(project.Project.OrgId)
}
data.Branch = types.ObjectValueMust(
branchAttrTypes,
map[string]attr.Value{
"id": types.StringValue(branch.Id),
"name": types.StringValue(branch.Name),
"endpoint": types.ObjectValueMust(
branchEndpointAttrTypes,
map[string]attr.Value{
"id": types.StringValue(endpoint.Endpoint.Id),
"host": types.StringValue(endpoint.Endpoint.Host),
"min_cu": types.Float64Value(endpoint.Endpoint.AutoscalingLimitMinCu),
"max_cu": types.Float64Value(endpoint.Endpoint.AutoscalingLimitMaxCu),
"compute_provisioner": types.StringValue(endpoint.Endpoint.ComputeProvisioner),
"suspend_timeout": types.Int64Value(endpoint.Endpoint.SuspendTimeoutSeconds),
},
),
},
)
resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
}
func (r *ProjectResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var data *ProjectResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}
_, err := delete(r.client, fmt.Sprintf("/projects/%s", data.Id.ValueString()))
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to delete project, got error: %s", err))
return
}
tflog.Trace(ctx, "deleted a project")
}
func (r *ProjectResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp)
}
func readPrimaryBranch(client *http.Client, projectId string) (Branch, error) {
var branch Branch
// Read all branches
branches, err := branchList(client, projectId)
if err != nil {
return branch, err
}
// Get the primary branch
branchIdx := slices.IndexFunc(branches.Branches, func(branch Branch) bool {
return branch.Primary
})
return branches.Branches[branchIdx], nil
}