Read Resources
Read (refresh) is part of the basic Terraform lifecycle for managing resources. During the terraform apply
, terraform plan
, and terraform refresh
commands, Terraform calls the provider ReadResource
RPC, in which the framework calls the resource.Resource
interface Read
method. The Read
method is also executed after resource import. The request contains Terraform prior state data. The response contains the refreshed state data. The data is defined by the schema of the resource.
Other resource lifecycle implementations include:
- Create resources by receiving Terraform configuration and plan data, performing creation logic, and saving Terraform state data.
- Update resources in-place by receiving Terraform prior state, configuration, and plan data, performing update logic, and saving updated Terraform state data.
- Delete resources by receiving Terraform prior state data and performing deletion logic.
Define Read Method
Implement the Read
method by:
- Accessing prior state data from the
resource.ReadRequest.State
field. - Retriving updated resource state, such as remote system information.
- Writing state data into the
resource.ReadResponse.State
field.
If the logic needs to return warning or error diagnostics, they can added into the resource.ReadResponse.Diagnostics
field.
In this example, the Read
function makes a HTTP call and refreshes the state data if the status code was 200 OK or removes the resource if 404 Not Found:
Caveats
Note these caveats when implementing the Read
method:
- An error is returned if the response state contains unknown values. Set all attributes to either null or known values in the response.
- Any response errors will cause Terraform to keep the prior resource state.
Recommendations
Note these recommendations when implementing the Read
method:
- Ignore returning errors that signify the resource is no longer existent, call the response state
RemoveResource()
method, and return early. The next Terraform plan will recreate the resource. - Refresh all possible values. This will ensure Terraform shows configuration drift and reduces import logic.
- Preserve the prior state value if the updated value is semantically equal. For example, JSON strings that have inconsequential object property reordering or whitespace differences. This prevents Terraform from showing extraneous drift in plans.