compliance.tf

What are Terraform lifecycle rules?

Terraform lifecycle rules are arguments placed inside a resource's lifecycle block, including prevent_destroy, ignore_changes and create_before_destroy, and they alter the way Terraform schedules creation, modification and removal of that resource.

The main settings

SettingEffectTypical use
prevent_destroy = trueAs long as this argument remains in the configuration, a plan that would delete or replace the resource errors out. Deleting the resource block lifts the protection as well.Databases, S3 buckets, KMS keys
ignore_changes = [...]Terraform disregards the named attributes when comparing stored state with the configurationTags managed by external tooling, autoscaled capacity, rotated passwords
create_before_destroy = trueTerraform builds the replacement object prior to removing the original oneSecurity groups, certificates
resource "aws_s3_bucket" "this" {
  bucket = "example-data"

  lifecycle {
    prevent_destroy = true
    ignore_changes  = [tags]
  }
}

The module limitation

Within Terraform, prevent_destroy, ignore_changes and create_before_destroy accept literal values alone, and the long-running request for variable support (hashicorp/terraform#3116) has been closed. Because of that, a reusable Terraform module cannot expose prevent_destroy as an input. OpenTofu 1.12 and newer permits an expression in prevent_destroy, while the other two stay literal. A wrapper module also cannot inject lifecycle settings into the resources of the module it invokes, so teams that need them on a third-party module end up forking it.

How compliance.tf applies it

Operational Rules write lifecycle values into the module code at download time, so you do not need to fork the module. Examples from the rule catalog:

RuleWhat it sets
lifecycle_prevent_destroy_dataprevent_destroy for S3, RDS and Aurora, DynamoDB, EFS and ElastiCache resources
lifecycle_prevent_destroy_encryptionprevent_destroy for KMS keys and Secrets Manager secrets
lifecycle_ignore_tagsignore_changes = [tags, tags_all]
lifecycle_create_before_destroycreate_before_destroy for security groups and ACM certificates

To verify what was put in place, inspect the downloaded module:

grep -B1 -A2 "prevent_destroy" .terraform/modules/s3_bucket/main.tf

Sources

On this page

Ask AI about this

Help improve this page