terraform:有没有办法动态创建 iam 策略语句?

terraform: is there a way to create iam policy statements dynamically?

地形版本:0.11

我是 运行 多个 eks 集群,并尝试按照此文档在所有集群中启用基于 IAM 角色的服务帐户: https://www.terraform.io/docs/providers/aws/r/eks_cluster.html#enabling-iam-roles-for-service-accounts

当我在策略语句中对集群名称进行硬编码并创建多个语句时,这会起作用

data "aws_iam_policy_document" "example_assume_role_policy" {

# for cluster 1

  statement {
    actions = ["sts:AssumeRoleWithWebIdentity"]
    effect  = "Allow"

    condition {
      test     = "StringEquals"
      variable = "${replace(aws_iam_openid_connect_provider.example1.url, "https://", "")}:sub"
      values   = ["system:serviceaccount:kube-system:aws-node"]
    }

    principals {
      identifiers = ["${aws_iam_openid_connect_provider.example1.arn}"]
      type        = "Federated"
    }
  }
}

因为我有多个集群,所以我希望能够动态生成语句 所以我做了以下更改:

我创建了一个 count 变量并更改了主体和条件中的值

count = "${length(var.my_eks_cluster)}" 

    condition {
      test     = "StringEquals"
      variable = "${replace(element(aws_iam_openid_connect_provider.*.url, count.index), "https://", "")}:sub"
      values   = ["system:serviceaccount:kube-system:aws-node"]
    }

    principals {
      identifiers = ["${element(aws_iam_openid_connect_provider.*.url, count.index)}"]
      type        = "Federated"
    }

Terraform 现在能够找到集群,但也会生成多个策略。 这是行不通的,因为在下面的语法中,assume_role_policy 不采用列表

resource "aws_iam_role" "example" {
  assume_role_policy = "${data.aws_iam_policy_document.example_assume_role_policy.*.json}"
  name               = "example"
}

我似乎不需要创建多个策略,而是需要在一个策略中生成多个语句(这样我就可以添加到一个 iam_role)。有没有人做过类似的事情?谢谢。

您只需要一项政策,因此您不应在政策中使用 count 参数。 你想要的是多个语句,像这样

data "aws_iam_policy_document" "example" {
  statement {
    # ...
  }
  statement {
    # ...
  }
}

现在您可以直接对其进行硬编码(也许这将是测试它是否有效的良好开端)。如果你想从一个变量动态生成这个,你需要一个 dynamic-block,如下所述:https://www.terraform.io/docs/configuration/expressions.html

在你的情况下可能是

data "aws_iam_policy_document" "example" {
  dynamic "statement" {
    for_each = aws_iam_openid_connect_provider

    content {
      actions = ["sts:AssumeRoleWithWebIdentity"]
      effect  = "Allow"

      condition {
        test     = "StringEquals"
        variable = "${replace(statement.value.url, "https://", "")}:sub"
          values   = ["system:serviceaccount:kube-system:aws-node"]
      }

      principals {
        identifiers = ["${statement.value.arn}"]
        type        = "Federated"
      }      
    }
  }
}

我认为 "dynamic" 仅在 TF 0.12 之后可用。