Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I attach multiple pre-existing AWS managed roles to a policy?

I want to associate existing policies in AWS to a role, I am using the terraform tool

I want to associate these policies, this code is with the aws cloudformation tool:

   AWSCodeCommitFullAccess
   AWSCodeBuildAdminAccess
   AWSCodeDeployFullAccess
   AWSCodePipelineFullAccess
   AWSElasticBeanstalkFullAccess

try with the attach

data "aws_iam_policy" "attach-policy" {
  arn = ["arn:aws:iam::aws:policy/AWSCodeCommitFullAccess", "arn:aws:iam::aws:policy/AWSCodeBuildAdminAccess", "arn:aws:iam::aws:policy/AWSCodeDeployFullAccess", "arn:aws:iam::aws:policy/AWSCodePipelineFullAccess"]
}

resource "aws_iam_role_policy_attachment" "tc-role-policy-attach" {
  role = "${aws_iam_role.toolchain-role.name}"

  policy_arn = "${data.aws_iam_policy.attach-policy.arn}"
}
like image 691
Daniel Contreras Avatar asked Mar 28 '19 18:03

Daniel Contreras


People also ask

Can you attach multiple IAM roles?

When creating IAM roles, associate least privilege IAM policies that restrict access to the specific API calls the application requires. You can only attach one IAM role to an instance, but you can attach the same role to many instances.

Can I attach multiple roles to EC2 instance?

Can I attach more than 1 IAM role to an EC2 instance? You can attach only one role to ec2 instance.

How many managed policies can be applied to an entity in AWS?

You can attach up to 20 managed policies to IAM roles and users.

Can you attach multiple policies to a role?

To add permissions to an IAM identity (IAM user, group, or role), you create a policy, validate the policy, and then attach the policy to the identity. You can attach multiple policies to an identity, and each policy can contain multiple permissions.


1 Answers

You go with the right direction with terraform resource aws_iam_role_policy_attachment but need some adjustment.

AWS managed policies' ARN are exist in the system. For example, if you need attach the first managed policy to an IAM role,

resource "aws_iam_role_policy_attachment" "test-policy-AWSCodeCommitFullAccess" {
  policy_arn = "arn:aws:iam::aws:policy/AWSCodeCommitFullAccess"
  role       = "${aws_iam_role.toolchain-role.name}"
}

You can add other managed policies one by one.

If you want to do together, you can try below code

variable "managed_policies" {
  default = ["arn:aws:iam::aws:policy/AWSCodeCommitFullAccess",
    "arn:aws:iam::aws:policy/AWSCodeBuildAdminAccess",
    "arn:aws:iam::aws:policy/AWSCodeDeployFullAccess",
    "arn:aws:iam::aws:policy/AWSCodePipelineFullAccess",
  ]
}

resource "aws_iam_role_policy_attachment" "tc-role-policy-attach" {
  count      = "${length(var.managed_policies)}"
  policy_arn = "${element(var.managed_policies, count.index)}"
  role       = "${aws_iam_role.toolchain-role.name}"
}
like image 64
BMW Avatar answered Jan 03 '23 02:01

BMW