kerlant
kerlant

Reputation: 23

Destroy AWS resources of a failed/canceled Terraform apply

So I've used a lot AWS CDK and if a deployment fails I can destroy de Cloudformation stack an any service created is destroyed. But using Terraform I end up having the same problem of cancelling or failing a deployment (terraform apply) but some resources has been deployed before it failed, however if I run terraform destroy it does not know that these resources has been deployed... so is the only way to clean up these resources manually? Or I'm missing something?

(I know that this deployment should be run in a CICD, but if the pipeline fails the deployment the problem will be the same: some orphan AWS resources that have to be deleted manually).

Upvotes: 0

Views: 2823

Answers (1)

Tuan Nguyen
Tuan Nguyen

Reputation: 567

I did a quick test and even terraform apply failed in the middle, it still keeps completed resources in terraform.tfstate

File main.tf

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

resource "aws_vpc" "test" {
  cidr_block       = "10.0.0.0/16"
  instance_tenancy = "default"

  tags = {
    Name = "test"
  }
}

resource "aws_subnet" "sub1" {
  vpc_id     = aws_vpc.test.id
  cidr_block = "10.0.1.0/24"

  tags = {
    Name = "sub1"
  }
}

resource "aws_subnet" "sub2" {
  vpc_id     = aws_vpc.test.id
  cidr_block = "10.0.2.0/24"

  tags = {
    Name = "sub2"
  }
}

resource "aws_subnet" "sub3" {
  vpc_id     = aws_vpc.test.id
  cidr_block = "10.0.0.0/8"

  tags = {
    Name = "sub3"
  }
}

resource "aws_route_table" "rtb1" {
  depends_on = [aws_subnet.sub3]
  vpc_id = aws_vpc.test.id

  route = []

  tags = {
    Name = "rtb1"
  }
}

Terraform plan passed and failed on terraform apply as below: enter image description here

You can see the state list and this is the result of terraform destroy enter image description here

Upvotes: 1

Related Questions