Terraform yaml 配置

Terraform yaml config

我有以下 YAML 配置文件:

AWSConfig:
  conformance_pack_templates:
    - Operational_Best_Practices_test1:
       - excluded_accounts:
           -  "closed"
           -  "staging"
    - Operational_Best_Practices_test2:
        - excluded_accounts:
            -  "opened"

我想获取我的 AWS organization 中存在的所有“排除”帐户 id,其中包括列表中指定的名称。
我正在使用 data.aws_organizations_organization.org.accounts 获取 AWS organization.
下的所有帐户详细信息 data source 输出是:

  ([{
    "arn" = "arn:aws:organizations::example1:account/f-432145321/example"
    "email" = "test@example.com"
    "id" = "543632464532"
    "name" = "closed"
    "status" = "SUSPENDED"
  },
  {
    "arn" = "arn:aws:organizations::example2:account/f-43214431/example"
    "email" = "test1@example.com"
    "id" = "45321534214"
    "name" = "closed"
    "status" = "SUSPENDED"
  },
])

我需要过滤列表中指定名称的所有帐户,并获得以下对象列表格式输出:

[ 
  { template = Operational_Best_Practices_test1, 
    excluded_accounts = [ 543632464532, 45321534214, 54325413421 ]},
  { template = Operational_Best_Practices_test2, 
    excluded_accounts = [ 65465554365, 654365436543 ]}
]

您可以使用 for with a condition and the contains 函数来实现此目的。

鉴于:

variable "accounts" {
  default = [{
      "arn" = "arn:aws:organizations::example1:account/f-432145321/example"
      "email" = "test@example.com"
      "id" = "543632464532"
      "name" = "closed"
      "status" = "SUSPENDED"
    },
    {
      "arn" = "arn:aws:organizations::example2:account/f-43214431/example"
      "email" = "test1@example.com"
      "id" = "45321534214"
      "name" = "closed"
      "status" = "SUSPENDED"
    },
    {
      "arn" = "arn:aws:organizations::example3:account/f-43214431/example"
      "email" = "test1@example.com"
      "id" = "45321534215"
      "name" = "opened"
      "status" = "OPENED"
    },
  ]
}

output "test" {
  value = {
    for rules in "${yamldecode(file("aws_config.yml")).AWSConfig.conformance_pack_templates}" :
      keys(rules).0 => [
        for account in var.accounts : 
          account.id
        if contains(rules[keys(rules).0].0.excluded_accounts, account.name)
      ]
  }
}

这产生:

test = {
  "Operational_Best_Practices_test1" = [
    "543632464532",
    "45321534214",
  ]
  "Operational_Best_Practices_test2" = [
    "45321534215",
  ]
}

这就是说,如果您是 YAML 的所有者并且您可以稍微更改它的结构,将您的一些列表转换为字典,如下所示:

AWSConfig:
  conformance_pack_templates:
    Operational_Best_Practices_test1:
      excluded_accounts:
        -  "closed"
        -  "staging"
    Operational_Best_Practices_test2:
      excluded_accounts:
        -  "opened"

您可以通过删除 keys 函数的需要来简化 terraform 代码:​​

output "test" {
  value = {
    for label, rule in "${yamldecode(file("aws_config.yml")).AWSConfig.conformance_pack_templates}" :
      label => [
        for account in var.accounts : 
          account.id
        if contains(rule.excluded_accounts, account.name)
      ]
  }
}