Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create AWS IAM role attaching managed policy only using Boto3

I am trying to use Boto3 to create a new instance role that will attach a managed policy only.

I have the following:

Policy Name: my_instance_policy

Policy ARN: arn:aws:iam::123456789012:policy/my_test_policy

I want to create the role called 'my_instance_role' attaching attaching the above policy only.

Boto3 client has the create_role() function like below:

import boto3
client = boto3.client('iam')
response = client.create_role(
    Path='string',
    RoleName='string',
    AssumeRolePolicyDocument='string',
    Description='string'
)

Here, I do not see an option to use the policy ARN or name. My understanding is that AssumeRolePolicyDocument variable needs the JSON formatted policy document converted in to text.

Is it possible the way I am looking for?

like image 684
Rafiq Avatar asked May 22 '17 20:05

Rafiq


People also ask

How do you create a IAM policy on Boto3?

To create an IAM policy, you need to use the create_policy() method of the Boto3 IAM client. The returned response object will contain additional information about the created policy.

How do you attach an IAM role?

To attach an IAM role to an instance Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/ . In the navigation pane, choose Instances. Select the instance, choose Actions, Security, Modify IAM role. Select the IAM role to attach to your instance, and choose Save.

How many policies can you attach to an IAM role?

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


2 Answers

You would have to create the role (as you are doing above) and then separately attach the managed policy to the role like this:

response = client.attach_role_policy(
    RoleName='MyRole', PolicyArn='<arn of managed policy>')
like image 155
garnaat Avatar answered Sep 25 '22 01:09

garnaat


I had a similar question in regard to how to supply the AssumeRolePolicyDocument when creating an IAM role with Boto3.

I used the following code...

assume_role_policy_document = json.dumps({
    "Version": "2012-10-17",
    "Statement": [
        {
        "Effect": "Allow",
        "Principal": {
            "Service": "greengrass.amazonaws.com"
        },
        "Action": "sts:AssumeRole"
        }
    ]
})

create_role_response = self._iam.create_role(
    RoleName = "my-role-name,
    AssumeRolePolicyDocument = assume_role_policy_document
)

Note that the AssumeRolePolicyDocument is about defining the trust relationship and not the actual permissions of the role you are creating.

like image 24
Remotec Avatar answered Sep 23 '22 01:09

Remotec