Is terraform destroy needed before terraform apply?
Terraform destroy will no doubt provide you a clean slate to work with your infrastructure but it is not needed to run terraform destroy before running terraform apply or plan commands.
There is one caution while working with terraform destroy
command, it is not advisable to run it on a production environment because it can do some serious damage to your cloud infrastructure setup.
Just to keep everything in sync you can use terraform refersh
anytime or even before you apply to terraform configuration.
This blog will help you to understand a bit more on how and when to use terraform destroy and terraform refresh
Table of Content
- When to use Terraform destroy?
- How to refresh and keep your terraform state(tfstate) file up to date with your infrastructure changes?
1. When to use Terraform destroy?
Well the first golden rule with terraform destroy
is you should never use it in the production environment because there is no returning once you execute the terraform destroy
.
1.1 Instead use terraform destroy with -target to destroy specific resource
The safe way to run the terraform destroy
is along with the -target
parameter because once you specify the -target
param then you need to pass the resource name which you want to destroy from your cloud infrastructure.
Here is the example command where I am trying to destroy aws_instance
with the name jhooq_hello
-
1terraform destroy -target aws_instance.jhooq_hello
The benefit of using the above command is - "It will only destroy the aws_instance
with the name jhooq_hello
" and you are safe from accidentally deleting all of your infrastructure resources.
1.2 Remove resource from terraform.tfstate file
In the previous step, we have seen how to remove/destroy specific resources using -target
parameter.
But suppose if you want to destroy all other resources except one resource then I would recommend you to use terraform state rm <resource-to-exclude-from-destroy>
so that you can exclude the resource from getting destroyed.
1terraform state rm aws_instance.jhooq_hello
Now we have excluded the aws_instance.jhooq_hello
and you can run the terraform destroy
command and it will destroy all other resources.
1.3 Use terraform lifecycle block to prevent destroy
One more recommended way to create and prevent the resource is to use the lifecycle
block inside your terraform configuration so that the resource does not get deleted accidentally.
Here is an example terraform configuration -
1provider "aws" {
2 region = "eu-central-1"
3 access_key = "AKIATQ37NXB2JMXVGYPG"
4 secret_key = "ockvEN1DzYynDuKIh56BVQv/tMqmzvKnYB8FttSp"
5}
6
7resource "aws_instance" "ec2_example" {
8
9 ami = "ami-0767046d1677be5a0"
10 instance_type = "t2.micro"
11
12 tags = {
13 Name = "Terraform EC2"
14 }
15 lifecycle {
16 prevent_destroy= true
17 }
18}
If you try to run the terraform destroy
command it will throw the following error -
1the plan would destroy this resource, but it currently has lifecycle.preven_destroy set to true. to avoid this error and continue with the plan. either disable or adjust the scope.
1.4 Use terraform nuke (Only for development purpose)
You can check How to nuke AWS resources and save additional AWS infrastructure cost? for destroying everything in one command but it is only intended for development purposes.
2. How to refresh and keep your local terraform state(tfstate) file up to date with remote terraform state(tfstate)?
Well there is one more important question Will terraform.tfstate file will be in sync if someone has deleted or updated the resource manually?
In such scenario, it is always recommended to use terraform refresh
so that the local terraform state(tfstate) and remote terraform state(tfstate) are in sync.
For Example -: Let suppose you have created three aws_instance
- aws_instance.ec2_example1
- aws_instance.ec2_example2
- aws_instance.ec2_example3
And you manually deleted the aws_instance.ec2_example2 from your AWS console.
So using terraform refresh
you can sync your both local terraform state(tfstate) and remote terraform state(tfstate).
Now you will have a better understanding of terraform destroy
, terraform refresh
and when to use both.
Read More - Terragrunt -
Posts in this Series
- Securing Sensitive Data in Terraform
- Boost Your AWS Security with Terraform : A Step-by-Step Guide
- How to Load Input Data from a File in Terraform?
- Can Terraform be used to provision on-premises infrastructure?
- Fixing the Terraform Error creating IAM Role. MalformedPolicyDocument Has prohibited field Resource
- In terraform how to handle null value with default value?
- Terraform use module output variables as inputs for another module?
- How to Reference a Resource Created by a Terraform Module?
- Understanding Terraform Escape Sequences
- How to fix private-dns-enabled cannot be set because there is already a conflicting DNS domain?
- Use Terraform to manage AWS IAM Policies, Roles and Users
- How to split Your Terraform main.tf File into Multiple Files
- How to use Terraform variable within variable
- Mastering the Terraform Lookup Function for Dynamic Keys
- Copy files to EC2 and S3 bucket using Terraform
- Troubleshooting Error creating EC2 Subnet InvalidSubnet Range The CIDR is Invalid
- Troubleshooting InvalidParameter Security group and subnet belong to different networks
- Managing strings in Terraform: A comprehensive guide
- How to use terraform depends_on meta argument?
- What is user_data in Terraform?
- Why you should not store terraform state file(.tfstate) inside Git Repository?
- How to import existing resource using terraform import comand?
- Terraform - A detailed guide on setting up ALB(Application Load Balancer) and SSL?
- Testing Infrastructure as Code with Terraform?
- How to remove a resource from Terraform state?
- What is Terraform null Resource?
- In terraform how to skip creation of resource if the resource already exist?
- How to setup Virtual machine on Google Cloud Platform
- How to use Terraform locals?
- Terraform Guide - Docker Containers & AWS ECR(elastic container registry)?
- How to generate SSH key in Terraform using tls_private_key?
- How to fix-Terraform Error acquiring the state lock ConditionalCheckFiledException?
- Terraform Template - A complete guide?
- How to use Terragrunt?
- Terraform and AWS Multi account Setup?
- Terraform and AWS credentials handling?
- How to fix-error configuring S3 Backend no valid credential sources for S3 Backend found?
- Terraform state locking using DynamoDB (aws_dynamodb_table)?
- Managing Terraform states?
- Securing AWS secrets using HashiCorp Vault with Terraform?
- How to use Workspaces in Terraform?
- How to run specific terraform resource, module, target?
- How Terraform modules works?
- Secure AWS EC2s & GCP VMs with Terraform SSH Keys!
- What is terraform provisioner?
- Is terraform destroy needed before terraform apply?
- How to fix terraform error Your query returned no results. Please change your search criteria and try again?
- How to use Terraform Data sources?
- How to use Terraform resource meta arguments?
- How to use Terraform Dynamic blocks?
- Terraform - How to nuke AWS resources and save additional AWS infrastructure cost?
- Understanding terraform count, for_each and for loop?
- How to use Terraform output values?
- How to fix error configuring Terraform AWS Provider error validating provider credentials error calling sts GetCallerIdentity SignatureDoesNotMatch?
- How to fix Invalid function argument on line in provider credentials file google Invalid value for path parameter no file exists
- How to fix error value for undeclared variable a variable named was assigned on the command line?
- What is variable.tf and terraform.tfvars?
- How to use Terraform Variables - Locals,Input,Output
- Terraform create EC2 Instance on AWS
- How to fix Error creating service account googleapi Error 403 Identity and Access Management (IAM) API has not been used in project before or it is disabled
- Install terraform on Ubuntu 20.04, CentOS 8, MacOS, Windows 10, Fedora 33, Red hat 8 and Solaris 11