0
votes

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.

1
according to the documentation for the aws_iam_role, the id and name attributes are both "The name of the role". Doesn't seem to be a difference between the two. Personally I tend to use name. (registry.terraform.io/providers/hashicorp/aws/latest/docs/…)m_callens

1 Answers

1
votes

As already pointed out, there is no difference between id and name. You can check it by simply outputting your role:

output "test" {
  value = aws_iam_role.test_role
}

which shows that both id and name are set to test_role:

test = {
  "arn" = "arn:aws:iam::xxxxxx:role/test_role"
  "assume_role_policy" = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"\",\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"ec2.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}"
  "create_date" = "2021-02-14T01:25:48Z"
  "description" = ""
  "force_detach_policies" = false
  "id" = "test_role"
  "max_session_duration" = 3600
  "name" = "test_role"
  "name_prefix" = tostring(null)
  "path" = "/"
  "permissions_boundary" = tostring(null)
  "tags" = tomap({})
  "unique_id" = "AROASZHPM3IXXHCEBQ6OD"
}