Terraform: correct way to attach AWS managed policies to a role?

Viewed 60082

I want to attach one of the pre-existing AWS managed roles to a policy, here's my current code:

resource "aws_iam_role_policy_attachment" "sto-readonly-role-policy-attach" {
  role       = "${aws_iam_role.sto-test-role.name}"
  policy_arn = "arn:aws:iam::aws:policy/ReadOnlyAccess"
}

Is there a better way to model the managed policy and then reference it instead of hardcoding the ARN? It just seems like whenever I hardcode ARNs / paths or other stuff like this, I usually find out later there was a better way.

Is there something already existing in Terraform that models managed policies? Or is hardcoding the ARN the "right" way to do it?

3 Answers

I got a similar situation, and I don't want to use the arn in my terraform script for two reasons,

  • If we do it on the Web console, we don't really look at the arn, we search the role name, then attach it to the role
  • The arn is not easy to remember, looks like is not for human

I would rather use the policy name, but not the arn, here is my example

# Get the policy by name
data "aws_iam_policy" "required-policy" {
  name = "AmazonS3FullAccess"
}

# Create the role
resource "aws_iam_role" "system-role" {
  name = "data-stream-system-role"
  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Action = "sts:AssumeRole"
        Effect = "Allow"
        Sid    = ""
        Principal = {
          Service = "ec2.amazonaws.com"
        }
      },
    ]
  })
}


# Attach the policy to the role
resource "aws_iam_role_policy_attachment" "attach-s3" {
  role       = aws_iam_role.system-role.name
  policy_arn = data.aws_iam_policy.required-policy.arn
}
Related