How to attach multiple IAM policies to IAM roles using Terraform?

Pranshu Verma picture Pranshu Verma · Aug 3, 2017 · Viewed 23.6k times · Source

I want to attach multiple IAM Policy ARNs to a single IAM Role.

One method is to create a new policy with privileges of all the policies (multiple policies).

But in AWS, we have some predefined IAM policies like AmazonEC2FullAccess, AmazomS3FullAccess, etc. I want to use a combination of these for my role.

I could not find a way to do so in the Terraform documentation.

As per documentation we can use aws_iam_role_policy_attachment to attach a policy to a role, but not multiple policies to a role as this is available via AWS console.

Please let me know if there is a method to do the same or is it still a feature to be added.

The Terraform version I use is v0.9.5

Answer

Pranshu Verma picture Pranshu Verma · Aug 3, 2017

Thanks Krishna Kumar R for the hint.

A little more polished answer I reached from your answer.

# Define policy ARNs as list
variable "iam_policy_arn" {
  description = "IAM Policy to be attached to role"
  type = "list"
}

# Then parse through the list using count
resource "aws_iam_role_policy_attachment" "role-policy-attachment" {
  role       = "${var.iam_role_name}"
  count      = "${length(var.iam_policy_arn)}"
  policy_arn = "${var.iam_policy_arn[count.index]}"
}

And finally the list of policies should be specified in *.tfvars file or in command line using -var, for example:

iam_policy_arn = [ "arn:aws:iam::aws:policy/AmazonEC2FullAccess", "arn:aws:iam::aws:policy/AmazonS3FullAccess"]