Reputation: 1051
I deployed AWS infrastructure using Terraform and the state file is maintained in S3. Now I wanted to destroy this infrastructure and hence running a build which runs terraform plan
followed by terraform destroy
This destroyed most of the resources but got stuck while destroying one s3 bucket, so i manually killed the step. I noticed that the state file in s3 was unaltered. Now when I re-run the build which has terraform plan
followed by terraform destroy
, the plan step fails because the actual infrastructure does not match the one in the state file.
I would like to know how to rectify this.
Is there a way I can update the state file manually to reflect the current infrastructure?
Upvotes: 4
Views: 2269
Reputation: 700
As a "wrapper" to @Marcin's proposed solution above you could use terraform state rm
within a basic bash loop based on the output of terraform state list
. Below a simple example:
List resources in state file
$ terraform state list
data.aws_ami.amazon_linux
data.aws_subnet_ids.def_vpc_public_subnets
data.aws_vpc.def_vpc
aws_instance.test1
aws_security_group.sec_ssh_ping
(send list to a text file)
$ terraform state list > state_list.txt
(Edit state_list.txt so that it contains only resources you want deleted) (backup state file)
Delete Resources listed in file with a bash loop
$ for s in $(cat state_list.txt) ;do echo "removing $s"; terraform state rm $s ; done
removing data.aws_ami.amazon_linux
Removed data.aws_ami.amazon_linux
Successfully removed 1 resource instance(s).
removing data.aws_subnet_ids.def_vpc_public_subnets
Removed data.aws_subnet_ids.def_vpc_public_subnets
Successfully removed 1 resource instance(s).
removing data.aws_vpc.def_vpc
Removed data.aws_vpc.def_vpc
Successfully removed 1 resource instance(s).
removing aws_instance.test1
Removed aws_instance.test1
Successfully removed 1 resource instance(s).
removing aws_security_group.sec_ssh_ping
Removed aws_security_group.sec_ssh_ping
Successfully removed 1 resource instance(s).
I would be extra careful and try this in a test account/environment before hitting any important/production infrastructure.
Upvotes: 4