Will Terraform Delete my Existing Infrastructure on AWS when Apply?

tanut aran
3 min readNov 21, 2023

--

This can be the serious concern if you

  1. Already have AWS and resources created manually
  2. Considering adopt Terraform

You know that Terraform will try to create the infrastructure as described in the code.

This means adding something, editing something and deleting something.

If you have only one resource in the code, you worry that Terraform will delete everything else when apply to match the infra in the code.

Short Answer: No

Terraform will only delete something they create.

Long Answer: No, It see everything by State File

To understand why, you have to know that Terraform will see the infrastructure by “State file”.

It will not go to your AWS and inspecting everything.

When first apply, Terraform create state file.

When apply change, Terraform see state file, make change, then update state file.

When destroy, Terraform see state file, delete resources it see, then update state file.

Some Experiment: Creating EC2

You can see this by yourself with simple hands-on experiment for example, creating the EC2 with Terraform.

Create empty folder and add main.tf with following code.

terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.16"
}
}

required_version = ">= 1.2.0"
}

provider "aws" {
region = "ap-southeast-1"
}

resource "aws_instance" "app_server" {
ami = "ami-078c1149d8ad719a7"
instance_type = "t2.micro"

tags = {
Name = "ExampleAppServerInstance"
}
}

You can dry run to check before applying with plan command.

You see only one thing Terraform add and nothing to destroy.

$ terraform plan

...

Plan: 1 to add, 0 to change, 0 to destroy.

Then you run terraform apply , now you see the EC2 created and terraform.tfstate appears. You see EC2 in the state file.

Nothing else in your AWS account is deleted.

Try Deleting State file

Then if you delete the state file terraform.tfstate

Then run plan command again. It try to create the duplicated EC2.

This prove Terraform inspect nothing. It reads, operates and writes through the state file.

When apply, you can see the duplicated instance created.

Now you see how it works.

Bonus: How to destroy EC2 in the first state file you deleted

Now you run terraform destroy the first ExampleAppServerInstance is going away.

Now, you must delete the orphan ExampleAppServerInstance manually because this go away with first state file you delete.

Another recovery way is to import it manually.

You see instance id in the console, then you recover this by import command.

terraform import aws_instance.app_server i-043d6ee6568720eed 

Now your terraform know the instance and match this with app_server in the main.tf file.

Now Terraform know this resource.

So you can delete this by terraform destroy !

See you next time : )

--

--

tanut aran
tanut aran

Written by tanut aran

Co-founder and Coder at work !

No responses yet