Terraform: associate an aws_iam_role with an aws_iam_policy

5.1k views Asked by At

Reading through the docs and having a hard time seeing how to associate an aws_iam_role with an aws_iam_policy. Obviously there's aws_iam_role_policy, but that only allows making "inline policies" for a particular role.

Any suggestions?

3

There are 3 answers

0
Martin Atkins On BEST ANSWER

The aws_iam_policy_attachment resource allows connections to be created between IAM policies and the various other IAM objects.

For example:

resource "aws_iam_role" "foo" {
    name = "example-role"
}

resource "aws_iam_policy" "foo" {
    name = "example-policy"
    description = "An example policy"
    policy = "..."
}

resource "aws_iam_policy_attachment" "foo" {
    name = "example-attachment"
    policy_arn = "${aws_iam_policy.foo.arn}"
    roles = ["${aws_iam_role.foo.name}"]
}

Policies can also be attached to users and groups, as illustrated on the Terraform documentation page.

0
Michael Olafisoye On

What I've had to do is create a role and a policy and then attach them as shown in an answer by Martin Atkins.

resource "aws_iam_role" "context-builder-role" {
  name = "context-builder-role-${terraform.workspace}"

  assume_role_policy = <<EOF
{
     "Version": "2012-10-17",
     "Statement": [
       {
         "Action": "sts:AssumeRole",
         "Principal": {
         "Service": "lambda.amazonaws.com"
       },
         "Effect": "Allow",
         "Sid": ""
       }
     ]
}
EOF
}

resource "aws_iam_policy" "arm_cfs_sqs_queue_policy" {

  name = "starmine-inline-policy-${terraform.workspace}"

  policy = <<EOF
{
   "Version": "2012-10-17",
   "Statement": [
       {
           "Effect": "Allow",
           "Action": [
               "logs:CreateLogGroup",
               "logs:CreateLogStream",
               "logs:PutLogEvents"
           ],
           "Resource": "arn:aws:logs:*:*:*"
       },
       {
           "Action": [
               "sqs:SendMessage",
               "sqs:GetQueueUrl",
               "sqs:DeleteMessage"
           ],
           "Effect": "Allow",
           "Resource": "arn:aws:sqs:*"
       }
   ]
}
EOF
}

resource "aws_iam_role_policy_attachment" "inline-policy-attach" {
  role       = aws_iam_role.context-builder-role.name
  policy_arn = aws_iam_policy.arm_cfs_sqs_queue_policy.arn
}

You can also attach an AWS policy to a role by using the policies ARN:

resource "aws_iam_role_policy_attachment" "s3-read-only-attach" {
  role       = aws_iam_role.context-builder-role.name
  policy_arn = "arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess"
}
1
Domain On

Follow the below steps:

Step 1) Create the policy which you want to associate with the aws role.

Step 2) Create aws role as follow:

i. Set role name.

ii. Set role type according to your preference.

iii. Attach the policy which you have created in step1.

iv. Review and create the role.

Hope it helps.......