【问题标题】:Terraform How To Interpolate Name Of Data Resource In Module CallTerraform如何在模块调用中插入数据资源的名称
【发布时间】:2021-12-19 04:36:31
【问题描述】:

我的目标是使用 for_each 调用策略模块,以便为每个策略名称输入选择正确的 policy_document。有没有办法做到这一点?输入是带有键 example-service 的地图的示例

data "aws_iam_policy_document" "policy-example-service" {
  statement {
    sid       = "AllowListBuckets"
    actions   = ["s3:ListAllMyBuckets"]
    resources = ["*"]
  }
}

module "policy_example" {
  source = "../modules/aws-iam-policy"

  for_each = var.example_policies_mapped_to_roles
  name        = "example-${each.key}"
  path        = "/"

  policy = "${data.aws_iam_policy_document.policy-${each.key}.json}" //so here "policy-example-service" would be filled in

}

这将允许我使用许多不同的 policy_documents 定义一个模块调用。

【问题讨论】:

  • 看起来像这样--example_policies_mapped_to_roles = { example-service-policy = ["example-service-A"] }。所以我的想法的关键是example-service-policy,最后我会在地图中有一堆其他的键
  • 哦,哎呀——我回复的评论消失了。不过,我会留下来澄清一下。
  • 地图的想法很有效。从管理员的角度来看,我认为这很好,但如果管理员向用户提供模块,这对用户来说不是很友好。 “note不要忘记为您创建的每个策略添加一个新条目到地图中”那种人们会忘记的自述文件

标签: terraform terragrunt


【解决方案1】:

很遗憾,您不能这样做。 TF 不支持动态引用data.aws_iam_policy_document.policy-${each.key}.json 形式的资源。

解决此问题的方法是在您的aws_iam_policy_document.policy-example-service 中使用for_each

data "aws_iam_policy_document" "policy-example-service" {
 
  for_each = var.example_policies_mapped_to_roles

  # all this must be parameterized based on `each.key` values
  # for example with dynamic blocks
  statement {
    sid       = "AllowListBuckets"
    actions   = ["s3:ListAllMyBuckets"]
    resources = ["*"]
  }
}

那么,你可以这样做:

policy = data.aws_iam_policy_document.policy[each.key].json

另一种方法是将您的 IAM 策略保存在 json 文件中,然后根据需要加载文件。

【讨论】:

  • 啊,好吧,这令人失望。我尝试了类似于您在此处显示的内容,但问题是我希望拥有许多具有不同权限的不同策略文档,在这种情况下,它将为地图中的每个条目创建相同的策略。即目标是地图中的每个条目都对应于其自己的特定权限(策略)
  • @Howard_Roark 您可以将它们保存在文件或变量映射中。您还可以为所有这些策略创建一个专用模块。
  • 好的,谢谢你的想法。我的团队在政策文件策略上很重要,而不是 json 文件,所以我会考虑你的地图或专用模块的想法
猜你喜欢
  • 2018-01-28
  • 1970-01-01
  • 2018-03-03
  • 2019-01-23
  • 2021-09-12
  • 1970-01-01
  • 2021-07-09
  • 2018-12-29
  • 1970-01-01
相关资源
最近更新 更多