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

Rafiq picture Rafiq · May 22, 2017 · Viewed 8.8k times · Source

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?

Answer

garnaat picture garnaat · May 22, 2017

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