在这里找到了一个有用的线程,它帮助我获得了脚本的一部分,以获取所有角色及其附加策略的列表:
response = client.list_attached_role_policies(
RoleName='MyRoleName'
)
我正在尝试弄清楚如何进行这项工作,因此我获得了我们 AWS 账户中所有角色及其附加策略的列表。我对 Python/Boto3 还很陌生,因此非常感谢任何帮助
答案 0 :(得分:2)
你应该能够做这样的事情:
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)
分页器应该帮助处理您可能拥有比 AWS 施加的每个响应限制更多的角色/策略的情况。与编程一样,有很多不同的方法可以做到这一点,但这是一种方法。