Type conversion from slice of user defined type to types.List

Help me find relevant documentation or examples preferably with generated code using tfplugin-framework.

tfplugingen-framework generate all --input ./provider_code_spec.json --output internal/provider

The tutorials talks about conversion from []string to types.List only. Plugin Development - Framework: List Type | Terraform | HashiCorp Developer

Hi @TheNilesh :wave:t6:,
Can you describe your use case in more detail? Are you trying to generate provider code using tfplugingen-framework from your provider code specification and want a specific field to convert to types.List in the final generated provider code?

I want to implement convert() that converts from a slice of domain objects to types.List and vice versa. Here’s the relevant source code.

nodes_data_source.go

nodesList, err := d.client.ListNodes(projectID)
if err != nil {
	resp.Diagnostics.AddError("Failed to list nodes", err.Error())
	return
}
state.Nodes = convert(nodesList) // I want to implement convert()

nodes_data_source_gen.go

type NodesModel struct {
	Filter FilterValue  `tfsdk:"filter"`
	Id     types.String `tfsdk:"id"`
	Nodes  types.List   `tfsdk:"nodes"`
}

type NodesValue struct {
	Id            basetypes.StringValue `tfsdk:"id"`
	Name          basetypes.StringValue `tfsdk:"name"`
	PrimaryIp     basetypes.StringValue `tfsdk:"primary_ip"`
	Status        basetypes.StringValue `tfsdk:"status"`
	state         attr.ValueState
}

Hi @TheNilesh,

Thank you for the context. To convert from a Go slice to the Framework type types.List, you can use types.ListValueFrom()

For example, assuming nodesList is of type []Nodes:

var convertDiags diag.Diagnostics  
state.Nodes, convertDiags = types.ListValueFrom(ctx, state.Nodes.ElementType(ctx), nodesList)  
if convertDiags.HasError() {  
    resp.Diagnostics.Append(convertDiags...)  
    return  
}

There’s many examples of this type of conversion in the DNS Provider, if you would like more references.

Thanks, @SBGoods that helps!

1 Like