Skip to content

Commit

Permalink
Adding plan modifier (#303)
Browse files Browse the repository at this point in the history
  • Loading branch information
bendbennett committed Sep 1, 2022
1 parent fae7ea6 commit 47c5c51
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 2 deletions.
56 changes: 56 additions & 0 deletions internal/planmodifiers/attribute.go
Expand Up @@ -143,3 +143,59 @@ func (d *numberNumericAttributePlanModifier) Modify(ctx context.Context, req tfs
return
}
}

func RequiresReplaceIfValuesNotNull() tfsdk.AttributePlanModifier {
return requiresReplaceIfValuesNotNullModifier{}
}

type requiresReplaceIfValuesNotNullModifier struct{}

func (r requiresReplaceIfValuesNotNullModifier) Modify(ctx context.Context, req tfsdk.ModifyAttributePlanRequest, resp *tfsdk.ModifyAttributePlanResponse) {
if req.AttributeConfig == nil || req.AttributePlan == nil || req.AttributeState == nil {
// shouldn't happen, but let's not panic if it does
return
}

if req.State.Raw.IsNull() {
// if we're creating the resource, no need to delete and
// recreate it
return
}

if req.Plan.Raw.IsNull() {
// if we're deleting the resource, no need to delete and
// recreate it
return
}

attrConfig := req.AttributeConfig

m, ok := attrConfig.(types.Map)
if !ok {
return
}

replace := false

for _, v := range m.Elems {
if v.IsNull() && !v.IsUnknown() {
continue
}

replace = true
}

if replace {
resp.RequiresReplace = true
}
}

// Description returns a human-readable description of the plan modifier.
func (r requiresReplaceIfValuesNotNullModifier) Description(ctx context.Context) string {
return "If the value of this attribute changes, Terraform will destroy and recreate the resource."
}

// MarkdownDescription returns a markdown description of the plan modifier.
func (r requiresReplaceIfValuesNotNullModifier) MarkdownDescription(ctx context.Context) string {
return "If the value of this attribute changes, Terraform will destroy and recreate the resource."
}
8 changes: 6 additions & 2 deletions internal/provider/resource_integer.go
Expand Up @@ -12,6 +12,7 @@ import (
"github.com/hashicorp/terraform-plugin-framework/tfsdk"
"github.com/hashicorp/terraform-plugin-framework/types"

"github.com/terraform-providers/terraform-provider-random/internal/planmodifiers"
"github.com/terraform-providers/terraform-provider-random/internal/random"
)

Expand All @@ -34,8 +35,11 @@ func (r *integerResourceType) GetSchema(context.Context) (tfsdk.Schema, diag.Dia
Type: types.MapType{
ElemType: types.StringType,
},
Optional: true,
PlanModifiers: []tfsdk.AttributePlanModifier{resource.RequiresReplace()},
Optional: true,
Computed: true,
PlanModifiers: []tfsdk.AttributePlanModifier{
planmodifiers.RequiresReplaceIfValuesNotNull(),
},
},
"min": {
Description: "The minimum inclusive value of the range.",
Expand Down

0 comments on commit 47c5c51

Please sign in to comment.