/
vpc_resource.go
376 lines (345 loc) · 12.2 KB
/
vpc_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
package provider
import (
"context"
"fmt"
"strconv"
"time"
"github.com/hashicorp/terraform-plugin-framework-timeouts/resource/timeouts"
"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/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/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry"
tsClient "github.com/timescale/terraform-provider-timescale/internal/client"
)
// Ensure the implementation satisfies the expected interfaces.
var (
_ resource.Resource = &vpcResource{}
_ resource.ResourceWithConfigure = &vpcResource{}
ErrVPCRead = "Error reading VPC"
ErrVPCCreate = "Error creating VPC"
ErrVPCUpdate = "Error updating VPC"
)
// NewVpcsResource is a helper function to simplify the provider implementation.
func NewVpcsResource() resource.Resource {
return &vpcResource{}
}
// vpcResource is the data source implementation.
type vpcResource struct {
client *tsClient.Client
}
type vpcResourceModel struct {
ID types.Int64 `tfsdk:"id"`
ProvisionedID types.String `tfsdk:"provisioned_id"`
ProjectID types.String `tfsdk:"project_id"`
CIDR types.String `tfsdk:"cidr"`
Name types.String `tfsdk:"name"`
RegionCode types.String `tfsdk:"region_code"`
Status types.String `tfsdk:"status"`
ErrorMessage types.String `tfsdk:"error_message"`
Created types.String `tfsdk:"created"`
Updated types.String `tfsdk:"updated"`
Timeouts timeouts.Value `tfsdk:"timeouts"`
}
// Metadata returns the data source type name.
func (r *vpcResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_vpcs"
}
// Read refreshes the Terraform state with the latest data.
func (r *vpcResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state vpcResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
var vpc *tsClient.VPC
var err error
if !state.Name.IsNull() {
tflog.Info(ctx, "Getting VPC by name: "+state.Name.ValueString())
vpc, err = r.client.GetVPCByName(ctx, state.Name.ValueString())
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to Read vpc, got error: %s, %s", state.Name.ValueString(), err))
return
}
} else {
resp.Diagnostics.AddError(ErrVPCRead, "error must provide Name")
return
}
vpcID, err := strconv.ParseInt(vpc.ID, 10, 64)
if err != nil {
resp.Diagnostics.AddError("Parse Error", "could not parse vpcID")
}
state.ID = types.Int64Value(vpcID)
state.Created = types.StringValue(vpc.Created)
state.ProjectID = types.StringValue(vpc.ProjectID)
state.ProvisionedID = types.StringValue(vpc.ProvisionedID)
state.CIDR = types.StringValue(vpc.CIDR)
state.RegionCode = types.StringValue(vpc.RegionCode)
model := vpcToResource(vpc, state)
// Save updated plan into Terraform state
resp.Diagnostics.Append(resp.State.Set(ctx, model)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, fmt.Sprintf("error updating terraform state %v", resp.Diagnostics.Errors()))
return
}
}
func vpcToResource(s *tsClient.VPC, state vpcResourceModel) vpcResourceModel {
model := vpcResourceModel{
ID: state.ID,
ProjectID: state.ProjectID,
Created: state.Created,
RegionCode: state.RegionCode,
CIDR: state.CIDR,
Name: types.StringValue(s.Name),
ProvisionedID: types.StringValue(s.ProvisionedID),
Status: types.StringValue(s.Status),
ErrorMessage: types.StringValue(s.ErrorMessage),
Updated: types.StringValue(s.Updated),
Timeouts: state.Timeouts,
}
return model
}
// Create creates a VPC shell
func (r *vpcResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
tflog.Trace(ctx, "VpcResource.Create")
var plan vpcResourceModel
// Read Terraform plan data into the model
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if plan.RegionCode.IsNull() {
resp.Diagnostics.AddError(ErrVPCCreate, "Region code is required")
return
}
if plan.CIDR.IsNull() {
resp.Diagnostics.AddError(ErrVPCCreate, "CIDR is required")
return
}
vpc, err := r.client.CreateVPC(ctx, plan.Name.ValueString(), plan.CIDR.ValueString(), plan.RegionCode.ValueString())
if err != nil {
resp.Diagnostics.AddError(
fmt.Sprintf("Unable to Create Vpc %v", plan),
err.Error(),
)
return
}
vpcID, err := strconv.ParseInt(vpc.ID, 10, 64)
if err != nil {
resp.Diagnostics.AddError("Parse Error", "could not parse vpcID")
return
}
vpc, err = r.waitForVPCReadiness(ctx, vpcID, plan.Timeouts)
if err != nil {
resp.Diagnostics.AddError("Create VPC Error", "error waiting for VPC readiness: "+err.Error())
return
}
plan.ID = types.Int64Value(vpcID)
plan.Created = types.StringValue(vpc.Created)
plan.ProjectID = types.StringValue(vpc.ProjectID)
plan.ProvisionedID = types.StringValue(vpc.ProvisionedID)
plan.CIDR = types.StringValue(vpc.CIDR)
plan.RegionCode = types.StringValue(vpc.RegionCode)
model := vpcToResource(vpc, plan)
// Set state
resp.Diagnostics.Append(resp.State.Set(ctx, model)...)
if resp.Diagnostics.HasError() {
return
}
}
func (r *vpcResource) waitForVPCReadiness(ctx context.Context, id int64, timeouts timeouts.Value) (*tsClient.VPC, error) {
tflog.Trace(ctx, "VPCResource.waitForServiceReadiness")
defaultTimeout := 5 * time.Minute
timeout, diags := timeouts.Create(ctx, defaultTimeout)
if diags != nil && diags.HasError() {
tflog.Error(ctx, fmt.Sprintf("found errs %v", diags.Errors()))
return nil, fmt.Errorf("unable to get timeout from config %v", diags.Errors())
}
conf := retry.StateChangeConf{
Pending: []string{"CREATING"},
Target: []string{"CREATED"},
Delay: 5 * time.Second,
Timeout: timeout,
PollInterval: 5 * time.Second,
ContinuousTargetOccurence: 1,
Refresh: func() (result interface{}, state string, err error) {
vpc, err := r.client.GetVPCByID(ctx, id)
if err != nil {
return nil, "", err
}
return vpc, vpc.Status, nil
},
}
res, err := conf.WaitForStateContext(ctx)
if err != nil {
return nil, err
}
vpc, ok := res.(*tsClient.VPC)
if !ok {
return nil, fmt.Errorf("unexpected type found, expected VPC but got %T", res)
}
return vpc, nil
}
// Delete deletes a VPC shell
func (r *vpcResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
tflog.Trace(ctx, "VpcsResource.Delete")
var state vpcResourceModel
// // TODO: find a way to have this before automated test deletion
// time.Sleep(10 * time.Second)
// Read Terraform plan data into the model
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, fmt.Sprintf("Deleting Vpc: %v", state.ID.ValueInt64()))
err := r.client.DeleteVPC(ctx, state.ID.ValueInt64())
if err != nil {
resp.Diagnostics.AddError(
"Error Deleting Timescale Vpc",
"Could not delete vpc, unexpected error: "+err.Error(),
)
return
}
}
// Update updates a VPC shell
func (r *vpcResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
tflog.Trace(ctx, "VpcsResource.Update")
var plan, state vpcResourceModel
// Read Terraform plan data into the model
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
if plan.RegionCode != state.RegionCode {
resp.Diagnostics.AddError(ErrVPCUpdate, "Do not support region code change")
return
}
if plan.CIDR != state.CIDR {
resp.Diagnostics.AddError(ErrVPCUpdate, "Do not support cidr change")
return
}
if !plan.Name.Equal(state.Name) {
if err := r.client.RenameVPC(ctx, state.ID.ValueInt64(), plan.Name.ValueString()); err != nil {
resp.Diagnostics.AddError(ErrVPCUpdate, err.Error())
return
}
state.Name = plan.Name
}
resp.Diagnostics.Append(resp.State.Set(ctx, state)...)
}
func (r *vpcResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
resource.ImportStatePassthroughID(ctx, path.Root("name"), req, resp)
}
// Configure adds the provider configured client to the data source.
func (r *vpcResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
tflog.Trace(ctx, "vpcsResource.Configure")
if req.ProviderData == nil {
return
}
client, ok := req.ProviderData.(*tsClient.Client)
if !ok {
resp.Diagnostics.AddError(
"Unexpected Resource Configure Type",
fmt.Sprintf("Expected *tsClient.Client, got: %T. Please report this issue to the provider developers.", req.ProviderData),
)
return
}
r.client = client
}
// Schema defines the schema for the data source.
func (r *vpcResource) Schema(ctx context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: `Schema for a VPC. Import can be done using your VPCs name`,
Attributes: map[string]schema.Attribute{
"id": schema.Int64Attribute{
Computed: true,
PlanModifiers: []planmodifier.Int64{
int64planmodifier.UseStateForUnknown(),
},
},
"provisioned_id": schema.StringAttribute{
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"project_id": schema.StringAttribute{
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"cidr": schema.StringAttribute{
Description: `The IPv4 CIDR block`,
MarkdownDescription: "The IPv4 CIDR block",
Required: true,
},
"name": schema.StringAttribute{
MarkdownDescription: "VPC Name is the configurable name assigned to this vpc. If none is provided, a default will be generated by the provider.",
Description: "Vpc name",
Optional: true,
// If the name attribute is absent, the provider will generate a default.
Computed: true,
},
"region_code": schema.StringAttribute{
Description: `The region for this VPC`,
MarkdownDescription: "The region for this VPC.",
Required: true,
},
"status": schema.StringAttribute{
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"error_message": schema.StringAttribute{
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"created": schema.StringAttribute{
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"updated": schema.StringAttribute{
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"timeouts": timeoutSchema(ctx, timeouts.Opts{
Create: true,
}),
},
}
}
// adding timeouts can break earlier versions of the provider since the field is not set.
// reference: https://github.com/hashicorp/terraform-plugin-framework-timeouts/issues/49#issuecomment-1511027690
func timeoutSchema(ctx context.Context, opts timeouts.Opts) schema.SingleNestedAttribute {
timeout := timeouts.Attributes(ctx, opts).(schema.SingleNestedAttribute)
at := map[string]attr.Type{}
if opts.Create {
at["create"] = types.StringType
}
if opts.Read {
at["read"] = types.StringType
}
if opts.Update {
at["update"] = types.StringType
}
if opts.Delete {
at["delete"] = types.StringType
}
timeout.Computed = true
timeout.Default = objectdefault.StaticValue(
types.ObjectNull(at),
)
return timeout
}