Issue with calling `Plan.Get` despite model struct containing required fields

Hello! I’m sure I’m making a very silly mistake as I’m just making my way through the terraform plugin provider tutorials but for the life of me I can’t figure out the issue.

I’m trying to define a terraform resource, I have defined the Schema method, a model struct type containing all the fields using types.String/Bool/etc (see here for my code), and have confirmed that when calling terraform apply the code reaches my Create method but fails for the following block:

        // Retrieve values from plan
	var plan lessonResourceModel
	diags = req.Plan.Get(ctx, &plan)
	resp.Diagnostics.Append(diags...)
	if resp.Diagnostics.HasError() {
		return
	}

with error mismatch between struct and object: Object defines fields not found in struct: (proceeds to list all of my fields)

I’ve confirmed with the following snippet that req.Plan has all the values I’m expecting:

        var test types.String
	diags := req.Plan.GetAttribute(ctx, path.Root("title"), &test)
	resp.Diagnostics.Append(diags...)
	if resp.Diagnostics.HasError() {
		return
	}

	fmt.Println(test.ValueString())

But for whatever reason it thinks that lessonResourceModel doesn’t have the fields specified (even though I defined it directly above this function). Any things I should be looking out for?

Hey there @glipR, welcome to the discuss forum :wave:!

Taking a quick look, I believe you’re running into a problem due to the visibility of the fields in your struct, as Plan.Get uses Go reflection to set these fields. The fields in your struct need to be exported (public), which in Go, is just done by capitalizing the field name.

Current (private)

type lessonResourceModel struct {
	id       types.Int64  `tfsdk:"id"`
	attempts types.Int64  `tfsdk:"attempts"`
// etc.
}

New (public)

type lessonResourceModel struct {
	Id       types.Int64  `tfsdk:"id"`
	Attempts types.Int64  `tfsdk:"attempts"`
// etc.
}

Try capitalizing all the struct field names that have tfsdks tags and see if that resolves your issue!

1 Like

That error message is unfortunately not super descriptive of the root cause, I’ve opened an issue to improve that error messaging for future provider developers: Improve reflection error messaging for unexported fields with `tfsdk` tags · Issue #866 · hashicorp/terraform-plugin-framework · GitHub

Hopefully that helps!

1 Like