Terraform: Unintended Resource Replacement from for_each Key Changes on Immutable Attributes

TechLab Editorial TeamPublished 16 views1 answer
1

Editorial Q&A · This problem and its answer were written by the TechLab editorial team to document a common issue. It isn't a question from a community member. If you've hit a variation of it or know a better approach, add a reply below.

A common pitfall encountered by professional developers when using Terraform (v1.7.0) involves unintended resource replacement, particularly with resources managed via for_each. This often occurs when the keys used in a for_each expression are modified, even if the underlying resource configuration remains largely the same. Terraform interprets a change in a for_each key as the destruction of the resource associated with the old key and the creation of a new resource with the new key, rather than an in-place update.

Consider a scenario where multiple AWS S3 buckets are managed using for_each, with bucket names derived directly from local map keys. Initially, the local map might define keys like "app-logs" and "data-backup". If a developer later decides to standardize prefixes, changing "app-logs" to "prod-app-logs", Terraform plans to destroy the app-logs bucket and create a new prod-app-logs bucket. For stateful resources like S3 buckets that might contain critical data, this behavior is highly undesirable and can lead to data loss or service disruption.

TERRAFORM
# main.tf (Initial configuration)
locals {
  bucket_configs = {
    "app-logs" = {
      acl        = "private"
      versioning = true
    },
    "data-backup" = {
      acl        = "private"
      versioning = true
    }
  }
}

resource "aws_s3_bucket" "example" {
  for_each = local.bucket_configs
  bucket   = each.key # Bucket name derived from for_each key
  acl      = each.value.acl
}

resource "aws_s3_bucket_versioning" "example" {
  for_each = local.bucket_configs
  bucket   = aws_s3_bucket.example[each.key].id
  versioning_configuration {
    status = each.value.versioning ? "Enabled" : "Disabled"
  }
}

output "bucket_names" {
  value = [for k, v in aws_s3_bucket.example : v.bucket]
}

Now, modify local.bucket_configs by changing "app-logs" to "prod-app-logs":

TERRAFORM
# main.tf (Modified configuration)
locals {
  bucket_configs = {
    "prod-app-logs" = { # Key changed
      acl        = "private"
      versioning = true
    },
    "data-backup" = {
      acl        = "private"
      versioning = true
    }
  }
}
# ... rest of the code is the same ...

Expected behavior: Terraform should recognize that the app-logs bucket is conceptually being renamed and either propose an in-place update or provide a controlled mechanism to migrate the resource without data loss.

Actual behavior: When terraform plan is executed after the key change, Terraform proposes to destroy the aws_s3_bucket.example["app-logs"] resource and create aws_s3_bucket.example["prod-app-logs"], along with corresponding versioning resources. The plan explicitly states: Terraform will perform the following actions: - destroy aws_s3_bucket.example["app-logs"] - destroy aws_s3_bucket_versioning.example["app-logs"] + create aws_s3_bucket.example["prod-app-logs"] + create aws_s3_bucket_versioning.example["prod-app-logs"]

This behavior leads to data loss for the app-logs bucket, as it is destroyed before the new one is created.

The question: How can Terraform be configured to prevent unintended resource destruction and recreation when for_each keys are altered, especially for stateful resources where the key directly drives an immutable identifier like an S3 bucket name?

Advertisement

1 Answer

0

Root Cause

The observed behavior stems from Terraform's strict resource instance tracking and the immutability of certain cloud resource attributes. Each resource managed by for_each is assigned a unique instance address by Terraform, combining its resource type, local name, and the specific key from the for_each expression (e.g., aws_s3_bucket.example["app-logs"]).

When a key in the for_each expression changes (e.g., from "app-logs" to "prod-app-logs"), Terraform perceives this as the disappearance of the resource instance at the old address and the appearance of a brand-new instance at the new address. Terraform has no inherent mechanism to understand that this constitutes a "rename" or logical evolution of an existing resource. Consequently, it generates a plan to destroy the resource associated with the old, now absent, key and create a new resource for the newly introduced key.

For resources like AWS S3 buckets, the bucket name (bucket attribute) is a primary identifier that is immutable after creation. If the for_each key directly populates this immutable attribute, Terraform correctly identifies that an in-place update or rename is not possible via the AWS API. Therefore, its only option is to destroy the old resource (with the old name) and create a new one (with the new name). This behavior, while technically correct from Terraform's perspective given the underlying cloud provider's API constraints, can lead to critical data loss or service disruption for stateful resources if not handled carefully.

Corrected Code and Solution (A controlled migration strategy)

Since S3 bucket names are immutable, a direct in-place update or simple terraform state mv operation is insufficient if the actual bucket name needs to change. Instead, a controlled, multi-step migration process is required to ensure data integrity and minimize disruption. This involves separating the resource creation, data migration, and resource deletion into distinct, deliberate phases.

Step 1: Implement a lifecycle block to prevent accidental deletion. This is a critical safety measure, ensuring Terraform cannot destroy existing, stateful buckets without explicit manual override, thereby preventing accidental data loss during planning errors or refactoring.

TERRAFORM
# main.tf (Initial configuration, BEFORE any key change - ensure 'prevent_destroy' is present)
locals {
  bucket_configs = {
    "app-logs" = {
      acl        = "private"
      versioning = true
    },
    "data-backup" = {
      acl        = "private"
      versioning = true
    }
  }
}

resource "aws_s3_bucket" "example" {
  for_each = local.bucket_configs
  bucket   = each.key
  acl      = each.value.acl

  lifecycle {
    prevent_destroy = true # CRITICAL: Prevents accidental destruction of stateful buckets.
  }
}

resource "aws_s3_bucket_versioning" "example" {
  for_each = local.bucket_configs
  bucket   = aws_s3_bucket.example[each.key].id
  versioning_configuration {
    status = each.value.versioning ? "Enabled" : "Disabled"
  }
  lifecycle {
    prevent_destroy = true # Also protect dependent resources from unintended deletion.
  }
}

output "bucket_names" {
  value = [for k, v in aws_s3_bucket.example : v.bucket]
}

Apply this configuration first: terraform apply. This ensures existing resources are protected.

Step 2: Introduce the new resource instance while temporarily preserving the old one. Modify local.bucket_configs to include both the old key ("app-logs") and the new key ("prod-app-logs"). This tells Terraform to create the new bucket without planning to destroy the old one yet.

TERRAFORM
# main.tf (TEMPORARY configuration for phased migration - includes both old and new keys)
locals {
  bucket_configs = {
    "app-logs" = {      # Old key, will be removed later
      acl        = "private"
      versioning = true
    },
    "prod-app-logs" = { # New key, being introduced
      acl        = "private"
      versioning = true
    },
    "data-backup" = {
      acl        = "private"
      versioning = true
    }
  }
}
# ... rest of resource blocks remain the same, including lifecycle { prevent_destroy = true } ...

Run terraform plan: This plan will show only the creation of aws_s3_bucket.example["prod-app-logs"] and its associated versioning resource. Apply this plan: terraform apply. The new prod-app-logs bucket is now created in AWS.

Step 3: Perform data migration and update application dependencies. This is a manual, out-of-band step vital for stateful resources:

  • Data Migration: Use appropriate tools (e.g., AWS CLI: aws s3 sync s3://app-logs s3://prod-app-logs) to migrate all necessary data from the old bucket (app-logs) to the new one (prod-app-logs).
  • Application Updates: Update any applications, services, or IAM policies that referenced app-logs to now point to prod-app-logs.
  • Verification: Thoroughly verify that all systems are correctly interacting with the new bucket and that the data migration was successful.

Step 4: Remove the old resource definition and explicitly allow destruction. Once data is migrated, dependencies are updated, and systems are verified, modify local.bucket_configs to remove the old key ("app-logs").

TERRAFORM
# main.tf (FINAL desired configuration - only new key remains)
locals {
  bucket_configs = {
    "prod-app-logs" = { # Only the new key remains
      acl        = "private"
      versioning = true
    },
    "data-backup" = {
      acl        = "private"
      versioning = true
    }
  }
}
# ... rest of resource blocks ...

# TEMPORARILY disable prevent_destroy for the old resource before destruction
resource "aws_s3_bucket" "example" {
  for_each = local.bucket_configs
  bucket   = each.key
  acl      = each.value.acl

  lifecycle {
    prevent_destroy = false # Temporarily set to false to allow destruction of the old bucket.
  }
}

resource "aws_s3_bucket_versioning" "example" {
  for_each = local.bucket_configs
  bucket   = aws_s3_bucket.example[each.key].id
  versioning_configuration {
    status = each.value.versioning ? "Enabled" : "Disabled"
  }
  lifecycle {
    prevent_destroy = false # Temporarily set to false for the old versioning resource.
  }
}

Run terraform plan: This will now show a plan to destroy aws_s3_bucket.example["app-logs"] and its versioning resource. Apply this plan: terraform apply. The old app-logs bucket will now be destroyed.

Important: Remember to re-enable prevent_destroy = true in your lifecycle blocks after the old resources have been successfully destroyed to restore the safety measure for your remaining infrastructure.

  1. Immutable Attributes Driving Recreation: This problem is most pronounced when a for_each key directly populates an attribute that is immutable once the resource is created (e.g., S3 bucket names, certain database instance types, VPC CIDR blocks). Always consult resource documentation to understand which attributes trigger replacement versus in-place updates.
  2. Complex Cross-Resource Dependencies: If many other Terraform resources explicitly depend on the renamed resource, their for_each keys or references may also need careful adjustment. This can complicate the phased migration strategy, potentially requiring multiple terraform state mv operations or further temporary configurations.
  3. moved Blocks (Terraform 1.1+): For scenarios where a resource's address changes (e.g., moving a resource from a standalone definition to a for_each block, or changing a module path) without necessitating the recreation of the underlying cloud resource, Terraform v1.1+ introduced moved blocks. These declare that a resource object has moved from one address to another, allowing Terraform to update state without manual terraform state mv commands or planning recreation. However, they do not circumvent the destroy/create plan if the underlying cloud resource itself must be recreated due to an immutable attribute change driven by the new key.

💡 Bonus Tip:

When designing your Terraform configurations, for resources where identifiers derived from for_each keys might change, consider decoupling the internal, immutable identifier from human-readable names. For example, use a stable id (like a UUID) as the for_each key, and then use a separate, mutable attribute for the human-readable name or label. If only the human-readable label changes, Terraform can perform an in-place update. This approach makes resource instance tracking more resilient to cosmetic naming changes and simplifies refactoring efforts.

TechLab Editorial TeamAuthorAnswered

Know the answer?

Posting answers needs a TechLab plan. Reading every discussion stays free.