Assuming the below given role , let’s see how we can multiple policies
resource "aws_iam_policy" "my_policy" {
name = "all_the_ec2"
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = ["ec2:*"]
Effect = "Allow"
Resource = "*"
}
]
})
}
resource "aws_iam_role_policy_attachment" "attachment" {
role = aws_iam_role.my_role.name
policy_arn = aws_iam_policy.my_policy.arn
}
Attaching multiple policies with for_each
If you have defined a number of aws_iam_policy
(s), you can attach all the policies you need to a role, or a user, or a group with this neat Terraform trick:
resource "aws_iam_role_policy_attachment" "attachment" {
for_each = toset([
aws_iam_policy.my_first_policy.arn,
aws_iam_policy.my_other_policy.arn,
# Works with AWS Provided policies too!
"arn:aws:iam::aws:policy/AmazonS3FullAccess"
])
role = aws_iam_role.my_role.name
policy_arn = each.value
}