-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathresource.go
More file actions
496 lines (448 loc) · 16.2 KB
/
Copy pathresource.go
File metadata and controls
496 lines (448 loc) · 16.2 KB
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
package externalsubnet
import (
"context"
"fmt"
"github.com/hashicorp/terraform-plugin-framework-nettypes/cidrtypes"
"github.com/hashicorp/terraform-plugin-framework-timeouts/resource/timeouts"
"github.com/hashicorp/terraform-plugin-framework-validators/int64validator"
"github.com/hashicorp/terraform-plugin-framework-validators/resourcevalidator"
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
"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/int64planmodifier"
"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/oxidecomputer/oxide.go/oxide"
"github.com/oxidecomputer/terraform-provider-oxide/internal/provider/shared"
oxidevalidator "github.com/oxidecomputer/terraform-provider-oxide/internal/provider/validator"
)
// Ensure the implementation satisfies the expected interfaces.
var (
_ resource.Resource = (*Resource)(nil)
_ resource.ResourceWithConfigure = (*Resource)(nil)
_ resource.ResourceWithImportState = (*Resource)(nil)
_ resource.ResourceWithConfigValidators = (*Resource)(nil)
)
// NewResource is a helper function to simplify the provider implementation.
func NewResource() resource.Resource {
return &Resource{}
}
// Resource is the resource implementation.
type Resource struct {
client *oxide.Client
}
type ResourceModel struct {
ID types.String `tfsdk:"id"`
Name types.String `tfsdk:"name"`
Description types.String `tfsdk:"description"`
ProjectID types.String `tfsdk:"project_id"`
Subnet cidrtypes.IPPrefix `tfsdk:"subnet"`
PrefixLen types.Int64 `tfsdk:"prefix_len"`
SubnetPoolID types.String `tfsdk:"subnet_pool_id"`
IPVersion types.String `tfsdk:"ip_version"`
SubnetPoolMemberID types.String `tfsdk:"subnet_pool_member_id"`
InstanceID types.String `tfsdk:"instance_id"`
TimeCreated types.String `tfsdk:"time_created"`
TimeModified types.String `tfsdk:"time_modified"`
Timeouts timeouts.Value `tfsdk:"timeouts"`
}
// Metadata returns the resource type name.
func (r *Resource) Metadata(
_ context.Context,
req resource.MetadataRequest,
resp *resource.MetadataResponse,
) {
resp.TypeName = "oxide_external_subnet"
}
// Configure adds the provider configured client to the data source.
func (r *Resource) Configure(
_ context.Context,
req resource.ConfigureRequest,
_ *resource.ConfigureResponse,
) {
if req.ProviderData == nil {
return
}
r.client = req.ProviderData.(*oxide.Client)
}
// ImportState imports an external subnet using its ID.
func (r *Resource) ImportState(
ctx context.Context,
req resource.ImportStateRequest,
resp *resource.ImportStateResponse,
) {
resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp)
}
// ConfigValidators returns the config validators for the resource.
func (r *Resource) ConfigValidators(_ context.Context) []resource.ConfigValidator {
return []resource.ConfigValidator{
resourcevalidator.ExactlyOneOf(
path.MatchRoot("subnet"),
path.MatchRoot("prefix_len"),
),
}
}
// Schema defines the schema for the resource.
func (r *Resource) Schema(
ctx context.Context,
_ resource.SchemaRequest,
resp *resource.SchemaResponse,
) {
resp.Schema = schema.Schema{
MarkdownDescription: "This resource manages external subnets allocated from subnet pools.",
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
Computed: true,
Description: "Unique, immutable, system-controlled identifier of the external subnet.",
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"name": schema.StringAttribute{
Required: true,
Description: "Unique, mutable, user-controlled identifier for the external subnet.",
},
"description": schema.StringAttribute{
Required: true,
Description: "Human-readable free-form text about the external subnet.",
},
"project_id": schema.StringAttribute{
Required: true,
Description: "Project ID where this external subnet is located.",
Validators: []validator.String{
oxidevalidator.IsUUID(),
},
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"subnet": schema.StringAttribute{
Optional: true,
Computed: true,
CustomType: cidrtypes.IPPrefixType{},
MarkdownDescription: "The subnet CIDR to reserve. Must be available in the pool. Conflicts with `prefix_len`. If unset, a subnet will be automatically allocated with the specified `prefix_len`.",
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplaceIfConfigured(),
stringplanmodifier.UseStateForUnknown(),
},
Validators: []validator.String{
stringvalidator.ConflictsWith(path.MatchRoot("prefix_len")),
stringvalidator.ConflictsWith(path.MatchRoot("subnet_pool_id")),
stringvalidator.ConflictsWith(path.MatchRoot("ip_version")),
},
},
"prefix_len": schema.Int64Attribute{
Optional: true,
MarkdownDescription: "The prefix length for automatic subnet allocation (e.g., 24 for a /24). Conflicts with `subnet`. Required when using automatic allocation.",
PlanModifiers: []planmodifier.Int64{
int64planmodifier.RequiresReplace(),
},
Validators: []validator.Int64{
int64validator.ConflictsWith(path.MatchRoot("subnet")),
int64validator.Between(1, 128),
},
},
"subnet_pool_id": schema.StringAttribute{
Optional: true,
Computed: true,
MarkdownDescription: "Subnet pool ID to allocate from. If unset when using automatic allocation (`prefix_len`), the silo's default subnet pool is used. Conflicts with `subnet`.",
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplaceIfConfigured(),
stringplanmodifier.UseStateForUnknown(),
},
Validators: []validator.String{
oxidevalidator.IsUUID(),
stringvalidator.ConflictsWith(path.MatchRoot("subnet")),
},
},
"ip_version": schema.StringAttribute{
Optional: true,
MarkdownDescription: "IP version to use when multiple default pools exist. Required if both IPv4 and IPv6 default subnet pools are configured for the silo. Possible values: `v4`, `v6`. Conflicts with `subnet`.",
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
Validators: []validator.String{
stringvalidator.ConflictsWith(path.MatchRoot("subnet")),
stringvalidator.OneOf(
string(oxide.IpVersionV4),
string(oxide.IpVersionV6),
),
},
},
"subnet_pool_member_id": schema.StringAttribute{
Computed: true,
Description: "The subnet pool member this subnet was allocated from.",
},
"instance_id": schema.StringAttribute{
Computed: true,
Description: "Instance ID this external subnet is attached to, if any.",
},
"time_created": schema.StringAttribute{
Computed: true,
Description: "Timestamp when this external subnet was created.",
},
"time_modified": schema.StringAttribute{
Computed: true,
Description: "Timestamp when this external subnet was last modified.",
},
"timeouts": timeouts.Attributes(ctx, timeouts.Opts{
Create: true,
Read: true,
Update: true,
Delete: true,
}),
},
}
}
// Create creates the resource and sets the initial Terraform state.
func (r *Resource) Create(
ctx context.Context,
req resource.CreateRequest,
resp *resource.CreateResponse,
) {
var plan ResourceModel
// Read Terraform plan data into the model
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
createTimeout, diags := plan.Timeouts.Create(ctx, shared.DefaultTimeout())
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
ctx, cancel := context.WithTimeout(ctx, createTimeout)
defer cancel()
params := oxide.ExternalSubnetCreateParams{
Project: oxide.NameOrId(plan.ProjectID.ValueString()),
Body: &oxide.ExternalSubnetCreate{
Name: oxide.Name(plan.Name.ValueString()),
Description: plan.Description.ValueString(),
},
}
if subnet := plan.Subnet.ValueString(); subnet != "" {
// Explicit subnet allocation with pool inferred from CIDR.
ipNet, err := oxide.NewIpNet(subnet)
if err != nil {
resp.Diagnostics.AddError(
"Error parsing subnet CIDR",
err.Error(),
)
return
}
params.Body.Allocator = oxide.ExternalSubnetAllocator{
Value: &oxide.ExternalSubnetAllocatorExplicit{Subnet: ipNet},
}
} else {
// Automatic allocation. The `prefix_len` attribute will always be defined if we reach this
// code due to validation in ConfigValidators.
prefixLen := int(plan.PrefixLen.ValueInt64())
var poolSelector oxide.PoolSelector
if pool := plan.SubnetPoolID.ValueString(); pool != "" {
// Auto subnet allocation from explicit pool.
poolSelector = oxide.PoolSelector{
Value: &oxide.PoolSelectorExplicit{Pool: oxide.NameOrId(pool)},
}
} else {
// Auto subnet allocation from default pool. If there are multiple default pools IP
// version is required.
poolSelector = oxide.PoolSelector{
Value: &oxide.PoolSelectorAuto{
IpVersion: oxide.IpVersion(plan.IPVersion.ValueString()),
},
}
}
params.Body.Allocator = oxide.ExternalSubnetAllocator{
Value: &oxide.ExternalSubnetAllocatorAuto{
PrefixLength: &prefixLen,
PoolSelector: poolSelector,
},
}
}
externalSubnet, err := r.client.ExternalSubnetCreate(ctx, params)
if err != nil {
resp.Diagnostics.AddError(
"Error creating external subnet",
"API error: "+err.Error(),
)
return
}
tflog.Trace(
ctx,
fmt.Sprintf("created external subnet with ID: %v", externalSubnet.Id),
map[string]any{"success": true},
)
// Map response body to schema and populate Computed attribute values
plan.ID = types.StringValue(externalSubnet.Id)
plan.Name = types.StringValue(string(externalSubnet.Name))
plan.Description = types.StringValue(externalSubnet.Description)
plan.ProjectID = types.StringValue(externalSubnet.ProjectId)
plan.Subnet = cidrtypes.NewIPPrefixValue(externalSubnet.Subnet.String())
plan.SubnetPoolID = types.StringValue(externalSubnet.SubnetPoolId)
plan.SubnetPoolMemberID = types.StringValue(externalSubnet.SubnetPoolMemberId)
plan.InstanceID = types.StringValue(externalSubnet.InstanceId)
plan.TimeCreated = types.StringValue(externalSubnet.TimeCreated.String())
plan.TimeModified = types.StringValue(externalSubnet.TimeModified.String())
// Save plan into Terraform state
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
}
// Read refreshes the Terraform state with the latest data.
func (r *Resource) Read(
ctx context.Context,
req resource.ReadRequest,
resp *resource.ReadResponse,
) {
var state ResourceModel
// Read Terraform prior state data into the model
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
readTimeout, diags := state.Timeouts.Read(ctx, shared.DefaultTimeout())
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
ctx, cancel := context.WithTimeout(ctx, readTimeout)
defer cancel()
params := oxide.ExternalSubnetViewParams{
ExternalSubnet: oxide.NameOrId(state.ID.ValueString()),
}
externalSubnet, err := r.client.ExternalSubnetView(ctx, params)
if err != nil {
if shared.Is404(err) {
resp.State.RemoveResource(ctx)
return
}
resp.Diagnostics.AddError(
"Unable to read external subnet:",
"API error: "+err.Error(),
)
return
}
tflog.Trace(
ctx,
fmt.Sprintf("read external subnet with ID: %v", externalSubnet.Id),
map[string]any{"success": true},
)
state.ID = types.StringValue(externalSubnet.Id)
state.Name = types.StringValue(string(externalSubnet.Name))
state.Description = types.StringValue(externalSubnet.Description)
state.ProjectID = types.StringValue(externalSubnet.ProjectId)
state.Subnet = cidrtypes.NewIPPrefixValue(externalSubnet.Subnet.String())
state.SubnetPoolID = types.StringValue(externalSubnet.SubnetPoolId)
state.SubnetPoolMemberID = types.StringValue(externalSubnet.SubnetPoolMemberId)
state.InstanceID = types.StringValue(externalSubnet.InstanceId)
state.TimeCreated = types.StringValue(externalSubnet.TimeCreated.String())
state.TimeModified = types.StringValue(externalSubnet.TimeModified.String())
// Save updated data into Terraform state
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
}
// Update updates the resource and sets the updated Terraform state on success.
func (r *Resource) Update(
ctx context.Context,
req resource.UpdateRequest,
resp *resource.UpdateResponse,
) {
var plan ResourceModel
var state ResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
updateTimeout, diags := plan.Timeouts.Update(ctx, shared.DefaultTimeout())
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
ctx, cancel := context.WithTimeout(ctx, updateTimeout)
defer cancel()
params := oxide.ExternalSubnetUpdateParams{
ExternalSubnet: oxide.NameOrId(state.ID.ValueString()),
Body: &oxide.ExternalSubnetUpdate{
Name: oxide.Name(plan.Name.ValueString()),
Description: plan.Description.ValueString(),
},
}
externalSubnet, err := r.client.ExternalSubnetUpdate(ctx, params)
if err != nil {
resp.Diagnostics.AddError(
"Unable to update external subnet:",
"API error: "+err.Error(),
)
return
}
tflog.Trace(
ctx,
fmt.Sprintf("updated external subnet with ID: %v", externalSubnet.Id),
map[string]any{"success": true},
)
plan.ID = types.StringValue(externalSubnet.Id)
plan.Name = types.StringValue(string(externalSubnet.Name))
plan.Description = types.StringValue(externalSubnet.Description)
plan.ProjectID = types.StringValue(externalSubnet.ProjectId)
plan.Subnet = cidrtypes.NewIPPrefixValue(externalSubnet.Subnet.String())
plan.SubnetPoolID = types.StringValue(externalSubnet.SubnetPoolId)
plan.SubnetPoolMemberID = types.StringValue(externalSubnet.SubnetPoolMemberId)
plan.InstanceID = types.StringValue(externalSubnet.InstanceId)
plan.TimeCreated = types.StringValue(externalSubnet.TimeCreated.String())
plan.TimeModified = types.StringValue(externalSubnet.TimeModified.String())
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
}
// Delete deletes the resource and removes the Terraform state on success.
func (r *Resource) Delete(
ctx context.Context,
req resource.DeleteRequest,
resp *resource.DeleteResponse,
) {
var state ResourceModel
// Read Terraform prior state data into the model
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
deleteTimeout, diags := state.Timeouts.Delete(ctx, shared.DefaultTimeout())
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
ctx, cancel := context.WithTimeout(ctx, deleteTimeout)
defer cancel()
params := oxide.ExternalSubnetDeleteParams{
ExternalSubnet: oxide.NameOrId(state.ID.ValueString()),
}
if err := r.client.ExternalSubnetDelete(ctx, params); err != nil {
if !shared.Is404(err) {
resp.Diagnostics.AddError(
"Error deleting external subnet:",
"API error: "+err.Error(),
)
return
}
}
tflog.Trace(
ctx,
fmt.Sprintf("deleted external subnet with ID: %v", state.ID.ValueString()),
map[string]any{"success": true},
)
}