Force DocumentDB replacement on VPC change

AWS cannot move a DocumentDB subnet group or cluster to a different VPC. Include the VPC ID in the subnet group name and create it before destroy, and add a replace_triggered_by lifecycle rule so the cluster is recreated when the subnet group changes instead of failing on an unsupported in-place update.

Document the behaviour and the snapshot caveat in the module README.
This commit is contained in:
Cédric Verstraeten
2026-08-11 13:08:35 +02:00
parent 687a0019d8
commit bf164c208b
2 changed files with 33 additions and 2 deletions

View File

@@ -68,6 +68,28 @@ terraform apply
Creating the cluster and the database takes a while (EKS and DocumentDB are
both slow to provision).
### Replacing the VPC
AWS cannot move a DocumentDB subnet group or cluster between VPCs. The subnet
group name therefore includes the VPC ID, allowing Terraform to create a new
group and replace the cluster when the VPC changes instead of attempting an
unsupported in-place subnet update.
Discard any saved plan created before a VPC replacement or configuration
change, then create and apply a fresh one:
```bash
rm -f tfplan
terraform plan -out=tfplan
terraform apply tfplan
```
> [!WARNING]
> Replacing the VPC also replaces the DocumentDB cluster. If it contains data,
> create and verify a snapshot before applying the plan; a final snapshot
> preserves the old data but is not restored into the replacement cluster
> automatically.
State is kept locally by default. For anything shared, add a backend, for
example:

View File

@@ -22,7 +22,8 @@ resource "random_password" "docdb" {
}
locals {
docdb_password = var.docdb_password != null ? var.docdb_password : random_password.docdb[0].result
docdb_password = var.docdb_password != null ? var.docdb_password : random_password.docdb[0].result
docdb_subnet_group_name = "${local.name}-docdb-${module.vpc.vpc_id}"
}
resource "aws_security_group" "docdb" {
@@ -56,11 +57,15 @@ resource "aws_vpc_security_group_ingress_rule" "docdb_from_cidrs" {
}
resource "aws_docdb_subnet_group" "this" {
name = "${local.name}-docdb"
name = local.docdb_subnet_group_name
description = "Private subnets of the Kerberos Hub VPC"
subnet_ids = module.vpc.private_subnets
tags = local.tags
lifecycle {
create_before_destroy = true
}
}
resource "aws_docdb_cluster_parameter_group" "this" {
@@ -107,6 +112,10 @@ resource "aws_docdb_cluster" "this" {
final_snapshot_identifier = var.docdb_skip_final_snapshot ? null : "${local.name}-docdb-final"
tags = local.tags
lifecycle {
replace_triggered_by = [aws_docdb_subnet_group.this.name]
}
}
resource "aws_docdb_cluster_instance" "this" {