What is the difference between the data source Configure in provider.go and in data_source.go files?


I’m working through the “Implement a provider wit the Terraform Plugin Framework” and reading the similar framework documentation. I’m attempting to make a provider for an application running locally with a rest API.

Initially I tried to keep it simple with just setting the client to &http.Client since that was used in the documentation, but I need to include a username and password to authenticate for the API calls to work, so I set up a struct in the provider.go file that included an http client, username, and password. I’m really just not understanding how this relates to the configure function in the data_sources.go file I’m setting up.

Can someone help me understand what these two configure functions are doing, how they’re different, and how I should code this to get it to work with a simple http client with username/password authentication?

The provider’s Configure() method has access to the provider configuration stanza in your (probably) provider.tf file via this thing.

The Configure() method on a Data Source and Resource have access to these things which only know about breadcrumbs the provider has decided are appropriate to leave behind for their use.

A likely workflow, then:

  1. The provider has access to API URL and credentials via the provider configuration stanza.
  2. When the provider’s Configure() method is invoked (this happens only once per plan/apply), the provider authenticates with the API, gets a session token or whatever, and leaves a logged-in http.Client object around for Data Sources and Resources to use.
  3. The Data Sources and Resources (possibly many of them) don’t need to individually authenticate with the API because they’ve got access to the already-logged-in client left behind by the provider.

This is so helpful. Thanks for the walkthrough. The issue I guess is that I don’t think the endpoint I’m working with (ONOS, using JAAS auth services) generates a token to use for future calls. Assuming that’s the case, should I forgo using the configure methods and just put the http client authentication code and api request directly in the data source’s read method?

I would definitely not put credentials in the data or resource stanzas, because that will put the credentials in your terraform state.

I would probably do this:

  • Make URL, username, password (or whatever) Optional = true, in the provider schema.
  • In the provider’s Configure() method, check both the config object and the environment for variables which include those details (forcing users to write authentication secrets in the config file isn’t great either).
  • Error if the required info can’t be found in either place.
  • Define a provider data structure where you’ll leave those details for use by resources and data sources.
  • Collect the provider data struct in each resource and data source’s Configure() method.