Tainting a Resource - Terraform

Tainting a Resource - Terraform

You have created a new resource via Terraform and multiple users(your teammates) have made a lot of manual changes with respect to the infrastructure you have created.

There are two ways to deal with these manual changes: <1>. Import the changes to Terraform. <2>. Delete and re-create the resource.

The Terraform taint command manually marks a terraform-managed resource as tainted and forces it to be destroyed and re-created on the apply (terraform apply).

Taking an example to understand:

Let's create a configuration file as tainting.tf

provider "aws" {
  region     = "ap-south-1"
  access_key = "GIVE-ACCESS-KEY"
  secret_key = "GIVE-SECRET-KEY"
}

resource "aws_instance" "myec2" {
    ami = "GIVE AMI-ID"
    instance_type = "t2.micro"
}

Now whatever users did manually on the resource(here aws_instance), we want to revert all those changes and use the configuration of instance as written in tainting.tf file.

> terraform taint aws_instance.myec2

You will get output like - Resource instance aws_instance.myc2 has been marked as tainted.

> terraform plan

We can see that the resource aws_instance.myce2 is marked as tainted in .tfstate file only. so to apply these changes we need to use terraform apply command.

> terraform apply

Now, the resource will be destroyed and re-created.

Thank you so much for taking your valuable time for reading.

I have tried my level best to explain as much information as possible in the easiest manner. Any feedback for further improvement will be highly appreciated!

#WeMakeDevs

We can connect at: Rahul Kumar Verma | LinkedIn