Should terraform treat computed values as null by default?

I use the terraform plugin framework.

A resource has an attribute replica this is computed. Here is the schema:

"replica": schema.Int64Attribute{
						Optional:            true,
						Computed:            true,
						PlanModifiers: []planmodifier.Int64{
							int64planmodifier.UseStateForUnknown(),
						},
					},

The user did not specify the replica value in the config. To get this value provider calls GET endpoint and then populates the state file. Unfortunately sometimes creating the resource fails, so do not reach the code path where the GET endpoint is called to get the computed value. The following error was seen:

Problem with resource "provider_resource":
After the apply operation, the provider still indicated an unknown value
for provider_resource.create_resource.replica.  All values must be known after apply, so this is always a bug in the provider and should be reported in the provider's own repository. Terraform will still save the other known object values in the state.

To get around this problem I initialize the computed value to null ie

func (t *Thing) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
	var plan schema.Resource
	resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
	if resp.Diagnostics.HasError() {
		return
	}

	// initialize computed attributes to null.
	if plan.Replica.IsNull() || plan.Replica.IsUnknown() {
			plan.Replica = types.Int64Null()
	}

   // create the resource 
   // call GET endpoint to get latest status of resource
   // save to state file

}

I’m wondering why terraform does not automatically assume computed attributes are null ? There are corner cases where provider cannot get this compute value.

Or if I should be doing this in a better way, let me know !

Hi @picavoh.mobijaf,

Terraform can only follow the planned resource change returned by a provider, and will only save exactly what that provider returned after the change is applied. A provider returning an unknown value after apply is a violation of the plugin protocol, so Terraform isn’t going to assume that particular error should just be ignored as null because it could be an actual failure which is missing critical data.

I’m not sure what the common design patterns for framework providers look like, but logically if you have an early return from the Create function, you will need to ensure all the necessary values are set before that return point, so that the resulting object is valid for all non-error return paths.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.