In terraform's official site, they have an example like this (https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy):
resource "aws_iam_role_policy" "test_policy" {
name = "test_policy"
role = aws_iam_role.test_role.id
# Terraform's "jsonencode" function converts a
# Terraform expression result to valid JSON syntax.
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = [
"ec2:Describe*",
]
Effect = "Allow"
Resource = "*"
},
]
})
}
resource "aws_iam_role" "test_role" {
name = "test_role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = "sts:AssumeRole"
Effect = "Allow"
Sid = ""
Principal = {
Service = "ec2.amazonaws.com"
}
},
]
})
}
where they attach a policy to a role by setting the role id in the policy, namely:
role = aws_iam_role.test_role.id
But setting it this way didn't work for me in one of our team projects, I kept on getting errors (see details here Task role defined by Terraform not working correctly for ECS scheduled task). Eventually, I realized that I had to set it using role name like this in my policy:
role = aws_iam_role.my_role.name
But I do see instances in our other team projects where my coworkers are using role id. I wonder what are the differences between id and name in the context of terraform and when to use which.
aws_iam_role
, theid
andname
attributes are both"The name of the role"
. Doesn't seem to be a difference between the two. Personally I tend to usename
. (registry.terraform.io/providers/hashicorp/aws/latest/docs/…) – m_callens