Terraform - 操作局部变量

Terraform - Manipulate local variables

我正在尝试设置一些 aws_ssoadmin_managed_policy_attachments(最终会有很多)所以理想情况下我只想能够更新一个局部变量然后使用 for_each 来完成所说的变量并在另一端产生大量资源。

我目前有如下内容:

locals {
    roles = {
        admin = {
           //managed_policy_name = toset(["AdministratorAccess", "AWSSupportAccess"])
           managed_policy_name = "AWSSupportAccess"
           perm_set_name       = "admin"
        }
       auditor = { ...
    }
}

这里面会有更多的角色。我使用下面的方法将其转换为 for_each.

更有用的东西
managed_policy_map = [for keys, managed_policy_names in local.roles : {
for managed_policy_name in managed_policy_names :
format("%s-%s", keys, managed_policy_name) => { "managed_policy_name" : managed_policy_name }
}]
perm_set_to_managed_policy_map = merge(local.managed_policy_map...)

此输出:

a = [{
    "admin-AWSSupportAccess" = {
      "managed_policy_name" = "AWSSupportAccess"
      "perm_set_name" = "admin"
    }
    "admin-admin" = {
      "managed_policy_name" = "admin"
      "perm_set_name" = "admin"
    }
    "auditor-ReadOnlyAccess" = {
      "managed_policy_name" = "ReadOnlyAccess"
      "perm_set_name" = "auditor"
    }
    "auditor-auditor" = {
      "managed_policy_name" = "auditor"
      "perm_set_name" = "auditor"
    }
    "auditor-auditor-permission-set" = {
      "managed_policy_name" = "auditor-permission-set"
      "perm_set_name" = "auditor"
   }
},]

现在,理想情况下,我想使用注释 managed_policy_name,它使用列表(或设置以避免重复)//managed_policy_name = toset(["AdministratorAccess", "AWSSupportAccess"]) 并循环遍历它以得到类似的结果。

a = [{
    "admin-AdministratorAccess" = {
      "managed_policy_name" = "AdministratorAccess"
      "perm_set_name" = "admin"
    }
    "admin-AWSSupportAccess" = {
      "managed_policy_name" = "AWSSupportAccess"
      "perm_set_name" = "admin"
    }
    "auditor-ReadOnlyAccess" = {
      "managed_policy_name" = "ReadOnlyAccess"
      "perm_set_name" = "auditor"
    } ...

这可行吗?我的假设是它会相当复杂,或者我缺少一些使它变得简单的 Terraform 函数。任何帮助将不胜感激。

你可以简化你的变量结构:

locals {
  roles = {
    admin = toset(["AdministratorAccess", "AWSSupportAccess"])
    auditor = ...
  }
}

然后简化您的 for 表达式:

managed_policy_map = [for role, managed_policy_names in local.roles : {
  for policy in managed_policy_names : "${role}-${policy}" => {
    "managed_policy_name" = policy
    "perm_set_name"       = role
  }
}]

使用 set 类型而不是 string 类型轻松实现相同的输出结构:

[
  {
    "admin-AWSSupportAccess"    = {
      "managed_policy_name" = "AWSSupportAccess"
      "perm_set_name"       = "admin"
    }
    "admin-AdministratorAccess" = {
      "managed_policy_name" = "AdministratorAccess"
      "perm_set_name"       = "admin"
    }
  },
]

我还建议根据问题中陈述的意图简化输出结构,以便于在 for_each meta-argument 中使用。