Terraform 数据块仅当它是 dev env

Terraform data block only if it is dev env

我正在尝试获取 IAM 组中的用户列表。该组仅存在于开发帐户中,不存在于产品中

# lookup for user accounts in Developers group only if its dev env
data "aws_iam_group" "developers" {
  count  = var.profile == "dev" ? 1 : 0
  group_name = "Developers"
}

当我有以下

locals = {
    mapdevelopers  =  [
      for index, x in data.aws_iam_group.developers[count.index].users : {
        username = x.user_name
        userarn  = x.arn
        groups   = ["system:masters"]
      }
    ] 
}

我遇到错误

│ The "count" object can only be used in "module", "resource", and "data"
│ blocks, and only when the "count" argument is set.

所以,我尝试了没有 count.index 的当地人,比如

locals = {
    mapdevelopers  =  [
      for index, x in data.aws_iam_group.developers.users : {
        username = x.user_name
        userarn  = x.arn
        groups   = ["system:masters"]
      }
    ] 
  }

现在我收到一个错误

│ Because data.aws_iam_group.developers has "count" set, its attributes must
│ be accessed on specific instances.
│ 
│ For example, to correlate with indices of a referring resource, use:
│     data.aws_iam_group.developers[count.index]

如何获取mapdevelopers局部变量?

只需将此 data.aws_iam_group.developers[count.index].users 更新为此 data.aws_iam_group.developers[0].users

由于您将 count 用于 aws_iam_group,这会将此资源转换为资源数组。如果你想迭代它并访问某些项目,你会想要使用 splat。此外,在您的情况下,您需要 flatten users 属性 以获得正确的值:

locals {
  mapdevelopers = [
    for index, x in flatten(data.aws_iam_group.developers[*].users) : {
      username = x.user_name
      userarn  = x.arn
      groups   = ["system:masters"]
    }
  ]
}

输出将类似于:

mapdevelopers = [
  {
    "groups" = [
      "system:masters",
    ]
    "userarn" = "arn:aws:iam::069700690111:user/random-user"
    "username" = "random-username"
  },
]

即使 count = var.profile == "dev" ? 1 : 0 的计算结果为 0,这仍然有效。