Prevent unintended Amazon RDS cluster replacement when Terraform reads a dynamic Availability Zone list
AWS Regions grow over time as new Availability Zones are added. If your Terraform configuration reads the Region’s Availability Zone list dynamically and passes it directly into a database resource, that growth can have an unexpected consequence: the next terraform apply can propose deleting and rebuilding your cluster. In this post, you learn why this happens, how to prevent it in your Terraform, and how to protect the data on independent layers even if a destructive change slips through.
This post assumes you are comfortable with core Terraform concepts - resources, data sources, state, and the plan and apply workflow. You do not need a running cluster to follow the reasoning; the configuration examples are here for when you want to apply the patterns to your own Amazon RDS or Amazon Aurora setup.
The scenario
Consider a common situation. You provisioned an Amazon Aurora (or Amazon RDS) cluster with Terraform months ago, and it has run without incident ever since. Today you make a small, unrelated change (perhaps a tag or a security group rule) and run terraform plan. The plan reports something you did not expect: your database cluster must be replaced. (Running terraform apply computes the same plan first and waits for your approval, so the warning appears there too, before anything changes.)
# aws_rds_cluster.main must be replaced -/+ resource "aws_rds_cluster" "main" { ~ availability_zones = [ # forces replacement "us-west-2a", "us-west-2b", "us-west-2c", + "us-west-2d", # newly added zone, picked up automatically ] # ... }
You did not touch the database configuration, so what changed? The Region did. AWS added a new Availability Zone, and your configuration read the Availability Zone list dynamically on the next plan. The returned list no longer matched what Terraform had recorded in state, and that mismatch was enough to mark the cluster for replacement.
Approve that plan, or let an auto-approved pipeline apply it, and Terraform deletes the running cluster and builds a new one. For a stateful resource, that means data loss and downtime, set off by a change you never intended to make.
Note: The Terraform AWS provider team is aware of this behavior and is tracking a fix in GitHub issue #49991. Once that change ships, the provider will validate the Availability Zone list before planning, and a newly added zone will no longer trigger a cluster replacement. Until the fix is released, the safeguards in this post remain the recommended way to protect your clusters.
Why it happens
Two behaviors combine to produce this result.
First, the Availability Zone argument is immutable. For the aws_rds_cluster resource, the AWS provider cannot change availability_zones in place. Any edit to that list forces a full destroy-and-recreate rather than an in-place update. The provider documentation is explicit about it:
"RDS automatically assigns 3 AZs if less than 3 AZs are configured, which will show as a difference requiring resource recreation next Terraform apply. We recommend specifying 3 AZs or using the lifecycle configuration block ignore_changes argument if necessary."
Second, the configuration reads the Availability Zone list dynamically. This pattern is common, and it looks harmless:
data "aws_availability_zones" "available" { state = "available" } resource "aws_rds_cluster" "main" { cluster_identifier = "main" availability_zones = data.aws_availability_zones.available.names # the risk engine = "aurora-postgresql" # ... }
The aws_availability_zones data source returns every Availability Zone currently available to your account in that Region, and Terraform re-evaluates it on every plan. Add a new Availability Zone to the Region and the list changes. Terraform compares it to state, detects a change on an immutable argument, and marks the cluster for replacement. It is behaving exactly as configured.
There is a second pitfall specific to aws_rds_cluster. The availability_zones argument accepts at most three Availability Zones, and RDS auto-assigns three if you provide fewer. So a dynamic list is not only unstable between plans; it can also return more zones than the argument allows. As the Region grows, you get either a surprise replacement or an outright error.
Each behavior is intentional on its own. The provider treats the Availability Zone list as immutable, and your configuration reads a list that grows as the Region grows. The two combine to turn a routine apply into a cluster replacement. The Terraform community has reported this interaction many times (see the Further reading section at the end of this post)
The core lesson: separate discovery from placement
The root cause is asking one value to do two different jobs:
- Discovery answers "which Availability Zones does my account have access to in this Region right now?" That answer is meant to grow over time.
- Placement answers "which Availability Zones is my database pinned to?" That should be a deliberate, stable decision.
Figure 1. Discovery vs. placement. Wiring a growable discovery source directly into an immutable placement argument is what turns a new Availability Zone into a cluster replacement. (Replace this placeholder with the final diagram before publishing.)
When you pass the discovery result directly into the placement argument, the two become a single value. After that, every Availability Zone AWS adds changes your database configuration on its own, with no decision from you. Keep them separate. Treat cloud-provider lists (Availability Zones, instance types, service endpoints) as values that grow over time, and do not connect "what is available" directly to "what my resources use."
This is not only an RDS concern. RDS and Aurora are where it surfaces most often, but the same pattern appears anywhere a dynamic list feeds an immutable argument:
- Amazon DocumentDB (
aws_docdb_cluster) carries the sameavailability_zonesbehavior as RDS, including the auto-assign-three-Availability-Zones recreation note and theignore_changesrecommendation. - Classic Load Balancer (
aws_elb) is a variation on the theme. Itsavailability_zonesargument is mutable, so a new Availability Zone alone will not force replacement. The risk appears when dynamic Availability Zone detection feeds a dynamic subnet lookup: a new zone can silently change the subnet set, causing disruption or forcing a new resource.
# Dynamic AZ detection grabs every available AZ in the region data "aws_availability_zones" "detected" { state = "available" } # Dynamic subnet lookup filters by those AZs data "aws_subnets" "public" { filter { name = "tag:Environment" values = ["production"] } filter { name = "availability-zone" values = data.aws_availability_zones.detected.names } } # The ELB receives a subnet list that can shift when the Region grows resource "aws_elb" "example" { name = "production-elb" subnets = data.aws_subnets.public.ids # risk: set changes silently # ... }
The common thread: whenever you pass a growable data source such as aws_availability_zones or aws_subnets into a field the provider treats as immutable, pin it or apply ignore_changes to it, and keep prevent_destroy on anything stateful.
Fixing it in your Terraform
Option 1: Pin the Availability Zone list explicitly (preferred)
Make placement a deliberate choice that lives in version control:
variable "db_availability_zones" { type = list(string) default = ["us-west-2a", "us-west-2b", "us-west-2c"] } resource "aws_rds_cluster" "main" { cluster_identifier = "main" availability_zones = var.db_availability_zones engine = "aurora-postgresql" # ... }
Now a new Availability Zone in the Region changes nothing here until you decide to edit the variable yourself.
Option 2: Ignore changes to the Availability Zone argument
This is the provider's own recommendation. Use it when something upstream can still surface the field, such as RDS auto-assigning three Availability Zones when you configure fewer. See the Terraform lifecycle meta-arguments for details:
resource "aws_rds_cluster" "main" { cluster_identifier = "main" # ... lifecycle { ignore_changes = [availability_zones] # a changing Region AZ list no longer forces replacement } }
Once the cluster exists, Terraform stops reconciling that field, and a changing Region Availability Zone list no longer triggers a replacement.
Option 3: Add a hard guardrail against destruction
On any stateful resource, prevent_destroy converts an accidental replacement into a failed plan rather than a deleted database:
resource "aws_rds_cluster" "main" { # ... lifecycle { prevent_destroy = true # Terraform-level protection } }
If some future change ever tries to destroy the cluster, Terraform halts with an error and puts a human back in the loop.
If you still want visibility into new Availability Zones, keep a separate, read-only aws_availability_zones data source for reporting or outputs, and never connect it to a resource's Availability Zone argument.
Make the database itself hard to lose
Terraform guardrails stop the destructive plan, but the strongest setups protect the database on two independent layers and use both:
- Terraform layer.
prevent_destroymakes Terraform refuse any plan that would destroy the resource. It guards against your own Terraform, from a mistaken change to a stray-targetflag, but only while a change flows through Terraform. - AWS layer.
deletion_protectionlives on the database itself and blocks deletion from the console, AWS CLI, and SDK too, even when Terraform is not involved. Turning it off is a separate, deliberate step.
resource "aws_db_instance" "example" { identifier = "my-secure-db" engine = "mysql" instance_class = "db.t3.micro" allocated_storage = 20 deletion_protection = true # AWS-level protection lifecycle { prevent_destroy = true # Terraform-level protection } }
Then add a recovery net so you can restore even after a legitimate delete:
- A final snapshot on deletion. Set
skip_final_snapshot = falseand providefinal_snapshot_identifier, so a deletion still leaves a recoverable snapshot behind. - Automated backups and point-in-time recovery. Keep a healthy
backup_retention_periodso you can rewind to a moment before the incident.
Here is the same idea on the Aurora cluster from earlier, with both layers and a recovery net in place:
resource "aws_rds_cluster" "main" { cluster_identifier = "main" engine = "aurora-postgresql" availability_zones = var.db_availability_zones backup_retention_period = 14 deletion_protection = true # AWS-level protection skip_final_snapshot = false final_snapshot_identifier = "main-final" lifecycle { ignore_changes = [availability_zones] prevent_destroy = true # Terraform-level protection } }
Catch it before apply
This failure is only dangerous because a destructive plan can reach apply without anyone reviewing it. Two habits close that gap:
- Review the plan, every time. Run
terraform plan -out=tfplanand gate apply on a review of that saved plan. A# forces replacementline on a database should stop the pipeline every time. - Enforce it with policy as code. Let Sentinel or Open Policy Agent (OPA/conftest) fail any plan that destroys or replaces a protected resource in CI. That turns the review into something that happens on every change, not only the ones people remember to check.
Both habits align with the AWS Well-Architected Reliability Pillar: REL08 (implement change) and REL11 (design workloads to withstand component failures).
Adopt new Availability Zones on purpose
You can take on a new Availability Zone safely, as long as you do it deliberately. When you are ready to use one:
- Check availability first, read-only via the EC2 DescribeAvailabilityZones API, or a standalone
aws_availability_zonesdata source used purely for outputs. - Update your pinned Availability Zone variable in a reviewed change.
- Plan and validate the impact. For many resources, changing the Availability Zone set is still a replacement, so plan the migration rather than letting it surprise you.
- Apply through your normal reviewed pipeline.
Expansion then becomes a deliberate, reviewable event rather than a side effect of your next unrelated apply.
Conclusion
A growing Region should never be able to delete your database as a side effect of an unrelated change. The fix comes down to keeping discovery separate from placement and defending stateful resources on more than one layer. Before your next apply, review your own configurations for these points:
- Never feed a dynamic
aws_availability_zonesresult into an immutable argument such as a cluster'savailability_zones. - Pin Availability Zones explicitly, and use
ignore_changeswhere the provider recommends it. - Protect stateful resources on both layers:
prevent_destroyin Terraform anddeletion_protectionin AWS. Back them with a final snapshot and point-in-time recovery. - Gate destructive plans with plan review and policy as code.
- Above all, assume every provider enumeration will grow, and adopt new ones deliberately rather than automatically.
Apply these patterns, and a new Availability Zone simply means more capacity for you to adopt when you are ready, with no impact on your running database.
Further reading
- aws_rds_cluster resource: see the
availability_zonesnote on recreation andignore_changes. - Terraform lifecycle meta-arguments:
ignore_changes,prevent_destroy,create_before_destroy. - AWS Well-Architected Reliability Pillar: REL08 (implement change) and REL11 (withstand component failures).
- Amazon RDS robustness: deletion protection and point-in-time recovery.
- Same class of behavior on other services: aws_docdb_cluster, aws_elb.
- Community reports of the same failure: terraform-provider-aws issues #49991, #29149 and #7779.
Contributors
Ankit Srivastava, Kevin Hughes, Madhav Vishnubhatta, Brian Simpson-Adkins, Krish Balaraman, kiran khambete, Roby Sharma, Amit Parikh
- Language
- English
Relevant content
AWS OFFICIALUpdated 3 months ago
AWS OFFICIALUpdated 2 years ago
AWS OFFICIALUpdated 5 months ago