Why set state for a datasource?

looking at this tutorial it shows the following:

func (d *coffeesDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {

...
// Set state
    diags := resp.State.Set(ctx, &state)
    resp.Diagnostics.Append(diags...)
    if resp.Diagnostics.HasError() {
      return
    }

couple of questions:

  1. help me understand why we set state, since datasource only retrieves resources.
  2. why is this in the last line if resp.Diagnostics.HasError() { return } ? function will return anyway as its the end of the function block

Hi @picavoh.mobijaf,

1: I’m not sure what you mean by “only retrieves resources”. The “state” here refers to the state of the data source, i.e. the value you are going to return. You set it so that it can be transmitted back to Terraform.

2: Yeah, the early return is obviously not necessary, the example was probably truncated from a larger one where an early return would avoid later logic in the function body.

1 Like

Thanks @jbardin

Here is what I mean by “only retrieves resources.” I notice that whatever is fetched by the datasource is saved in the state file. What is the use case of this ?

That is, does terraform ever look at the state file for datasources ? If yes then why ?

How terraform stores the data is a separate implementation detail from the plugin protocol you are working with when implementing a provider.

Terraform does currently store the state returned by data resources, but only due to legacy constraints. That stored data is not used for evaluation by terraform, and can probably be dropped entirely in a future major release.

1 Like