Reputation: 41
I am trying to create a single inline policy to attach with multiple IAM user in my terraform module.
This is my main.tf
locals {
name_prefix = var.environment
}
resource "aws_iam_user" "npdata" {
count = length(var.username)
name = element(var.username,count.index )
tags = merge({
Name = element(var.username,count.index )
},
var.default_tags,
)
}
resource "aws_iam_user_policy" "lb_ro" {
name = "test"
user = element(aws_iam_user.npdata.*.name,count.index)
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
actions = [
"s3:GetObject",
"s3:ListBucket",
"s3:PutObject",
"s3:GetObjectVersion"
]
Effect = "Allow"
resources = [
var.dev_arn,
var.prd_arn
]
},
]
})
}
but terraform plan is giving error
Error: Reference to "count" in non-counted context
on modules/iam-user/main.tf line 18, in resource "aws_iam_user_policy" "lb_ro":
18: user = element(aws_iam_user.npdata.*.name,count.index)
The "count" object can only be used in "module", "resource", and "data"
blocks, and only when the "count" argument is set.
How can I use count to provide list of IAM users to resource aws_iam_user_policy
Upvotes: 1
Views: 3046
Reputation: 201088
You're trying to use the count.index
variable here:
user = element(aws_iam_user.npdata.*.name,count.index)
But you haven't declared a count
for the aws_iam_user_policy
resource, so that variable doesn't exist.
Additionally, you can't assign a single inline policy to multiple users, so you will have to create multiple inline policy resources. So you need to add count = length(var.username)
to the aws_iam_user_policy
resource.
Upvotes: 3