-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathresource.go
More file actions
449 lines (386 loc) · 14.6 KB
/
resource.go
File metadata and controls
449 lines (386 loc) · 14.6 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
package environment
import (
"context"
"fmt"
"strconv"
"strings"
"github.com/dbt-labs/terraform-provider-dbtcloud/pkg/dbt_cloud"
"github.com/dbt-labs/terraform-provider-dbtcloud/pkg/helper"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/types"
)
var (
_ resource.Resource = &environmentResource{}
_ resource.ResourceWithConfigure = &environmentResource{}
_ resource.ResourceWithImportState = &environmentResource{}
)
// connectionIDFromAPI converts the API connection_id pointer to a types.Int64 value,
// treating nil and 0 as "not set" (null) so Terraform doesn't see a spurious diff.
func connectionIDFromAPI(id *int) types.Int64 {
if id != nil && *id != 0 {
return types.Int64Value(int64(*id))
}
return types.Int64Null()
}
func EnvironmentResource() resource.Resource {
return &environmentResource{}
}
type environmentResource struct {
client *dbt_cloud.Client
}
func (r *environmentResource) Metadata(
_ context.Context,
req resource.MetadataRequest,
resp *resource.MetadataResponse,
) {
resp.TypeName = req.ProviderTypeName + "_environment"
}
func (r *environmentResource) Read(
ctx context.Context,
req resource.ReadRequest,
resp *resource.ReadResponse,
) {
var state EnvironmentResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
projectID, environmentID, err := helper.SplitIDToInts(fmt.Sprintf("%d:%d", state.ProjectID.ValueInt64(), state.EnvironmentID.ValueInt64()), "dbtcloud_environment")
if err != nil {
resp.Diagnostics.AddError("Error parsing ID", err.Error())
return
}
environment, err := r.client.GetEnvironment(projectID, environmentID)
if err != nil {
resp.Diagnostics.AddError("Error getting the environment", err.Error())
return
}
state.EnvironmentID = types.Int64Value(int64(*environment.Environment_Id))
state.ProjectID = types.Int64Value(int64(environment.Project_Id))
state.ID = types.StringValue(fmt.Sprintf("%d:%d", state.ProjectID.ValueInt64(), state.EnvironmentID.ValueInt64()))
state.Name = types.StringValue(environment.Name)
state.IsActive = types.BoolValue(environment.State == dbt_cloud.STATE_ACTIVE)
// Handle versionless to latest conversion
if state.DbtVersion.ValueString() == "versionless" && environment.Dbt_Version == "latest" {
state.DbtVersion = types.StringValue("versionless")
} else {
state.DbtVersion = types.StringValue(environment.Dbt_Version)
}
state.Type = types.StringValue(environment.Type)
state.UseCustomBranch = types.BoolValue(environment.Use_Custom_Branch)
if environment.Custom_Branch != nil {
state.CustomBranch = types.StringPointerValue(environment.Custom_Branch)
}
state.DeploymentType = types.StringPointerValue(environment.DeploymentType)
if environment.ExtendedAttributesID != nil {
state.ExtendedAttributesID = types.Int64Value(int64(*environment.ExtendedAttributesID))
} else {
state.ExtendedAttributesID = types.Int64Null()
}
state.EnableModelQueryHistory = types.BoolValue(environment.EnableModelQueryHistory)
state.ConnectionID = connectionIDFromAPI(environment.ConnectionID)
if environment.Credential_Id != nil {
state.CredentialID = types.Int64Value(int64(*environment.Credential_Id))
} else {
state.CredentialID = types.Int64Null()
}
// Only update primary_profile_id if it was already in state (user-configured).
// The API always returns a profile (auto-creating one if needed), but the
// auto-created ID is an implementation detail that shouldn't leak into state.
if !state.PrimaryProfileID.IsNull() {
if environment.PrimaryProfileID != nil {
state.PrimaryProfileID = types.Int64Value(int64(*environment.PrimaryProfileID))
} else {
state.PrimaryProfileID = types.Int64Null()
}
}
resp.Diagnostics.Append(resp.State.Set(ctx, state)...)
}
func (r *environmentResource) Create(
ctx context.Context,
req resource.CreateRequest,
resp *resource.CreateResponse,
) {
var plan EnvironmentResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
customBranchValue := plan.CustomBranch.ValueString()
if plan.CustomBranch.IsUnknown() {
customBranchValue = types.StringNull().ValueString()
}
deploymentType := plan.DeploymentType.ValueString()
if plan.DeploymentType.IsUnknown() {
deploymentType = types.StringNull().ValueString()
}
environment, err := r.client.CreateEnvironment(
plan.IsActive.ValueBool(),
int(plan.ProjectID.ValueInt64()),
plan.Name.ValueString(),
plan.DbtVersion.ValueString(),
plan.Type.ValueString(),
plan.UseCustomBranch.ValueBool(),
customBranchValue,
int(plan.CredentialID.ValueInt64()),
deploymentType,
int(plan.ExtendedAttributesID.ValueInt64()),
int(plan.ConnectionID.ValueInt64()),
plan.EnableModelQueryHistory.ValueBool(),
int(plan.PrimaryProfileID.ValueInt64()),
)
if err != nil {
resp.Diagnostics.AddError("Error creating the environment", err.Error())
return
}
// Set the IDs first so we can use them to read the environment
plan.EnvironmentID = types.Int64Value(int64(*environment.Environment_Id))
plan.ProjectID = types.Int64Value(int64(environment.Project_Id))
plan.ID = types.StringValue(fmt.Sprintf("%d:%d", plan.ProjectID.ValueInt64(), plan.EnvironmentID.ValueInt64()))
plan.IsActive = types.BoolValue(environment.State == dbt_cloud.STATE_ACTIVE)
// Handle versionless to latest conversion
if plan.DbtVersion.ValueString() == "versionless" && environment.Dbt_Version == "latest" {
plan.DbtVersion = types.StringValue("versionless")
} else {
plan.DbtVersion = types.StringValue(environment.Dbt_Version)
}
if plan.Type.IsUnknown() {
plan.Type = types.StringValue(environment.Type)
}
if plan.UseCustomBranch.IsUnknown() {
plan.UseCustomBranch = types.BoolValue(environment.Use_Custom_Branch)
}
if plan.CustomBranch.IsUnknown() {
plan.CustomBranch = types.StringPointerValue(environment.Custom_Branch)
}
if plan.DeploymentType.IsUnknown() {
plan.DeploymentType = types.StringPointerValue(environment.DeploymentType)
}
if environment.ExtendedAttributesID != nil {
plan.ExtendedAttributesID = types.Int64Value(int64(*environment.ExtendedAttributesID))
} else {
plan.ExtendedAttributesID = types.Int64Null()
}
plan.EnableModelQueryHistory = types.BoolValue(environment.EnableModelQueryHistory)
plan.ConnectionID = connectionIDFromAPI(environment.ConnectionID)
plan.CredentialID = types.Int64PointerValue(
helper.IntPointerToInt64Pointer(environment.Credential_Id),
)
// Only store primary_profile_id if the user configured it (known value in plan).
// When not configured, plan is null/unknown and we don't surface the auto-created ID.
if !plan.PrimaryProfileID.IsNull() && !plan.PrimaryProfileID.IsUnknown() {
if environment.PrimaryProfileID != nil {
plan.PrimaryProfileID = types.Int64Value(int64(*environment.PrimaryProfileID))
} else {
plan.PrimaryProfileID = types.Int64Null()
}
} else {
plan.PrimaryProfileID = types.Int64Null()
}
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
}
func (r *environmentResource) Update(
ctx context.Context,
req resource.UpdateRequest,
resp *resource.UpdateResponse,
) {
var plan, state EnvironmentResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
projectID, environmentID, err := helper.SplitIDToInts(fmt.Sprintf("%d:%d", state.ProjectID.ValueInt64(), state.EnvironmentID.ValueInt64()), "dbtcloud_environment")
if err != nil {
resp.Diagnostics.AddError("Error parsing ID", err.Error())
return
}
envToUpdate, err := r.client.GetEnvironment(projectID, environmentID)
if err != nil {
resp.Diagnostics.AddError("Error getting the environment", err.Error())
return
}
if plan.Name.ValueString() != state.Name.ValueString() {
envToUpdate.Name = plan.Name.ValueString()
}
if !plan.CredentialID.Equal(state.CredentialID) {
if plan.CredentialID.IsNull() || plan.CredentialID.IsUnknown() {
// Only explicitly clear if the state had a value and plan is null (removal)
if !state.CredentialID.IsNull() && plan.CredentialID.IsNull() {
envToUpdate.Credential_Id = nil
}
} else {
envToUpdate.Credential_Id = helper.Int64ToIntPointer(plan.CredentialID.ValueInt64())
}
}
// Handle versionless to latest conversion
if plan.DbtVersion.ValueString() == "versionless" && envToUpdate.Dbt_Version == "latest" {
plan.DbtVersion = types.StringValue("versionless")
} else if plan.DbtVersion.ValueString() != state.DbtVersion.ValueString() {
envToUpdate.Dbt_Version = plan.DbtVersion.ValueString()
}
if plan.Type.ValueString() != state.Type.ValueString() {
envToUpdate.Type = plan.Type.ValueString()
}
if plan.UseCustomBranch.ValueBool() != state.UseCustomBranch.ValueBool() {
envToUpdate.Use_Custom_Branch = plan.UseCustomBranch.ValueBool()
}
if plan.CustomBranch.ValueString() != state.CustomBranch.ValueString() {
customBranch := plan.CustomBranch.ValueString()
envToUpdate.Custom_Branch = &customBranch
}
if plan.DeploymentType.ValueString() != state.DeploymentType.ValueString() {
deploymentType := plan.DeploymentType.ValueString()
if deploymentType == "" {
// Nil omits deployment_type in JSON; a pointer to "" sends "" and the API rejects it (issue #623).
envToUpdate.DeploymentType = nil
} else {
envToUpdate.DeploymentType = &deploymentType
}
}
// Handle extended_attributes_id - need to properly handle null and unknown values
if !plan.ExtendedAttributesID.Equal(state.ExtendedAttributesID) {
if plan.ExtendedAttributesID.IsNull() || plan.ExtendedAttributesID.IsUnknown() {
// If null or unknown, don't change the value (preserve existing or let API handle)
// We only explicitly set nil if the state had a value and plan is null (removal)
if !state.ExtendedAttributesID.IsNull() && plan.ExtendedAttributesID.IsNull() {
envToUpdate.ExtendedAttributesID = nil
}
} else {
extendedAttrID := int(plan.ExtendedAttributesID.ValueInt64())
envToUpdate.ExtendedAttributesID = &extendedAttrID
}
}
if !plan.ConnectionID.Equal(state.ConnectionID) {
if plan.ConnectionID.IsNull() || plan.ConnectionID.IsUnknown() {
// Don't change - let API/profile determine value
} else {
connID := int(plan.ConnectionID.ValueInt64())
envToUpdate.ConnectionID = &connID
}
}
if plan.EnableModelQueryHistory.ValueBool() != state.EnableModelQueryHistory.ValueBool() {
envToUpdate.EnableModelQueryHistory = plan.EnableModelQueryHistory.ValueBool()
}
// Handle primary_profile_id - need to properly handle null and unknown values
if !plan.PrimaryProfileID.Equal(state.PrimaryProfileID) {
if plan.PrimaryProfileID.IsNull() || plan.PrimaryProfileID.IsUnknown() {
if !state.PrimaryProfileID.IsNull() && plan.PrimaryProfileID.IsNull() {
envToUpdate.PrimaryProfileID = nil
}
} else {
profileID := int(plan.PrimaryProfileID.ValueInt64())
envToUpdate.PrimaryProfileID = &profileID
}
}
updatedEnv, err := r.client.UpdateEnvironment(
projectID,
environmentID,
*envToUpdate,
)
if err != nil {
resp.Diagnostics.AddError("Error updating environment", err.Error())
return
}
plan.EnvironmentID = types.Int64Value(int64(*updatedEnv.Environment_Id))
plan.ConnectionID = connectionIDFromAPI(updatedEnv.ConnectionID)
if updatedEnv.Credential_Id != nil {
plan.CredentialID = types.Int64Value(int64(*updatedEnv.Credential_Id))
} else {
plan.CredentialID = types.Int64Null()
}
if updatedEnv.ExtendedAttributesID != nil {
plan.ExtendedAttributesID = types.Int64Value(int64(*updatedEnv.ExtendedAttributesID))
} else {
plan.ExtendedAttributesID = types.Int64Null()
}
// Write back primary_profile_id based on plan intent (not prior state).
// The UseStateWhenConfigSet plan modifier ensures the plan is null when
// the user removes the attribute, and non-null when they set it.
if !plan.PrimaryProfileID.IsNull() && !plan.PrimaryProfileID.IsUnknown() {
if updatedEnv.PrimaryProfileID != nil {
plan.PrimaryProfileID = types.Int64Value(int64(*updatedEnv.PrimaryProfileID))
} else {
plan.PrimaryProfileID = types.Int64Null()
}
} else {
plan.PrimaryProfileID = types.Int64Null()
}
plan.ID = types.StringValue(fmt.Sprintf("%d:%d", plan.ProjectID.ValueInt64(), plan.EnvironmentID.ValueInt64()))
resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
}
func (r *environmentResource) Delete(
ctx context.Context,
req resource.DeleteRequest,
resp *resource.DeleteResponse,
) {
var state EnvironmentResourceModel
diags := req.State.Get(ctx, &state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
projectID, environmentID, err := helper.SplitIDToInts(fmt.Sprintf("%d:%d", state.ProjectID.ValueInt64(), state.EnvironmentID.ValueInt64()), "dbtcloud_environment")
if err != nil {
resp.Diagnostics.AddError("Error parsing ID", err.Error())
return
}
_, err = r.client.DeleteEnvironment(
projectID,
environmentID,
)
if err != nil {
resp.Diagnostics.AddError("Error deleting environment", err.Error())
return
}
}
func splitEnvironmentID(id string) (int, int, error) {
parts := strings.Split(id, ":")
if len(parts) != 2 {
return 0, 0, fmt.Errorf("invalid environment ID")
}
part1, err := strconv.Atoi(parts[0])
if err != nil {
return 0, 0, fmt.Errorf("invalid project ID")
}
part2, err := strconv.Atoi(parts[1])
if err != nil {
return 0, 0, fmt.Errorf("invalid environment ID")
}
return part1, part2, nil
}
func (r *environmentResource) ImportState(
ctx context.Context,
req resource.ImportStateRequest,
resp *resource.ImportStateResponse,
) {
// The import ID is in the format "project_id:environment_id"
projectID, environmentID, err := splitEnvironmentID(req.ID)
if err != nil {
resp.Diagnostics.AddError("Error splitting environment ID", err.Error())
return
}
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), projectID)...)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("environment_id"), environmentID)...)
if resp.Diagnostics.HasError() {
return
}
// Set the id to match the import ID
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), types.StringValue(req.ID))...)
if resp.Diagnostics.HasError() {
return
}
// Set connection_id to null so it is refreshed from the API on the next plan/apply
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("connection_id"), types.Int64Null())...)
}
func (r *environmentResource) Configure(
ctx context.Context,
req resource.ConfigureRequest,
resp *resource.ConfigureResponse,
) {
if req.ProviderData == nil {
return
}
r.client = req.ProviderData.(*dbt_cloud.Client)
}