使用 boto3 根据 AssumeRolePolicyDocument 中的操作列出角色名称

List RoleNames based on Action in AssumeRolePolicyDocument using boto3

我正在使用下面的 python 代码列出所有 IAM 角色名称。

from boto3 import Session
import logging
from botocore.exceptions import ClientError


logger = logging.getLogger(__name__)


def list_iam_roles(profile):
    boto_sess = Session(profile_name=profile)
    client = boto_sess.client('iam')

    roles = client.list_roles()
    for role in roles["Roles"]:
        print (role["RoleName"])
    return 

list_iam_roles('some_profile')

它成功 returns 所有 IAM 角色名称的列表,但我的要求是根据特定的 AssumeRolePolicyDocument 进行过滤。

我想过滤具有 Action: sts:AssumeRoleWithSAML.

的角色名称

有什么提示可以过滤吗?

下面粘贴了每个角色的示例输出。已经用 xxx 加密了一些重要信息。

{'Path': '/', 'RoleName': 'some_role_name', 'RoleId': 'some_id', 'Arn': 'arn:aws:iam::xxxxx:role/some_role_name', 'CreateDate': datetime.datetime(2021, 2, 14, 12, 49, 26, tzinfo=tzutc()), 'AssumeRolePolicyDocument': {'Version': '2012-10-17', 'Statement': [{'Sid': '', 'Effect': 'Allow', 'Principal': {'Federated': 'arn:aws:iam::xxxxx:saml-provider/provider_name'}, 'Action': 'sts:AssumeRoleWithSAML', 'Condition': {'StringEquals': {'SAML:aud': 'https://signin.aws.amazon.com/saml'}}}]}, 'MaxSessionDuration': 36000}

一种方法是简单地将 role 转换为字符串并进行字符串搜索:


def list_iam_roles(profile):
    boto_sess = Session(profile_name=profile)
    client = boto_sess.client('iam')

    roles = client.list_roles()
    for role in roles["Roles"]:
        if "sts:AssumeRoleWithSAML".lower() in str(role).lower(): 
            print (role["RoleName"])
    return 

还有一个稍微更明确的检查。只检查一个字符串可能就足够了。

roles = [
    {
        "Path": "/",
        "RoleName": "some_role_name",
        "RoleId": "some_id",
        "Arn": "arn:aws:iam::xxxxx:role/some_role_name",
        "AssumeRolePolicyDocument": {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Sid": "",
                    "Effect": "Allow",
                    "Principal": {
                        "Federated": "arn:aws:iam::xxxxx:saml-provider/provider_name"
                    },
                    "Action": "sts:AssumeRoleWithSAML",
                    "Condition": {
                        "StringEquals": {
                            "SAML:aud": "https://signin.aws.amazon.com/saml"
                        }
                    },
                }
            ],
        },
        "MaxSessionDuration": 36000,
    },
    {
        "Path": "/",
        "RoleName": "some_other_role_name",
        "RoleId": "some_other_id",
        "Arn": "arn:aws:iam::xxxxx:role/some_other_role_name",
        "AssumeRolePolicyDocument": {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Sid": "",
                    "Effect": "Allow",
                    "Principal": {
                        "Federated": "arn:aws:iam::xxxxx:saml-provider/provider_name"
                    },
                    "Action": "not:theActionYoureLookingFor",
                }
            ],
        },
        "MaxSessionDuration": 36000,
    },
]

filtered = set()

for r in roles:
    for s in r.get("AssumeRolePolicyDocument", {}).get("Statement", []):
        actions = s.get("Action", [])
        for a in actions if isinstance(actions, list) else [actions]:
            if "sts:AssumeRoleWithSAML" in a:
                filtered.add(r.get("RoleName"))

print(filtered)

输出:

{'some_role_name'}

在您的函数的上下文中,这将是:

def list_iam_roles(profile):
    filtered = set()
    for r in Session(profile_name=profile).client("iam").list_roles().get("Roles", []):
        for s in r.get("AssumeRolePolicyDocument", {}).get("Statement", []):
            actions = s.get("Action", [])
            for a in actions if isinstance(actions, list) else [actions]:
                if "sts:AssumeRoleWithSAML" in a:
                    filtered.add(r.get("RoleName"))
    return list(filtered)

肯定有一个非常讨厌的理解可以做到这一点,但这应该很清楚,并且处理可以是字符串或列表的策略值。