How to set defaults for an object?

I’m using the terraform plugin framework.

I have this resource schema:

func (g *GSI) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
	resp.Schema = schema.Schema{
        ...
        "with": schema.SingleNestedAttribute{
				Optional: true,
				Computed: true,
				Default: objectdefault.StaticValue(
					types.ObjectValueMust(
						map[string]attr.Type{
							"defer_build":   types.BoolType,
							"num_replica":   types.Int64Type,
							"num_partition": types.Int64Type,
						},
						map[string]attr.Value{
							"defer_build":   types.BoolValue(false),
							"num_replica":   types.Int64Value(0),
							"num_partition": types.Int64Null(),
						},
					)),
				Attributes: map[string]schema.Attribute{
					"defer_build": schema.BoolAttribute{
						Optional: true,
						Computed: true,
					},
					"num_replica": schema.Int64Attribute{
						Optional: true,
						Computed: true,
					},
					"num_partition": schema.Int64Attribute{
						Optional: true,
						Validators: []validator.Int64{
							int64validator.AtLeast(1),
						},
					},
				},
			}
       }
}

This doesn’t work. For example, if I omit num_replica from the HCL, the state file shows a value of null, but I’m expecting 0.

Also I’m a bit nervous about using types.ObjectValueMust . The doc says:

This creation function is only recommended to create Object values which will not potentially affect practitioners, such as testing, or exhaustively tested provider logic.

Is there a way to do this without types.ObjectValueMust ?

Hi @picavoh.mobijaf,

You’re setting a default for the with attribute, so omitting that attribute will cause the resource to plan a default value in its place. If you want a default for num_replica while still supplying the rest of the with object, you must specify a default for num_replica too.

1 Like

Got it, thanks.

The goals is if with attribute is omitted from HCL, it should set default values ie with.num_replica to 0, and with.defer_build as false.

If with attribute is provided in HCL, but say only has with.defer_build is true, then with.num_replica should default to 0.