Reputation: 561
I have trying to attach one Iam policy to with multiple existing Iam Role , role already is there so used data , and inside the variable mention all existing Iam role names using with list(string),
and the main file added role as a data and another new resource for attachment ,
I have listed my code below, its getting error like invalid expression value : a number is require
I think I am not used correctly for resource attachment at correct manner, because all role name it should be taken from variable as list(string) one by one . Can one help me to correct this issue, Thanks.
vars.tf
variable "aws_iam_roles" {
type = list(string)
default = ["role1", "role2", "role3"]
}
main.tf
data "aws_iam_roles" "role-policy-attachment" {
count = "length(var.aws_iam_roles)"
role = "var.aws_iam_roles[count.index]"
policy_arn = aws_iam_policy.policy.arn
}
resource "aws_iam_role_policy_attachment" "data-role" {
role = data.aws_iam_role.custom.id
policy_arn = aws_iam_policy.policy.arn
}
Upvotes: 1
Views: 2749
Reputation: 28739
There are multiple issues here which can all be solved with the following:
data "aws_iam_role" "role-policy-attachment" {
for_each = toset(var.aws_iam_roles)
name = each.value
}
resource "aws_iam_role_policy_attachment" "data-role" {
for_each = data.aws_iam_role.role-policy-attachment
role = each.value.name
policy_arn = aws_iam_policy.policy.arn
}
Upvotes: 1
Reputation: 1357
The length function should not be put in quotes. This should fix the issue with count.
data "aws_iam_roles" "role-policy-attachment" {
count = length(var.aws_iam_roles)
role = "var.aws_iam_roles[count.index]"
policy_arn = aws_iam_policy.policy.arn
}
However, you also need to use count or for loop for aws_iam_role_policy_attachment. Because each role requires a separate attachment to be made.
Upvotes: 0