Rafiq
Rafiq

Reputation: 1642

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?

Upvotes: 13

Views: 19368

Answers (2)

Remotec
Remotec

Reputation: 10760

I had a similar question in regard to how to supplying 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.

Upvotes: 15

garnaat
garnaat

Reputation: 45876

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>')

Upvotes: 16

Related Questions