DEV Community

Bartłomiej Danek
Bartłomiej Danek

Posted on • Originally published at bard.sh

Terraform lifecycle rules

lifecycle rules

lifecycle controls how Terraform creates, updates, and destroys a resource.

resource "aws_db_instance" "main" {
  identifier = "main-db"

  lifecycle {
    create_before_destroy = true
    prevent_destroy       = true
    ignore_changes        = [password, engine_version]
  }
}
Enter fullscreen mode Exit fullscreen mode

create_before_destroy

By default Terraform destroys then creates. With create_before_destroy it creates the replacement first - useful for resources that can't have downtime (load balancers, DNS records, certificates).

resource "aws_instance" "web" {
  ami           = data.aws_ami.latest.id
  instance_type = "t3.small"

  lifecycle {
    create_before_destroy = true
  }
}
Enter fullscreen mode Exit fullscreen mode

prevent_destroy

Blocks terraform destroy and any plan that would delete the resource. Good for databases and S3 buckets you can't lose.

resource "aws_s3_bucket" "critical" {
  bucket = "company-backups"

  lifecycle {
    prevent_destroy = true
  }
}
Enter fullscreen mode Exit fullscreen mode
# this will error:
terraform destroy
# Error: Instance cannot be destroyed
Enter fullscreen mode Exit fullscreen mode

ignore_changes

Stops Terraform from overwriting fields that change outside of Terraform - e.g. auto-scaling group sizes, passwords rotated by another tool.

resource "aws_autoscaling_group" "app" {
  name             = "app-asg"
  desired_capacity = 2

  lifecycle {
    ignore_changes = [desired_capacity]
  }
}
Enter fullscreen mode Exit fullscreen mode

Use ignore_changes = all to ignore every attribute - useful for resources fully managed externally.

replace_triggered_by

Force replacement when another resource or attribute changes:

resource "aws_instance" "app" {
  ami = data.aws_ami.latest.id

  lifecycle {
    replace_triggered_by = [aws_security_group.app.id]
  }
}
Enter fullscreen mode Exit fullscreen mode

Originally published at https://bard.sh/posts/terraform_lifecycle/

Top comments (0)