-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathresource.go
More file actions
331 lines (291 loc) · 8.96 KB
/
Copy pathresource.go
File metadata and controls
331 lines (291 loc) · 8.96 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
// 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 externalsubnetattachment
import (
"context"
"fmt"
"github.com/hashicorp/terraform-plugin-framework-timeouts/resource/timeouts"
"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/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)
)
// 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"`
ExternalSubnetID types.String `tfsdk:"external_subnet_id"`
InstanceID types.String `tfsdk:"instance_id"`
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_attachment"
}
// Configure adds the provider configured client to the resource.
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 attachment using the external subnet ID.
func (r *Resource) ImportState(
ctx context.Context,
req resource.ImportStateRequest,
resp *resource.ImportStateResponse,
) {
resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp)
}
// 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 the attachment of an external subnet to an instance.",
Attributes: map[string]schema.Attribute{
// External subnet attachments don't have their own IDs, and a given external subnet can
// be attached to at most one instance, so we use the instance ID as the ID of the
// attachment.
"id": schema.StringAttribute{
Computed: true,
Description: "Unique identifier for the attachment. Set to the external subnet ID.",
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"external_subnet_id": schema.StringAttribute{
Required: true,
Description: "ID of the external subnet to attach.",
Validators: []validator.String{
oxidevalidator.IsUUID(),
},
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"instance_id": schema.StringAttribute{
Required: true,
Description: "ID of the instance to attach the external subnet to.",
Validators: []validator.String{
oxidevalidator.IsUUID(),
},
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"timeouts": timeouts.Attributes(ctx, timeouts.Opts{
Create: true,
Read: 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
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.ExternalSubnetAttachParams{
ExternalSubnet: oxide.NameOrId(plan.ExternalSubnetID.ValueString()),
Body: &oxide.ExternalSubnetAttach{
Instance: oxide.NameOrId(plan.InstanceID.ValueString()),
},
}
externalSubnet, err := r.client.ExternalSubnetAttach(ctx, params)
if err != nil {
resp.Diagnostics.AddError(
"Error attaching external subnet",
"API error: "+err.Error(),
)
return
}
tflog.Trace(
ctx,
fmt.Sprintf(
"attached external subnet %v to instance %v",
externalSubnet.Id,
externalSubnet.InstanceId,
),
map[string]any{"success": true},
)
plan.ID = types.StringValue(externalSubnet.Id)
plan.ExternalSubnetID = types.StringValue(externalSubnet.Id)
plan.InstanceID = types.StringValue(externalSubnet.InstanceId)
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
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 attachment:",
"API error: "+err.Error(),
)
return
}
// If the subnet is no longer attached to any instance, remove from state.
if externalSubnet.InstanceId == "" {
resp.State.RemoveResource(ctx)
return
}
tflog.Trace(
ctx,
fmt.Sprintf("read external subnet attachment with ID: %v", externalSubnet.Id),
map[string]any{"success": true},
)
state.ID = types.StringValue(externalSubnet.Id)
state.ExternalSubnetID = types.StringValue(externalSubnet.Id)
state.InstanceID = types.StringValue(externalSubnet.InstanceId)
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.
// Only timeouts can change in-place; both mutable attributes trigger replacement.
func (r *Resource) Update(
ctx context.Context,
req resource.UpdateRequest,
resp *resource.UpdateResponse,
) {
var plan ResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
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
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()
// Only detach if the subnet is still attached to the expected
// instance. If it's gone, already detached, or re-attached to
// a different instance out of band, there's nothing to do.
viewParams := oxide.ExternalSubnetViewParams{
ExternalSubnet: oxide.NameOrId(state.ID.ValueString()),
}
externalSubnet, err := r.client.ExternalSubnetView(
ctx, viewParams,
)
if err != nil {
if shared.Is404(err) {
return
}
resp.Diagnostics.AddError(
"Error reading external subnet during delete:",
"API error: "+err.Error(),
)
return
}
if externalSubnet.InstanceId != state.InstanceID.ValueString() {
return
}
detachParams := oxide.ExternalSubnetDetachParams{
ExternalSubnet: oxide.NameOrId(state.ID.ValueString()),
}
if _, err := r.client.ExternalSubnetDetach(
ctx, detachParams,
); err != nil {
if !shared.Is404(err) {
resp.Diagnostics.AddError(
"Error detaching external subnet:",
"API error: "+err.Error(),
)
return
}
}
tflog.Trace(
ctx,
fmt.Sprintf("detached external subnet with ID: %v", state.ID.ValueString()),
map[string]any{"success": true},
)
}