Skip to content
Advertisement

List of all roles with attached policies with Boto3

Found a useful thread here that helped me get part of a script to get a list of all roles and its attached policies:

response = client.list_attached_role_policies(
  RoleName='MyRoleName'
)

I am trying to figure out how to make this work so I get a list of all the roles in our AWS account and their attached policies. I am pretty new to Python/Boto3 so any help would be greatly appreciated

Advertisement

Answer

You should be able to do something like this:

import boto3

from typing import Dict, List

client = boto3.client('iam')

def get_role_names() -> List[str]:
    """ Retrieve a list of role names by paginating over list_roles() calls """
    roles = []
    role_paginator = client.get_paginator('list_roles')
    for response in role_paginator.paginate():
        response_role_names = [r.get('RoleName') for r in response['Roles']]
        roles.extend(response_role_names)
    return roles

def get_policies_for_roles(role_names: List[str]) -> Dict[str, List[Dict[str, str]]]:
    """ Create a mapping of role names and any policies they have attached to them by 
        paginating over list_attached_role_policies() calls for each role name. 
        Attached policies will include policy name and ARN.
    """
    policy_map = {}
    policy_paginator = client.get_paginator('list_attached_role_policies')
    for name in role_names:
        role_policies = []
        for response in policy_paginator.paginate(RoleName=name):
            role_policies.extend(response.get('AttachedPolicies'))
        policy_map.update({name: role_policies})
    return policy_map

role_names = get_role_names()
attached_role_policies = get_policies_for_roles(role_names)

The paginators should help handle cases where you might have more roles / policies than the per-response limit imposed by AWS. As usual with programming there are a lot of different ways to do this, but this is one approach.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement