Skip to content

Commit f0bde45

Browse files
authored
fix(observability): changing a plan after creation results in an error (#1269)
STACKITTPR-504 Signed-off-by: Alexander Dahmen <alexander.dahmen@inovex.de>
1 parent 1305e67 commit f0bde45

File tree

7 files changed

+275
-68
lines changed

7 files changed

+275
-68
lines changed

stackit/internal/services/observability/instance/resource.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ import (
88
"strings"
99

1010
"github.com/google/go-cmp/cmp"
11-
"github.com/hashicorp/terraform-plugin-framework/resource/schema/int64planmodifier"
1211
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/utils"
12+
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/utils/planmodifiers/int64planmodifier"
1313

1414
observabilityUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/observability/utils"
1515

@@ -543,23 +543,23 @@ func (r *instanceResource) Schema(_ context.Context, _ resource.SchemaRequest, r
543543
Optional: true,
544544
Computed: true,
545545
PlanModifiers: []planmodifier.Int64{
546-
int64planmodifier.UseStateForUnknown(),
546+
int64planmodifier.UseStateForUnknownIf(utils.Int64Changed, "metrics_retention_days", "sets `UseStateForUnknown` only if `metrics_retention_days` has not changed"),
547547
},
548548
},
549549
"metrics_retention_days_5m_downsampling": schema.Int64Attribute{
550550
Description: "Specifies for how many days the 5m downsampled metrics are kept. must be less than the value of the general retention. Default is set to `90`.",
551551
Optional: true,
552552
Computed: true,
553553
PlanModifiers: []planmodifier.Int64{
554-
int64planmodifier.UseStateForUnknown(),
554+
int64planmodifier.UseStateForUnknownIf(utils.Int64Changed, "metrics_retention_days_5m_downsampling", "sets `UseStateForUnknown` only if `metrics_retention_days_5m_downsampling` has not changed"),
555555
},
556556
},
557557
"metrics_retention_days_1h_downsampling": schema.Int64Attribute{
558558
Description: "Specifies for how many days the 1h downsampled metrics are kept. must be less than the value of the 5m downsampling retention. Default is set to `90`.",
559559
Optional: true,
560560
Computed: true,
561561
PlanModifiers: []planmodifier.Int64{
562-
int64planmodifier.UseStateForUnknown(),
562+
int64planmodifier.UseStateForUnknownIf(utils.Int64Changed, "metrics_retention_days_1h_downsampling", "sets `UseStateForUnknown` only if `metrics_retention_days_1h_downsampling` has not changed"),
563563
},
564564
},
565565
"metrics_url": schema.StringAttribute{

stackit/internal/services/ske/cluster/resource.go

Lines changed: 3 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111

1212
serviceenablementUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/serviceenablement/utils"
1313
skeUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/ske/utils"
14+
stringplanmodifierUtils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/utils/planmodifiers/stringplanmodifier"
1415

1516
"github.com/hashicorp/terraform-plugin-framework-validators/listvalidator"
1617
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
@@ -368,7 +369,7 @@ func (r *clusterResource) Schema(_ context.Context, _ resource.SchemaRequest, re
368369
Description: "Full Kubernetes version used. For example, if 1.22 was set in `kubernetes_version_min`, this value may result to 1.22.15. " + SKEUpdateDoc,
369370
Computed: true,
370371
PlanModifiers: []planmodifier.String{
371-
utils.UseStateForUnknownIf(hasKubernetesMinChanged, "sets `UseStateForUnknown` only if `kubernetes_min_version` has not changed"),
372+
stringplanmodifierUtils.UseStateForUnknownIf(utils.StringChanged, "kubernetes_version_min", "sets `UseStateForUnknown` only if `kubernetes_min_version` has not changed"),
372373
},
373374
},
374375
"egress_address_ranges": schema.ListAttribute{
@@ -451,7 +452,7 @@ func (r *clusterResource) Schema(_ context.Context, _ resource.SchemaRequest, re
451452
Description: "Full OS image version used. For example, if 3815.2 was set in `os_version_min`, this value may result to 3815.2.2. " + SKEUpdateDoc,
452453
Computed: true,
453454
PlanModifiers: []planmodifier.String{
454-
utils.UseStateForUnknownIf(hasOsVersionMinChanged, "sets `UseStateForUnknown` only if `os_version_min` has not changed"),
455+
stringplanmodifierUtils.UseStateForUnknownIf(utils.StringChanged, "os_version_min", "sets `UseStateForUnknown` only if `os_version_min` has not changed"),
455456
},
456457
},
457458
"volume_type": schema.StringAttribute{
@@ -2108,52 +2109,6 @@ func getLatestSupportedKubernetesVersion(versions []ske.KubernetesVersion) (*str
21082109
return latestVersion, nil
21092110
}
21102111

2111-
func hasKubernetesMinChanged(ctx context.Context, request planmodifier.StringRequest, response *utils.UseStateForUnknownFuncResponse) { // nolint:gocritic // function signature required by Terraform
2112-
dependencyPath := path.Root("kubernetes_version_min")
2113-
2114-
var minVersionPlan types.String
2115-
diags := request.Plan.GetAttribute(ctx, dependencyPath, &minVersionPlan)
2116-
response.Diagnostics.Append(diags...)
2117-
if response.Diagnostics.HasError() {
2118-
return
2119-
}
2120-
2121-
var minVersionState types.String
2122-
diags = request.State.GetAttribute(ctx, dependencyPath, &minVersionState)
2123-
response.Diagnostics.Append(diags...)
2124-
if response.Diagnostics.HasError() {
2125-
return
2126-
}
2127-
2128-
if minVersionState == minVersionPlan {
2129-
response.UseStateForUnknown = true
2130-
return
2131-
}
2132-
}
2133-
2134-
func hasOsVersionMinChanged(ctx context.Context, request planmodifier.StringRequest, response *utils.UseStateForUnknownFuncResponse) { // nolint:gocritic // function signature required by Terraform
2135-
dependencyPath := request.Path.ParentPath().AtName("os_version_min")
2136-
2137-
var minVersionPlan types.String
2138-
diags := request.Plan.GetAttribute(ctx, dependencyPath, &minVersionPlan)
2139-
response.Diagnostics.Append(diags...)
2140-
if response.Diagnostics.HasError() {
2141-
return
2142-
}
2143-
2144-
var minVersionState types.String
2145-
diags = request.State.GetAttribute(ctx, dependencyPath, &minVersionState)
2146-
response.Diagnostics.Append(diags...)
2147-
if response.Diagnostics.HasError() {
2148-
return
2149-
}
2150-
2151-
if minVersionState == minVersionPlan {
2152-
response.UseStateForUnknown = true
2153-
return
2154-
}
2155-
}
2156-
21572112
func (r *clusterResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
21582113
var state Model
21592114
diags := req.State.Get(ctx, &state)

stackit/internal/utils/attributes.go

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,11 @@ import (
77

88
"github.com/hashicorp/terraform-plugin-framework/diag"
99
"github.com/hashicorp/terraform-plugin-framework/path"
10+
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
1011
"github.com/hashicorp/terraform-plugin-framework/types"
1112
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
13+
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/utils/planmodifiers/int64planmodifier"
14+
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/utils/planmodifiers/stringplanmodifier"
1215
)
1316

1417
type attributeGetter interface {
@@ -44,3 +47,51 @@ func GetTimeFromStringAttribute(ctx context.Context, attributePath path.Path, so
4447

4548
return diags
4649
}
50+
51+
// Int64Changed sets UseStateForUnkown to true if the attribute's planned value matches the current state
52+
func Int64Changed(ctx context.Context, attributeName string, request planmodifier.Int64Request, response *int64planmodifier.UseStateForUnknownFuncResponse) { // nolint:gocritic // function signature required by Terraform
53+
dependencyPath := request.Path.ParentPath().AtName(attributeName)
54+
55+
var attributePlan types.Int64
56+
diags := request.Plan.GetAttribute(ctx, dependencyPath, &attributePlan)
57+
response.Diagnostics.Append(diags...)
58+
if response.Diagnostics.HasError() {
59+
return
60+
}
61+
62+
var attributeState types.Int64
63+
diags = request.State.GetAttribute(ctx, dependencyPath, &attributeState)
64+
response.Diagnostics.Append(diags...)
65+
if response.Diagnostics.HasError() {
66+
return
67+
}
68+
69+
if attributeState == attributePlan {
70+
response.UseStateForUnknown = true
71+
return
72+
}
73+
}
74+
75+
// StringChanged sets UseStateForUnkown to true if the attribute's planned value matches the current state
76+
func StringChanged(ctx context.Context, attributeName string, request planmodifier.StringRequest, response *stringplanmodifier.UseStateForUnknownFuncResponse) { // nolint:gocritic // function signature required by Terraform
77+
dependencyPath := request.Path.ParentPath().AtName(attributeName)
78+
79+
var attributePlan types.String
80+
diags := request.Plan.GetAttribute(ctx, dependencyPath, &attributePlan)
81+
response.Diagnostics.Append(diags...)
82+
if response.Diagnostics.HasError() {
83+
return
84+
}
85+
86+
var attributeState types.String
87+
diags = request.State.GetAttribute(ctx, dependencyPath, &attributeState)
88+
response.Diagnostics.Append(diags...)
89+
if response.Diagnostics.HasError() {
90+
return
91+
}
92+
93+
if attributeState == attributePlan {
94+
response.UseStateForUnknown = true
95+
return
96+
}
97+
}
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
package int64planmodifier
2+
3+
import (
4+
"context"
5+
6+
"github.com/hashicorp/terraform-plugin-framework/diag"
7+
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
8+
)
9+
10+
type UseStateForUnknownFuncResponse struct {
11+
UseStateForUnknown bool
12+
Diagnostics diag.Diagnostics
13+
}
14+
15+
// UseStateForUnknownIfFunc is a conditional function used in UseStateForUnknownIf
16+
type UseStateForUnknownIfFunc func(context.Context, string, planmodifier.Int64Request, *UseStateForUnknownFuncResponse)
17+
18+
type useStateForUnknownIf struct {
19+
ifFunc UseStateForUnknownIfFunc
20+
attributeName string
21+
description string
22+
}
23+
24+
// UseStateForUnknownIf returns a plan modifier similar to UseStateForUnknown with a conditional
25+
func UseStateForUnknownIf(f UseStateForUnknownIfFunc, attributeName, description string) planmodifier.Int64 {
26+
return useStateForUnknownIf{
27+
ifFunc: f,
28+
attributeName: attributeName,
29+
description: description,
30+
}
31+
}
32+
33+
func (m useStateForUnknownIf) Description(context.Context) string {
34+
return m.description
35+
}
36+
37+
func (m useStateForUnknownIf) MarkdownDescription(ctx context.Context) string {
38+
return m.Description(ctx)
39+
}
40+
41+
func (m useStateForUnknownIf) PlanModifyInt64(ctx context.Context, req planmodifier.Int64Request, resp *planmodifier.Int64Response) { // nolint:gocritic // function signature required by Terraform
42+
// Do nothing if there is no state value.
43+
if req.StateValue.IsNull() {
44+
return
45+
}
46+
47+
// Do nothing if there is a known planned value.
48+
if !req.PlanValue.IsUnknown() {
49+
return
50+
}
51+
52+
// Do nothing if there is an unknown configuration value, otherwise interpolation gets messed up.
53+
if req.ConfigValue.IsUnknown() {
54+
return
55+
}
56+
57+
// The above checks are taken from the UseStateForUnknown plan modifier implementation
58+
// (https://github.com/hashicorp/terraform-plugin-framework/blob/44348af3923c82a93c64ae7dca906d9850ba956b/resource/schema/stringplanmodifier/use_state_for_unknown.go#L38)
59+
60+
funcResponse := &UseStateForUnknownFuncResponse{}
61+
m.ifFunc(ctx, m.attributeName, req, funcResponse)
62+
63+
resp.Diagnostics.Append(funcResponse.Diagnostics...)
64+
if resp.Diagnostics.HasError() {
65+
return
66+
}
67+
68+
if funcResponse.UseStateForUnknown {
69+
resp.PlanValue = req.StateValue
70+
}
71+
}
Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
package int64planmodifier
2+
3+
import (
4+
"context"
5+
"testing"
6+
7+
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
8+
"github.com/hashicorp/terraform-plugin-framework/types"
9+
)
10+
11+
func TestUseStateForUnknownIf_PlanModifyInt64(t *testing.T) {
12+
ctx := context.Background()
13+
14+
tests := []struct {
15+
name string
16+
stateValue types.Int64
17+
planValue types.Int64
18+
configValue types.Int64
19+
ifFunc UseStateForUnknownIfFunc
20+
expectedPlanValue types.Int64
21+
expectedError bool
22+
}{
23+
{
24+
name: "State is Null (Creation)",
25+
stateValue: types.Int64Null(),
26+
planValue: types.Int64Unknown(),
27+
configValue: types.Int64Value(10),
28+
ifFunc: func(_ context.Context, _ string, _ planmodifier.Int64Request, resp *UseStateForUnknownFuncResponse) {
29+
// This should not be reached because the state is null
30+
resp.UseStateForUnknown = true
31+
},
32+
expectedPlanValue: types.Int64Unknown(),
33+
},
34+
{
35+
name: "Plan is already known - (User updated the value)",
36+
stateValue: types.Int64Value(5),
37+
planValue: types.Int64Value(10),
38+
configValue: types.Int64Value(10),
39+
ifFunc: func(_ context.Context, _ string, _ planmodifier.Int64Request, resp *UseStateForUnknownFuncResponse) {
40+
// This should not be reached because the plan is known
41+
resp.UseStateForUnknown = true
42+
},
43+
expectedPlanValue: types.Int64Value(10),
44+
},
45+
{
46+
name: "Config is Unknown (Interpolation)",
47+
stateValue: types.Int64Value(5),
48+
planValue: types.Int64Unknown(),
49+
configValue: types.Int64Unknown(),
50+
ifFunc: func(_ context.Context, _ string, _ planmodifier.Int64Request, resp *UseStateForUnknownFuncResponse) {
51+
// This should not be reached
52+
resp.UseStateForUnknown = true
53+
},
54+
expectedPlanValue: types.Int64Unknown(),
55+
},
56+
{
57+
name: "Condition returns False (Do not use state)",
58+
stateValue: types.Int64Value(5),
59+
planValue: types.Int64Unknown(),
60+
configValue: types.Int64Null(), // Simulating computed only
61+
ifFunc: func(_ context.Context, _ string, _ planmodifier.Int64Request, resp *UseStateForUnknownFuncResponse) {
62+
resp.UseStateForUnknown = false
63+
},
64+
expectedPlanValue: types.Int64Unknown(),
65+
},
66+
{
67+
name: "Condition returns True (Use state)",
68+
stateValue: types.Int64Value(5),
69+
planValue: types.Int64Unknown(),
70+
configValue: types.Int64Null(),
71+
ifFunc: func(_ context.Context, _ string, _ planmodifier.Int64Request, resp *UseStateForUnknownFuncResponse) {
72+
resp.UseStateForUnknown = true
73+
},
74+
expectedPlanValue: types.Int64Value(5),
75+
},
76+
{
77+
name: "Func returns Error",
78+
stateValue: types.Int64Value(5),
79+
planValue: types.Int64Unknown(),
80+
configValue: types.Int64Null(),
81+
ifFunc: func(_ context.Context, _ string, _ planmodifier.Int64Request, resp *UseStateForUnknownFuncResponse) {
82+
resp.Diagnostics.AddError("Test Error", "Something went wrong")
83+
},
84+
expectedPlanValue: types.Int64Unknown(),
85+
expectedError: true,
86+
},
87+
}
88+
89+
for _, tt := range tests {
90+
t.Run(tt.name, func(t *testing.T) {
91+
// Initialize the modifier
92+
modifier := UseStateForUnknownIf(tt.ifFunc, "", "test description")
93+
94+
// Construct request
95+
req := planmodifier.Int64Request{
96+
StateValue: tt.stateValue,
97+
PlanValue: tt.planValue,
98+
ConfigValue: tt.configValue,
99+
}
100+
101+
// Construct response
102+
// Note: In the framework, resp.PlanValue is initialized to req.PlanValue
103+
// before the modifier is called. We must simulate this.
104+
resp := &planmodifier.Int64Response{
105+
PlanValue: tt.planValue,
106+
}
107+
108+
// Run the modifier
109+
modifier.PlanModifyInt64(ctx, req, resp)
110+
111+
// Check Errors
112+
if tt.expectedError {
113+
if !resp.Diagnostics.HasError() {
114+
t.Error("Expected error, got none")
115+
}
116+
} else {
117+
if resp.Diagnostics.HasError() {
118+
t.Errorf("Unexpected error: %s", resp.Diagnostics)
119+
}
120+
}
121+
122+
// Check Plan Value
123+
if !resp.PlanValue.Equal(tt.expectedPlanValue) {
124+
t.Errorf("PlanValue mismatch.\nExpected: %s\nGot: %s", tt.expectedPlanValue, resp.PlanValue)
125+
}
126+
})
127+
}
128+
}

0 commit comments

Comments
 (0)