【问题标题】:loop over aws provider to create ressources in every aws account遍历 aws 提供程序以在每个 aws 帐户中创建资源
【发布时间】:2021-08-12 22:49:08
【问题描述】:

我在 Terraform 中有一个名为 users 的对象列表,结构如下:

variable "accounts" {
  type = list(object({
    id       = string #used in assume_role
    email   = string
    is_enabled = bool
  }))
}

我现在想要实现的是在每个 AWS 账户中创建一个简单的 S3 存储桶(如果 is_enabled 为真)。我可以为单个帐户执行此操作,但我不确定是否有办法遍历提供程序?

单个帐户的代码 - main.tf

provider "aws" {
  alias = "new_account"
  region = "eu-west-3"

  assume_role {
    role_arn     = "arn:aws:iam::${aws_organizations_account.this.id}:role/OrganizationAccountAccessRole"
    session_name = "new_account_creation"
  }
}

resource "aws_s3_bucket" "bucket" {
  provider = aws.new_account

  bucket = "new-account-bucket-${aws_organizations_account.this.id}"
  acl    = "private"
}  

【问题讨论】:

  • 您可以改为将提供程序和存储桶放入文件夹/模块中,然后遍历该模块。模块支持 for_each / count。

标签: terraform


【解决方案1】:

您需要为要使用的每个 aws 帐户定义一个提供商:

  1. 创建一个模块(一个目录),您的存储桶配置所在的位置:
    ├── main.tf
    └── module
        └── bucket.tf
  1. bucket.tf 应该包含资源定义:resource "aws_s3_bucket" "bucket" {...}
  2. main.tf 中,定义多个 aws 提供程序并使用每个提供程序调用模块:
provider "aws" {
  alias  = "account1"
  region = "eu-west-1"
  ...
}
provider "aws" {
  alias  = "account2"
  region = "us-west-1"
  ...
}

module "my_module" {
  source = "./module"
  providers = {
    aws.account1 = aws.account1
    aws.account2 = aws.account2
  }
}

我想你也可以通过创建一个包含提供程序的变量来获得幻想,并将其传递给模块调用(你也可以使用列表中的过滤器来考虑is_enabled 标志)

有关提供商的更多详细信息:https://www.terraform.io/docs/language/modules/develop/providers.html

【讨论】:

  • 感谢您的完整回答。我的问题是我所有的 aws 帐户都存储在我的列表中,我也不知道帐户的确切数量
【解决方案2】:

在这里找到我要找的东西:https://github.com/hashicorp/terraform/issues/19932

谢谢布莱恩·卡拉法

## Just some data... a list(map())
locals {
  aws_accounts = [
    { "aws_account_id": "123456789012", "foo_value": "foo",    "bar_value": "bar"    },
    { "aws_account_id": "987654321098", "foo_value": "foofoo", "bar_value": "barbar" },
    ]
}
## Here's the proposed magic... `provider.for_each`
provider "aws" {
  for_each = local.aws_accounts
  alias = each.value.aws_account_id
  assume_role {
    role_arn    = "arn:aws:iam::${each.value.aws_account_id}:role/TerraformAccessRole"
  }
}
## Modules reference the provider dynamically using `each.value.aws_account_id`
module "foo" {
  source = "./foo"
  for_each = local.aws_accounts
  providers = {
    aws = "aws.${each.value.aws_account_id}"
  }
  foo = each.value.foo_value
}
module "bar" {
  source = "./bar"
  for_each = local.aws_accounts
  providers = {
    aws = "aws.${each.value.aws_account_id}"
  }
  bar = each.value.bar_value
}

【讨论】:

    猜你喜欢
    • 2022-11-11
    • 2020-05-11
    • 1970-01-01
    • 2021-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-11
    • 2020-01-21
    相关资源
    最近更新 更多