Delete Resources
Deletion is part of the basic Terraform lifecycle for managing resources. During the terraform apply
command, Terraform calls the provider ApplyResourceChange
RPC, in which the framework calls the resource.Resource
interface Delete
method. The request contains Terraform prior state data. The response is only for returning diagnostics. The data is defined by the schema of the resource.
Terraform 1.3 and later enables deletion planning, which resources can implement to return warning and error diagnostics. For additional information, refer to the resource plan modification documentation.
Other resource lifecycle implementations include:
- Create resources by receiving Terraform configuration and plan data, performing creation logic, and saving Terraform state data.
- Read resources by receiving Terraform prior state data, performing read logic, and saving refreshed 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.
Define Delete Method
Implement the Delete
method by:
- Accessing prior state data from the
resource.DeleteRequest.State
field. - Performing logic or external calls to destroy the resource.
If the logic needs to return warning or error diagnostics, they can added into the resource.DeleteResponse.Diagnostics
field.
In this example, the Delete
function makes a HTTP call and returns successfully if the status code was 200 OK or 404 Not Found:
Caveats
Note these caveats when implementing the Delete
method:
- An error is returned if the response state is set to anything other than null.
- Any response errors will cause Terraform to keep the resource under management.
Recommendations
Note these recommendations when implementing the Delete
method:
- Ignore errors that signify the resource is no longer existent.
- Skip calling the response state
RemoveResource()
method. The framework automatically handles this logic with the response state if there are no error diagnostics.