Found a useful thread here that helped me get part of a script to get a list of all roles and its attached policies:
JavaScript
x
4
1
response = client.list_attached_role_policies(
2
RoleName='MyRoleName'
3
)
4
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:
JavaScript
1
33
33
1
import boto3
2
3
from typing import Dict, List
4
5
client = boto3.client('iam')
6
7
def get_role_names() -> List[str]:
8
""" Retrieve a list of role names by paginating over list_roles() calls """
9
roles = []
10
role_paginator = client.get_paginator('list_roles')
11
for response in role_paginator.paginate():
12
response_role_names = [r.get('RoleName') for r in response['Roles']]
13
roles.extend(response_role_names)
14
return roles
15
16
def get_policies_for_roles(role_names: List[str]) -> Dict[str, List[Dict[str, str]]]:
17
""" Create a mapping of role names and any policies they have attached to them by
18
paginating over list_attached_role_policies() calls for each role name.
19
Attached policies will include policy name and ARN.
20
"""
21
policy_map = {}
22
policy_paginator = client.get_paginator('list_attached_role_policies')
23
for name in role_names:
24
role_policies = []
25
for response in policy_paginator.paginate(RoleName=name):
26
role_policies.extend(response.get('AttachedPolicies'))
27
policy_map.update({name: role_policies})
28
return policy_map
29
30
role_names = get_role_names()
31
attached_role_policies = get_policies_for_roles(role_names)
32
33
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.