Recommended way to trim white space from value in plan

I have a provider that interacts with an API that will trim white space for some values. So if I have my_value = "foo " in my Terraform config, the API will return "foo" as a response. This results in a “Provider produced inconsistent result after apply” error because the plan expected the trailing space.

I tried creating a custom plan modifier to trim this value before the plan:

func (t *TrimStringWhitespace) PlanModifyString(ctx context.Context, req planmodifier.StringRequest, resp *planmodifier.StringResponse) {
	if req.PlanValue.IsNull() || req.PlanValue.IsUnknown() {
		return
	}

	stringVal := strings.TrimSpace(req.PlanValue.ValueString())
	resp.PlanValue = types.StringValue(stringVal)
}

However, this triggered an invalid plan error

│ Provider planned an invalid value for resouce.my_value: planned
│ value cty.StringVal("foo") does not match config value cty.StringVal("foo ").

What is the recommended way to handle an API that trims white space?

This sounds like a scenario where you’d want to use a custom type which handles "foo" and " foo " as semantically equal.

The jsontypes.Normalized type found here might be a good starting point for a custom string type which trims whitespace when evaluating equality.

Though I might have sidestepped the problem by using a regex validator which rejects user input like that :slight_smile: