PF-01 · AWS · IaC
AWS multi-region Terraform
A Terraform module set that builds the same infrastructure in 16 AWS regions from one locals map per region.
- 16
- Regional provider aliases
- 24
- Terraform modules
- 3
- Validated examples
- Problem
-
The same resources had to exist in many regions. More regions meant more copied code and a higher risk that regions drift apart.
- Approach
-
A locals map per region declares the wanted state, and module plus for_each creates it all. Each region has a provider alias that assumes the same role. Terraform cannot choose a provider dynamically inside for_each, so the module block repeats per region.
- Result
-
A change is one map entry, and stable keys mean reordering never recreates anything. The 24 modules carry defaults for encryption, IMDSv2, and private S3, and three examples cover networks, EKS, and alerting.
- What I learned
-
Stable keys mattered as much as less repetition. count identifies resources by their position in a list, so inserting or reordering an entry can recreate everything after it, while for_each identifies them by map key, so the same resource is addressed whatever the order. Terraform cannot pick a provider inside for_each, and instead of hiding that limit, I repeated the module block per region in plain sight, which turned out easier to read and change. Since then, when the same structure has to exist in many places, I separate data (the map) from code (the module) first, and I judge the design by whether a change ends at one map entry.