Boto3: Error When Attaching a Managed Policy to an IAM Role

Created on 20 Nov 2015  路  2Comments  路  Source: boto/boto3

I'm trying to create a simple python script using boto3 to create a role and then attach a managed policy to that role. The script I created will create the role, but it fails to associate the managed policy to the role. I copy and pasted the exact syntax for associating a policy to a role and it still fails. I have pasted the output of my script running in python interactive shell. Please let me know if you need anything else.

Error:

AttributeError: 'iam.ServiceResource' object has no attribute 'attach_role_policy'

Python Shell Output
>>> client = boto3.resource('iam')
>>> 
>>> response_create_role = client.create_role(
...   RoleName='MySampleRole', 
...   AssumeRolePolicyDocument='{ "Version": "2012-10-17", "Statement": [ { "Sid": "", "Effect": "Allow", "Principal": { "Service": "ec2.amazonaws.com" }, "Action": "sts:AssumeRole" } ]}'
... )
>>> 
>>> print response_create_role
iam.Role(name='MySampleRole')
>>> response_attach_role_policy = client.attach_role_policy(
...     RoleName='MySampleRole',
...     PolicyArn='arn:aws:iam::aws:policy/IAMFullAccess'
... )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'iam.ServiceResource' object has no attribute 'attach_role_policy'
question

Most helpful comment

The attach_role_policy is available on a client, not a resource. If you change the first line to:

client = boto3.client('iam')

then this code snippet will work.

All 2 comments

The attach_role_policy is available on a client, not a resource. If you change the first line to:

client = boto3.client('iam')

then this code snippet will work.

Based on this guide (http://boto3.readthedocs.io/en/latest/reference/services/iam.html#IAM.Role.attach_policy) it looks like you can actually use something called attach_policy with resources, in place of the client attach_role_policy version. Just do:

import boto3

iam = boto3.resource('iam')
role = iam.Role('name')
response = role.attach_policy(
    PolicyArn='string'
)
Was this page helpful?
0 / 5 - 0 ratings