繁体   English   中英

带有 Boto3 附加策略的所有角色列表

[英]List of all roles with attached policies with Boto3

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

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

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

你应该能够做这样的事情:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM