terraform icon indicating copy to clipboard operation
terraform copied to clipboard

feature request: terraform state rm option to remove all resources created with a given provider

Open navi86 opened this issue 6 years ago • 8 comments
trafficstars

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

navi86 avatar Oct 08 '19 10:10 navi86

terraform state list | xargs -L 1 terraform state rm

ghost avatar Dec 16 '19 19:12 ghost

terraform state list | cut -f 1 -d '[' | xargs -L 1 terraform state rm

remoe avatar Jan 01 '20 19:01 remoe

or, without locking state between each resource:

terraform state list | cut -f 1 -d '[' | xargs -L 0 terraform state rm

dmccaffery avatar Aug 13 '20 18:08 dmccaffery

also worked for me:

terraform state rm $(terraform state list | grep aws_instance)

sann05 avatar Sep 29 '20 12:09 sann05

On terragrunt, this worked for me

terragrunt state list | sed 's/"/\\"/g' | xargs -I {} terragrunt state rm {}

arash-bizcover avatar Apr 22 '21 12:04 arash-bizcover

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.

erpel avatar Oct 09 '23 13:10 erpel

If like me you're terrified of wrecking everything on accident, state rm has a helpful -dry-run flag

elliotdickison avatar Aug 14 '24 19:08 elliotdickison

Just use

terraform state rm $(terraform state list)

yurinogueira avatar Nov 05 '24 18:11 yurinogueira

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

chrispruitt avatar Apr 09 '25 13:04 chrispruitt