Terraform
Configuring list resources
List Resources may require provider-level data or API clients to operate correctly. The framework supports the ability to configure this data and/or clients once within the provider, then pass that information to actions by adding the Configure method.
Prepare Provider Configure Method
Implement the provider.ConfigureResponse.ListResourceData field in the Provider interface Configure method.
This value can be set to any type, whether an existing client or vendor SDK type, a provider-defined custom type, or the provider implementation itself.
It is recommended to use pointer types so that the list resource can determine if this value was configured before attempting to use it.
In this example, the Go standard library net/http.Client is configured in the provider and made available for the list resource:
func (p *ExampleCloudProvider) Configure(ctx context.Context, req provider.ConfigureRequest, resp *provider.ConfigureResponse) {
resp.ListResourceData = &http.Client{/* ... */}
}
Define List Resource Configure Method
Implement the list.ListResourceWithConfigure interface which receives the provider configured data from the Provider interface Configure method and saves it into the list.ListResource interface implementation.
The list.ListResourceWithConfigure interface Configure method is called during execution of any Terraform command, however the provider is not configured during "offline" operations like terraform validate or terraform fmt, so implementations need to account for that situation.
In this example, the provider configured the Go standard library net/http.Client which the list resource uses during List:
type ThingListResource struct {
client *http.Client
}
func (r *ThingListResource) Configure(ctx context.Context, req list.ConfigureRequest, resp *list.ConfigureResponse) {
// Always perform a nil check when handling ProviderData because Terraform
// sets that data after it calls the ConfigureProvider RPC.
if req.ProviderData == nil {
return
}
client, ok := req.ProviderData.(*http.Client)
if !ok {
resp.Diagnostics.AddError(
"Unexpected List Configure Type",
fmt.Sprintf("Expected *http.Client, got: %T. Please report this issue to the provider developers.", req.ProviderData),
)
return
}
d.client = client
}
func (r *ThingListResource) List(ctx context.Context, req list.ListRequest, stream *list.ListResultsStream) {
httpReq, _ := http.NewRequest(
http.MethodPost,
"http://example.com/api/list_thing",
bytes.NewBuffer([]byte(`{"fake": "data"}`)),
)
httpResp, err := d.client.Do(httpReq)
/* ... */
}