I’ve been neck-deep in DevOps lately, and one thing keeps coming back: Infrastructure as Code reads better when it’s boring.
Let me show you what I mean—one migration, two ways to wire it.
Say you’ve got several networks in one account and you want each VPC living in its own account going forward.
1 | # network.auto.tfvars |
You’ll reuse a module per account. Fair.
And no, you can’t dynamically pick a provider at runtime—Terraform doesn’t do that.
The real question is how you shard that vpcs map so each module gets the right slice.
Two patterns I’ve seen a lot of teams reach for:
Option 1: group in code
Tag every VPC with an acct_key, then let locals do the grouping.
1 | # network.auto.tfvars |
You need two for expressions because Terraform’s native ... merge gives you arrays keyed the same way; what you want is one object per account so you can still do module.acct_a_vpcs.vpcs.network1 on outputs.
Plan output looks like:
1 | + group_result = { |
Classic engineer move: config barely changes, locals eat the complexity. Ship it.
…except there’s a second way.
Option 2: group in config
Structure the vars file the way the accounts actually look.
1 | # network.auto.tfvars |
Wiring is almost insultingly clear:
1 | module "acct_a_vpcs" { |
Both get the job done. For day-to-day ops I’d take option two every time: less HCL to squint at, grouping lives where humans already think in accounts.
IaC should be obvious on a tired Friday, not a puzzle you cracked once in a PR review.
Clever locals have their place—like merging module outputs when something cross-account needs a flat map of VPC IDs or route table IDs:
1 | locals { |
That’s the kind of abstraction I’d keep. The rest? I’d rather duplicate a line in tfvars than maintain a grouping algorithm nobody remembers.
Questions? Leave a comment below or email: newbvirgil@gmail.com![]()
