Using resource_data functions with data source

In the SDK there are ResourceData functions like GetChange which allow us to read user provided or computed attributes during a resource CRUD operations.

Are there equivalent functions for data resources? I’m trying to read a computed value of a data source but GetChange, Get or other functions doesn’t work with the data sources.

Hi @hus,

Is there a reason why you want to use GetChange for a data source?

Terraform data sources implements the “CR” (create and read) in CRUD. As a result, if you’re creating or modifying a data source, you should already have access to the computed value.

The three core steps in implementing a data source read is:

  1. Retrieve data from the API (Lines 73-83)
  2. Map response to a struct that the TF SDK can understand (Lines 84-88)
  3. Set the data source values (Lines 90-92)

If you wanted to apply conditional logic based on the data you received from the API, you would do it between steps 2 and 3. You would just access the data directly from the struct you created (i.e. coffees[0]).

The Setup and Implement Read tutorial walks you through the process of setting up a sample Terraform provider and creating a data source.

Hope this answer your question and have a great day!

– Tu

Hi @ im2nguyen

Is there a reason why you want to use GetChange for a data source?

I’m working on data_source_generic_secret and trying to read existing lease_id from Terraform state. When I check the state file I can see the lease_id is there, but Get functions don’t read it.

I’ll try to implement that again and let you know.

Thanks,
Hus

I was able to read data returned by API using get functions like GetOk but I would like to read the existing value from the Terraform state file. Is there a function in SDK or another way to read the existing state file entries?

When I use GetOk function before an API request the result was empty as expected.

Thanks,
Hus

The Terraform protocol only supplies access to the config values for the data source. Data source state, unfortunately, isn’t available to providers on the assumption that Terraform is not the source of truth for it, and the provider will be replacing the state entirely.

1 Like