简体   繁体   中英

How to attach new role permissions to iam_role in aws using python boto3?

I'm trying to attach new permissions to the existing IAM role using python boto3. I'm using the append() method to attach new permissions to the IAM role but it is not really adding permissions to the role.

Python:

import boto3
iam = boto3.client('iam',aws_access_key_id=ACCESS_KEY,aws_secret_access_key=SECRET_KEY)
rolename = ROLENAME
policyname = POLICYNAME

#Get rolepolicy 
response = iam.get_role_policy(RoleName=rolename,PolicyName=policyname)
add_permission = response['PolicyDocument']['Statement']

#Assume json_perm is the  permission that needs to be attached inside Statement block of policydocument.
json_perm = """ {'Action':'*','Resource':'','Effect':'Allow'})""" 

#Attaching new permissions to the role
add_permission.append(json_perm)
print(add_permission)

#Get response after appending
new_response = iam.get_role_policy(RoleName=rolename,PolicyName=policyname)
print(new_response)

When printing add_permission I'm able to see the new permissions got appended in the policy document. But I'm not able to see that permission in the AWS console and also after appending If I print new_response I'm not able to see the newly added permissions in the output terminal also.

Appending new permissions to the IAM-role doesn't actually do any change to the role..? How to attach new permissions to the IAM role PolicyDocument using python boto3?

Thanks.

Appending new permissions to the IAM-role doesn't actually do any change to the role..?

This does not work, because you are not actually updating the policy at AWS. You are just adding it to a python variable add_permission . This does not automatically translate to actual changes of the policy at AWS.

For that, you have to use put_role_policy call to AWS to update the policy.

You can try the following code:

#Get rolepolicy 
response = iam.get_role_policy(
    RoleName=rolename,
    PolicyName=policyname)

add_permission = response['PolicyDocument']
#print(add_permission)

#Attaching new permissions to the role
#add_permission.append(json_perm)
#print(add_permission)

# NOT a good idea to allow all actions on all resources
add_permission['Statement'].append({
                       'Action':'*',
                       'Resource':'*',
                       'Effect':'Allow',
                       'Sid': 'AllowAlll'})

response = iam.put_role_policy(
    RoleName=rolename,
    PolicyName=policyname,
    PolicyDocument=json.dumps(add_permission)
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM