-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathresource.go
More file actions
415 lines (364 loc) · 15.4 KB
/
resource.go
File metadata and controls
415 lines (364 loc) · 15.4 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
package foo
import (
"context"
"fmt"
"strings"
"github.com/hashicorp/terraform-plugin-framework-timeouts/resource/timeouts"
"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/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
fooUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/foo/utils"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/utils"
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
"github.com/stackitcloud/stackit-sdk-go/services/foo" // Import service "foo" from the STACKIT SDK for Go
"github.com/stackitcloud/stackit-sdk-go/services/foo/wait" // Import service "foo" waiters from the STACKIT SDK for Go (in case the service API has asynchronous endpoints)
// (...)
)
// Ensure the implementation satisfies the expected interfaces.
var (
_ resource.Resource = &barResource{}
_ resource.ResourceWithConfigure = &barResource{}
_ resource.ResourceWithImportState = &barResource{}
_ resource.ResourceWithModifyPlan = &barResource{} // not needed for global APIs
)
// Model is the internal model of the terraform resource
type Model struct {
Id types.String `tfsdk:"id"` // needed by TF
ProjectId types.String `tfsdk:"project_id"`
BarId types.String `tfsdk:"bar_id"`
Region types.String `tfsdk:"region"`
MyRequiredField types.String `tfsdk:"my_required_field"`
MyOptionalField types.String `tfsdk:"my_optional_field"`
MyReadOnlyField types.String `tfsdk:"my_read_only_field"`
Timeouts timeouts.Value `tfsdk:"timeouts"`
}
// NewBarResource is a helper function to simplify the provider implementation.
func NewBarResource() resource.Resource {
return &barResource{}
}
// barResource is the resource implementation.
type barResource struct {
client *foo.APIClient
providerData core.ProviderData // not needed for global APIs
}
// Metadata returns the resource type name.
func (r *barResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_foo_bar"
}
// ModifyPlan implements resource.ResourceWithModifyPlan.
// Use the modifier to set the effective region in the current plan. - FYI: This isn't needed for global APIs.
func (r *barResource) ModifyPlan(ctx context.Context, req resource.ModifyPlanRequest, resp *resource.ModifyPlanResponse) { // nolint:gocritic // function signature required by Terraform
// FYI: the ModifyPlan implementation is not needed for global APIs
var configModel Model
// skip initial empty configuration to avoid follow-up errors
if req.Config.Raw.IsNull() {
return
}
resp.Diagnostics.Append(req.Config.Get(ctx, &configModel)...)
if resp.Diagnostics.HasError() {
return
}
var planModel Model
resp.Diagnostics.Append(req.Plan.Get(ctx, &planModel)...)
if resp.Diagnostics.HasError() {
return
}
utils.AdaptRegion(ctx, configModel.Region, &planModel.Region, r.providerData.GetRegion(), resp)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(resp.Plan.Set(ctx, planModel)...)
if resp.Diagnostics.HasError() {
return
}
}
// Configure adds the provider configured client to the resource.
func (r *barResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
providerData, ok := conversion.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics)
if !ok {
return
}
apiClient := fooUtils.ConfigureClient(ctx, &providerData, &resp.Diagnostics)
if resp.Diagnostics.HasError() {
return
}
r.client = apiClient
tflog.Info(ctx, "Foo bar client configured")
}
// Schema defines the schema for the resource.
func (r *barResource) Schema(ctx context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
descriptions := map[string]string{
"main": "Foo bar resource schema.",
"id": "Terraform's internal resource identifier. It is structured as \"`project_id`,`bar_id`\".",
"project_id": "STACKIT Project ID to which the bar is associated.",
"bar_id": "The bar ID.",
"region": "The resource region. If not defined, the provider region is used.",
"my_required_field": "My required field description.",
"my_optional_field": "My optional field description.",
"my_read_only_field": "My read-only field description.",
}
resp.Schema = schema.Schema{
Description: descriptions["main"],
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
Description: descriptions["id"],
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"project_id": schema.StringAttribute{
Description: descriptions["project_id"],
Required: true,
PlanModifiers: []planmodifier.String{
// "RequiresReplace" makes the provider recreate the resource when the field is changed in the configuration
stringplanmodifier.RequiresReplace(),
},
Validators: []validator.String{
// Validators can be used to validate the values set to a field
validate.UUID(),
validate.NoSeparator(),
},
},
"bar_id": schema.StringAttribute{
Description: descriptions["bar_id"],
Computed: true,
},
"region": schema.StringAttribute{ // not needed for global APIs
Optional: true,
// must be computed to allow for storing the override value from the provider
Computed: true,
Description: descriptions["region"],
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"my_required_field": schema.StringAttribute{
Description: descriptions["my_required_field"],
Required: true,
PlanModifiers: []planmodifier.String{
// "RequiresReplace" makes the provider recreate the resource when the field is changed in the configuration
stringplanmodifier.RequiresReplace(),
},
},
"my_optional_field": schema.StringAttribute{
Description: descriptions["my_optional_field"],
Optional: true,
Computed: true,
PlanModifiers: []planmodifier.String{
// "UseStateForUnknown" can be used to copy a prior state value into the planned value. It should be used when it is known that an unconfigured value will remain the same after a resource update
stringplanmodifier.UseStateForUnknown(),
},
},
"my_read_only_field": schema.StringAttribute{
Description: descriptions["my_read_only_field"],
Computed: true,
},
"timeouts": timeouts.AttributesAll(ctx),
},
}
}
// Create creates the resource and sets the initial Terraform state.
func (r *barResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
var model Model
resp.Diagnostics.Append(req.Plan.Get(ctx, &model)...)
if resp.Diagnostics.HasError() {
return
}
waiterTimeout := wait.CreateBarWaitHandler(ctx, r.client, projectId, region, resp.BarId).GetTimeout()
createTimeout, diags := model.Timeouts.Create(ctx, waiterTimeout+core.DefaultTimeoutMargin)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
ctx, cancel := context.WithTimeout(ctx, createTimeout)
defer cancel()
ctx = core.InitProviderContext(ctx)
projectId := model.ProjectId.ValueString()
region := model.Region.ValueString() // not needed for global APIs
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "region", region)
// prepare the payload struct for the create bar request
payload, err := toCreatePayload(&model)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credential", fmt.Sprintf("Creating API payload: %v", err))
return
}
// Create new bar
barResp, err := r.client.CreateBar(ctx, projectId, region).CreateBarPayload(*payload).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating bar", fmt.Sprintf("Calling API: %v", err))
return
}
ctx = core.LogResponse(ctx)
// only in case the create bar API call is asynchronous (Make sure to include *ALL* fields which are part of the
// internal terraform resource id! And please include the comment below in your code):
// Write id attributes to state before polling via the wait handler - just in case anything goes wrong during the wait handler
ctx = utils.SetAndLogStateFields(ctx, &resp.Diagnostics, &resp.State, map[string]interface{}{
"project_id": projectId,
"region": region,
"bar_id": resp.BarId,
})
if resp.Diagnostics.HasError() {
return
}
// only in case the create bar API request is synchronous: just log the bar id field instead
ctx = tflog.SetField(ctx, "bar_id", resp.BarId)
// only in case the create bar API call is asynchronous: use a wait handler to wait for the create process to complete
barResp, err := wait.CreateBarWaitHandler(ctx, r.client, projectId, region, resp.BarId).WaitWithContext(ctx)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating bar", fmt.Sprintf("Bar creation waiting: %v", err))
return
}
// No matter if the API request is synchronous or asynchronous: Map response body to schema
err = mapFields(resp, &model)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating bar", fmt.Sprintf("Processing API payload: %v", err))
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, model)...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "Foo bar created")
}
// Read refreshes the Terraform state with the latest data.
func (r *barResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
var model Model
resp.Diagnostics.Append(req.State.Get(ctx, &model)...)
if resp.Diagnostics.HasError() {
return
}
readTimeout, diags := model.Timeouts.Read(ctx, core.DefaultOperationTimeout)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
ctx, cancel := context.WithTimeout(ctx, readTimeout)
defer cancel()
ctx = core.InitProviderContext(ctx)
projectId := model.ProjectId.ValueString()
region := r.providerData.GetRegionWithOverride(model.Region)
barId := model.BarId.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "region", region)
ctx = tflog.SetField(ctx, "bar_id", barId)
barResp, err := r.client.GetBar(ctx, projectId, region, barId).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading bar", fmt.Sprintf("Calling API: %v", err))
return
}
ctx = core.LogResponse(ctx)
// Map response body to schema
err = mapFields(barResp, &model)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading bar", fmt.Sprintf("Processing API payload: %v", err))
return
}
// Set refreshed state
resp.Diagnostics.Append(resp.State.Set(ctx, model)...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "Foo bar read")
}
// Update updates the resource and sets the updated Terraform state on success.
func (r *barResource) Update(ctx context.Context, _ resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
// Similar to Create method, calls r.client.UpdateBar (and wait.UpdateBarWaitHandler if needed) instead
}
// Delete deletes the resource and removes the Terraform state on success.
func (r *barResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
var model Model
diags := req.State.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
waiterTimeout := wait.DeleteBarWaitHandler(ctx, r.client, projectId, region, barId).GetTimeout()
deleteTimeout, diags := model.Timeouts.Delete(ctx, waiterTimeout+core.DefaultTimeoutMargin)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
ctx, cancel := context.WithTimeout(ctx, deleteTimeout)
defer cancel()
ctx = core.InitProviderContext(ctx)
projectId := model.ProjectId.ValueString()
region := model.Region.ValueString()
barId := model.BarId.ValueString()
ctx = tflog.SetField(ctx, "project_id", projectId)
ctx = tflog.SetField(ctx, "region", region)
ctx = tflog.SetField(ctx, "bar_id", barId)
// Delete existing bar
_, err := r.client.DeleteBar(ctx, projectId, region, barId).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting bar", fmt.Sprintf("Calling API: %v", err))
}
ctx = core.LogResponse(ctx)
// only in case the bar delete API endpoint is asynchronous: use a wait handler to wait for the delete operation to complete
_, err = wait.DeleteBarWaitHandler(ctx, r.client, projectId, region, barId).WaitWithContext(ctx)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting bar", fmt.Sprintf("Bar deletion waiting: %v", err))
return
}
tflog.Info(ctx, "Foo bar deleted")
}
// ImportState imports a resource into the Terraform state on success.
// The expected format of the bar resource import identifier is: project_id,bar_id
func (r *barResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
idParts := strings.Split(req.ID, core.Separator)
if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" {
core.LogAndAddError(ctx, &resp.Diagnostics,
"Error importing bar",
fmt.Sprintf("Expected import identifier with format [project_id],[region],[bar_id], got %q", req.ID),
)
return
}
ctx = utils.SetAndLogStateFields(ctx, &resp.Diagnostics, &resp.State, map[string]any{
"project_id": idParts[0],
"region": idParts[1],
"bar_id": idParts[2],
})
tflog.Info(ctx, "Foo bar state imported")
}
// Maps bar fields to the provider's internal model
func mapFields(barResp *foo.GetBarResponse, model *Model) error {
if barResp == nil {
return fmt.Errorf("response input is nil")
}
if barResp.Bar == nil {
return fmt.Errorf("response bar is nil")
}
if model == nil {
return fmt.Errorf("model input is nil")
}
bar := barResp.Bar
model.BarId = types.StringPointerValue(bar.BarId)
model.Id = utils.BuildInternalTerraformId(
model.ProjectId.ValueString(),
model.Region.ValueString(),
model.BarId.ValueString(),
)
model.MyRequiredField = types.StringPointerValue(bar.MyRequiredField)
model.MyOptionalField = types.StringPointerValue(bar.MyOptionalField)
model.MyReadOnlyField = types.StringPointerValue(bar.MyOtherField)
return nil
}
// Build CreateBarPayload from provider's model
func toCreatePayload(model *Model) (*foo.CreateBarPayload, error) {
if model == nil {
return nil, fmt.Errorf("nil model")
}
myRequiredFieldValue := conversion.StringValueToPointer(model.MyRequiredField)
myOptionalFieldValue := conversion.StringValueToPointer(model.MyOptionalField)
return &foo.CreateBarPayload{
MyRequiredField: myRequiredFieldValue,
MyOptionalField: myOptionalFieldValue,
}, nil
}