4
votes

I recently tested and created a UI with Cloudfront, S3 and WAF.

I made some changes to the Cloudfront module and hardcoded the created WAF ACL name so that each time I perform terraform apply it will be using the WAF I created. Then I removed the WAF module from my code.

When I try to do another terraform apply it says that the WAF will be destroyed. I assume its because I removed the WAF module.

Is there a way where I can perform a terraform plan/apply and skip destroying the WAF which was recently deployed from previous deployments?

3
Why have you removed the WAF configuration from your Terraform code if you want to keep it?ydaetskcoR

3 Answers

12
votes

terraform state rm some.resource.to.remove

Terraform state management actually works very well, I use it most often when moving a resource, e.g. when I modularised something that consisted of separate resources before. In that case, Terraform initially tries to destroy the old resource and create a new one, so I use:

terraform state mv aws_lb.my_lb module.some_module.aws_lb.my_lb

2
votes

You can use terraform -target=resource to update only a specific resource and its dependencies. This may be clunky, but should allow you to work around the missing declaration.

Alternatively you could remove the resource from the .tfstate file. I don't know whether terraform has any option to do that, and it might be a complex operation if the resource has many dependants.

0
votes

Just in case you don't want to remove the resources from the code and the state file, add the prevent_destroy attribute under the lifecycle block in all of those resources.

See example below:

variable "enable_prevent_destroy" {
  description = "Boolean to decide whether to enable enable_prevent_destroy or not"
  default     = true
}

resource "aws_instance" "example" {
  ami                    = data.aws_ami.ubuntu.id
  instance_type          = "t2.micro"
  vpc_security_group_ids = [aws_security_group.sg_web.id]
  tags = {
    Name          = "my-ec2"
  }

  lifecycle {
    prevent_destroy = var.enable_prevent_destroy
  }
}

Reference: Terraform | Manage Resource Lifecycle | Prevent resource deletion

Note: For this to work, you will need the Terraform v0.14 or later.