Navi
Navi

Reputation: 117

How to list AWS managed policy attached to a role using boto3

I am trying to list policies attached to a role using boto3. I am using list_role_policies or get_role_policy for that. But it only lists inline policies attached to the role and doesn't list AWS managed policies attached to it. is there any way we can list all the policies attached to a role (inline as well as AWS managed) using boto3.

Below is a code snippet using list_role_policies

import boto3
from botocore.exceptions import ClientError

ec2=boto3.client('ec2',region_name='ca-central-1')
iam=boto3.client('iam')


response = iam.list_role_policies(RoleName='rolename')
print(response)

Thanks

Upvotes: 2

Views: 1463

Answers (2)

Michael
Michael

Reputation: 99

I had to do the same thing today. Here's some code to make it easy:

import boto3
client=boto3.client('iam')

def list_attached_policies(role_name):
    params = {
        "RoleName": role_name 
    }      
    while True:
        policies = client.list_attached_role_policies(**params)
        for p in policies["AttachedPolicies"]:
            print(p)
        if not policies["IsTruncated"]:
            break
        else:
            params["Marker"] = policies["Marker"]

Upvotes: 1

Sathya_puttaiah
Sathya_puttaiah

Reputation: 11

I dont think we have anything as such. Need to use both 'list_role_policies'('to list inline policies') and 'list_attached_role_policies'(to list managed policies)

Upvotes: 1

Related Questions