You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AWS组织中批量部署Terraform配置

批量部署Terraform配置到AWS组织多账号的方案

方案1:使用Terraform for_each 批量生成Provider和Module实例

这是最直接的方式,能彻底避免重复编写每个账号的配置,只需要维护账号列表即可:

  1. 定义账号列表变量
    在你的Terraform配置中添加变量文件(比如variables.tf):
variable "aws_account_ids" {
  type    = list(string)
  default = ["11111", "22222", "33333", "99999"] # 替换成你的所有账号ID
}

# 假设AWS组织中每个账号都有统一命名的跨账号角色,默认是OrganizationAccountAccessRole
variable "cross_account_role_name" {
  type    = string
  default = "OrganizationAccountAccessRole"
}
  1. 用for_each批量创建AWS Provider
provider "aws" {
  for_each = toset(var.aws_account_ids)
  alias    = each.value

  assume_role {
    role_arn = "arn:aws:iam::${each.value}:role/${var.cross_account_role_name}"
  }
}
  1. 用for_each批量实例化模块
module "per_account_resources" {
  for_each = toset(var.aws_account_ids)
  source   = "./modules/per-account"

  providers = {
    aws = aws[each.value]
  }

  # 如果模块需要接收账号ID作为参数,可以直接传递
  account_id = each.value
}

方案2:支持不同账号的个性化配置

如果不同账号需要不同的角色名或资源参数,可以用map类型变量存储每个账号的自定义配置:

  1. 定义账号配置map
variable "account_custom_configs" {
  type = map(object({
    cross_account_role = string
    s3_bucket_suffix   = string
    # 其他你需要的个性化参数
  }))
  default = {
    "11111" = {
      cross_account_role = "CustomOrgAccessRole"
      s3_bucket_suffix   = "prod"
    },
    "22222" = {
      cross_account_role = "OrganizationAccountAccessRole"
      s3_bucket_suffix   = "stage"
    },
    "99999" = {
      cross_account_role = "OrgReadOnlyRole"
      s3_bucket_suffix   = "dev"
    }
  }
}
  1. 批量创建Provider和模块
provider "aws" {
  for_each = var.account_custom_configs
  alias    = each.key

  assume_role {
    role_arn = "arn:aws:iam::${each.key}:role/${each.value.cross_account_role}"
  }
}

module "per_account_resources" {
  for_each = var.account_custom_configs
  source   = "./modules/per-account"

  providers = {
    aws = aws[each.key]
  }

  account_id         = each.key
  s3_bucket_suffix   = each.value.s3_bucket_suffix
}

注意事项

  • 确保执行Terraform操作的身份(比如本地CLI用户、CI/CD服务角色)拥有assume每个账号目标角色的权限
  • 当账号数量较多时,terraform plan/apply会遍历所有账号,执行时间会相应增加,可考虑分批处理或使用Terraform Cloud的并行运行能力
  • 如果需要排除部分账号,直接从变量列表/map中移除即可

内容的提问来源于stack exchange,提问作者Chandrika

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 17:17:12