【问题标题】:List of all roles with attached policies with Boto3带有 Boto3 附加策略的所有角色列表
【发布时间】:2021-02-09 21:37:48
【问题描述】:

在这里找到了一个有用的线程,它帮助我获取脚本的一部分以获取所有角色及其附加策略的列表:

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

我正在尝试弄清楚如何完成这项工作,因此我获得了 AWS 账户中所有角色的列表及其附加策略。我对 Python/Boto3 还很陌生,因此将不胜感激任何帮助

【问题讨论】:

    标签: python amazon-web-services boto3


    【解决方案1】:

    你应该可以做这样的事情:

    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 施加的每个响应限制的情况。与编程一样,有很多不同的方法可以做到这一点,但这是一种方法。

    【讨论】:

    • 太棒了,谢谢。有没有办法我应该做打印功能?我运行它,它返回空白。
    • @Lombahdo - 你应该可以在最后做 print(attached_role_policies) 。如果你想要更漂亮的输出,你可以导入 json,然后 json.dumps(attached_role_policies, indent=2, sort_keys=True)
    • 非常感谢您帮助一个新人。是的,我确实使用了该打印功能,并会看看我是否可以让它看起来正确。非常感谢。
    • @Lombahdo 如果答案有帮助,最好接受它。
    猜你喜欢
    • 1970-01-01
    • 2017-05-17
    • 2020-11-29
    • 1970-01-01
    • 2017-10-22
    • 2020-10-31
    • 1970-01-01
    • 2019-10-10
    • 1970-01-01
    相关资源
    最近更新 更多