Custom Terraform Provider - Invalid Address to Set

I am currently writing a custom TF provider to be used with an internal API/Service.

ATM it’s just a minimal single data source as a PoC but I’m having issues setting the value on the data resource. A terraform apply shows the following error:

2021-12-07T14:50:25.569Z [INFO]  provider.terraform-provider-jscontroller_v1.0.0: 2021/12/07 14:50:25 [ERROR] setting state: Invalid address to set: []string{"items"}: timestamp=2021-12-07T14:50:25.568Z

I’ve looked at this several ways, read various docs & Stack Overflow posts but cannot wrap my head around what is actually wrong here.

The data resource looks like this:

package jscontroller

import (
	"context"
	"log"

	"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

func dataSourceAgents() *schema.Resource {
	return &schema.Resource{
		ReadContext: dataSourceAgentsRead,
		Schema: map[string]*schema.Schema{
			"tenant_id": {
				Type:     schema.TypeString,
				Required: true,
			},
			"agent_ids": {
				Type:     schema.TypeList,
				Computed: true,
				Elem: &schema.Schema{
					Type: schema.TypeString,
				},
			},
		},
	}
}

func dataSourceAgentsRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	c := m.(*Client)

	var diags diag.Diagnostics

	tenantId := d.Get("tenant_id").(string)

	agent_ids, err := c.getAgents(&tenantId)
	if err != nil {
		return diag.FromErr(err)
	}
	log.Printf("Data: %s", agent_ids)
	log.Printf("Data Type: %T", agent_ids)

	if err := d.Set("items", agent_ids); err != nil {
		return diag.FromErr(err)
	}

	return diags
}

The agent_ids var that comes back from the getAgents function is a []string.

Hi @danny.roberts,

The schema for this data source doesn’t seem to include an attribute names “items”, and so the Set function doesn’t know how to set it.

You can declare an “output” attribute like this with the field Computed: true to tell the SDK that this is something only to be set by the data source itself, and not allowed in the configuration.

2 Likes

Thanks @apparentlymart - not sure where I got the name items from now, I changed it to agent_ids to match the “spec” & it was fine. Thanks!

this helped thank you @apparentlymart !