![](/img/trans.png)
[英]How do you dynamically create an AWS IAM policy document with a variable number of resource blocks using terraform?
[英]terraform: is there a way to create iam policy statements dynamically?
Terraform 版本: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
块,如下所述: https://www.terraform.io/docs/configuration/expressions.ZFC35FDC70D5FC69D269883A822C7A5E3
在你的情况下,这可能是
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"
}
}
}
}
不过,我认为“动态”仅在 TF 0.12 之后才可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.