CodexBloom - Programming Q&A Platform

Terraform: how to to Create Multiple IAM Roles with Different Policies in AWS Using Count

👀 Views: 1818 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-11
terraform aws iam hcl

I'm having a hard time understanding I've been banging my head against this for hours... I'm trying to create multiple IAM roles in AWS using Terraform with varying policies, but I'm running into issues when using the `count` argument. My goal is to create three roles, each with different permissions based on their names. Here's what I've attempted: ```hcl variable "roles" { type = list(string) default = ["admin", "developer", "auditor"] } resource "aws_iam_role" "role" { count = length(var.roles) name = var.roles[count.index] assume_role_policy = jsonencode({ Version = "2012-10-17" Statement = [ { Action = "sts:AssumeRole" Principal = { Service = "ec2.amazonaws.com" } Effect = "Allow" Sid = "" } ] }) } resource "aws_iam_policy" "policy" { count = length(var.roles) name = "${var.roles[count.index]}-policy" policy = jsonencode({ Version = "2012-10-17" Statement = [ { Effect = "Allow" Action = ["s3:ListBucket"], Resource = "*" } ] }) } resource "aws_iam_role_policy_attachment" "attachment" { count = length(var.roles) policy_arn = aws_iam_policy.policy[count.index].arn role = aws_iam_role.role[count.index].name } ``` When I run `terraform apply`, I'm getting the following behavior: ``` behavior: Invalid template interpolation value on main.tf line 20, in resource "aws_iam_policy" "policy": 20: name = "${var.roles[count.index]}-policy" want to include the count.index variable in the interpolation in this context. ``` I've ensured that the role names in my variable are unique, but it seems that the `count.index` reference is causing an scenario in the policy resource definition. I've tried moving the `count` to the role resource only, but that didn't seem to resolve the scenario. Can anyone provide insights on how to correctly create multiple IAM roles with unique policies using the `count` parameter? Any help would be appreciated! I'd love to hear your thoughts on this.