带有 Boto3 附加策略的所有角色的列表 [英] List of all roles with attached policies with Boto3

查看:23
本文介绍了带有 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'
)

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

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

推荐答案

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

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)

分页器应该帮助处理您可能拥有比 AWS 施加的每个响应限制更多的角色/策略的情况.与编程一样,有很多不同的方法可以做到这一点,但这是一种方法.

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.

这篇关于带有 Boto3 附加策略的所有角色的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆