terraform
terraform copied to clipboard
feature request: terraform state rm option to remove all resources created with a given provider
Hi there, I think command "terraform rm module.${provider_name}" should remove all resources created with that provider. Terraform v0.12.9
Use-cases
I have some helm chart created using provider helm_release
Attempted Solutions
I can delete resources if I specify full path to resource.
example
terraform rm module.helm_release.dex
Proposal
"terraform rm module.${provider_name}" should remove all resources for defined provider
terraform state list | xargs -L 1 terraform state rm
terraform state list | cut -f 1 -d '[' | xargs -L 1 terraform state rm
or, without locking state between each resource:
terraform state list | cut -f 1 -d '[' | xargs -L 0 terraform state rm
also worked for me:
terraform state rm $(terraform state list | grep aws_instance)
On terragrunt, this worked for me
terragrunt state list | sed 's/"/\\"/g' | xargs -I {} terragrunt state rm {}
If using for_each with values or keys that might contain spaces, apply shell escaping for these too. The -I {} was not needed with macOs 13.5 xargs (from FreeBSD)
terraform state list | sed 's/"/\\"/g;s/ /\\ /g' | xargs terragrunt state rm
Be careful with all of these examples, as using the output of terraform state list unfiltered will work on all resources.
If like me you're terrified of wrecking everything on accident, state rm has a helpful -dry-run flag
Just use
terraform state rm $(terraform state list)
You could push an empty state file by pulling the current state, modifying it, and pushing it back up. You need to set the resources to empty and increment the serial by 1. I had to do this for a lot of backends when we were reorganizing our orgs and workspaces so I wrote a script to modify the state files, but here's the gist of it. This was a little faster for me than using terraform state rm.
# Read the JSON object from source-state.json
json_data=$(cat source-state.json)
# Use jq to modify the JSON object
modified_json=$(echo "$json_data" | jq '.outputs = {} | .resources = [] | .serial += 1')
# Write the modified JSON object to empty-state.json
echo "$modified_json" > empty-state.json