如何在Terraform模块中用for_each遍历多AWS账户(中心辐射模型)
基于Hub and Spoke模型实现多账户Route53 VPC关联授权的Terraform方案
核心需求回顾
在Hub and Spoke架构中,通过Terraform实现**单个主账户(Hub)对多个子账户(Spoke)**的Route53私有域进行VPC关联授权,同时完成子账户侧的VPC与Route53域绑定。
1. 变量定义(variables.tf)
先明确app_accounts变量的结构,添加类型约束确保输入合法:
variable "app_accounts" { type = list(object({ account_id = string # 子账户ID app_vpc_id = string # 子账户中需关联的VPC ID region = string # 子账户VPC所在区域 aws_profile = string # 本地AWS配置文件中对应的子账户配置名 })) description = "子账户及关联VPC的配置列表" } variable "master_aws_profile" { type = string description = "主账户的AWS配置文件名" } variable "route53_zone_id" { type = string description = "主账户中需要授权的Route53私有域ID" }
2. 多账户Provider配置(provider.tf)
- 主账户Provider:单独配置,用于执行授权操作
- 子账户Provider:通过
for_each遍历所有子账户,每个子账户对应唯一的Provider实例(alias必须唯一)
# 主账户Provider(Hub) provider "aws" { alias = "master" profile = var.master_aws_profile region = "us-east-1" # 主账户区域,Route53为全局服务,可按需调整 } # 子账户Provider(Spoke):遍历所有子账户配置 provider "aws" { for_each = { for acc in var.app_accounts : acc.aws_profile => acc } alias = each.key # 用子账户的profile名作为唯一别名 profile = each.value.aws_profile region = each.value.region }
3. 主账户授权与子账户关联资源(main.tf)
3.1 主账户侧:授权子账户VPC关联Route53域
使用for_each遍历所有子账户,为每个子账户的VPC创建授权记录:
resource "aws_route53_vpc_association_authorization" "master" { for_each = { for acc in var.app_accounts : "${acc.account_id}-${acc.app_vpc_id}" => acc } provider = aws.master zone_id = var.route53_zone_id vpc { vpc_id = each.value.app_vpc_id vpc_region = each.value.region } }
3.2 子账户侧:绑定VPC到Route53域
同样通过for_each遍历,每个子账户使用对应的Provider执行绑定操作:
resource "aws_route53_zone_association" "child" { for_each = { for acc in var.app_accounts : "${acc.account_id}-${acc.app_vpc_id}" => acc } provider = aws[each.value.aws_profile] # 引用对应子账户的Provider实例 zone_id = var.route53_zone_id vpc_id = each.value.app_vpc_id }
4. 模块调用示例(module.tf)
按变量结构传入子账户配置:
module "route53_hub_spoke_association" { source = "./modules/route53-hub-spoke" master_aws_profile = "master-account-profile" route53_zone_id = "Z0XXXXXXXXX12345" app_accounts = [ { account_id = "53xxxx08" app_vpc_id = "vpc-0fxxxxxfec8" region = "us-east-1" aws_profile = "child1" }, { account_id = "53xxxx09" app_vpc_id = "vpc-0axxxxxfed7" region = "us-west-2" aws_profile = "child2" } ] }
关键说明
- Provider唯一性:子账户Provider的
alias必须唯一,这里用子账户的aws_profile作为别名,避免冲突 - 资源键唯一性:
for_each的键需确保全局唯一,这里用${account_id}-${vpc_id}组合,避免重复 - 权限前置:需确保主账户能通过指定的
aws_profile访问子账户,子账户侧需配置对应IAM权限(允许route53:AssociateVPCWithHostedZone操作) - 区域一致性:Route53私有域的区域需与VPC区域匹配,或在授权时明确指定
vpc_region
内容的提问来源于stack exchange,提问作者EDU_EVER
相关产品推荐
相关产品推荐

