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?
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.
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.
IAM groups You can attach up to 20 managed policies to IAM roles and users.
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>')
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With