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

Viewed 14490

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?

2 Answers

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.

Related