【问题标题】:How to filter AWS roles by tags in boto3?如何通过 boto3 中的标签过滤 AWS 角色?
【发布时间】:2022-04-27 21:50:03
【问题描述】:

我正在尝试获取带有特殊标签的角色列表

Python 3.9 版

Boto3 版本 1.16.25

这是我的代码

iam = boto3.client('iam', region_name='us-east-1')
roles = iam.list_roles()["Roles"]
print(roles)

结果:

{
   "Path":"/",
   "RoleName":"aws-***-delivery-role",
   "RoleId":"AROA****LOIO",
   "Arn":"arn:aws:iam::448*****770:role/aws-***-delivery-role",
   "CreateDate":datetime.datetime(2017,   11,   28,   21,   13,   3, "tzinfo=tzutc())",
   "AssumeRolePolicyDocument":{
      "Version":"2012-10-17",
      "Statement":[
         {
            "Sid":"",
            "Effect":"Allow",
            "Principal":{
               "Service":"firehose.amazonaws.com"
            },
            "Action":"sts:AssumeRole",
            "Condition":{
               "StringEquals":{
                  "sts:ExternalId":"448***770"
               }
            }
         }
      ]
   },
   "MaxSessionDuration":3600
}

我没有看到标签

我也试过这个代码

iam = boto3.resource('iam', region_name='us-east-1')
roles = iam.roles.all()

但同样这些角色没有标签

只有当我运行这段代码时,我才能看到一个标签然后过滤它,但是 role.load() 每次都对 AWS 进行 API 调用,我有 3k 个没有 角色的角色。 load() 它不起作用。结果就是这么长

iam = boto3.resource('iam', region_name='us-east-1')
roles = iam.roles.all()
for role in roles:
    role.load()
    print(role.tags)

请给我一些建议或分享您的经验,我如何按标签过滤角色列表?

我播下这个文档https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/iam.html#IAM.Client.list_roles

list_roles 应该返回带有标签的 JSON,但这不起作用

【问题讨论】:

    标签: boto3 boto


    【解决方案1】:

    boto3 文档错误地报告 list_roles() 返回标签,请参阅此 GitHub 问题以获取更新: https://github.com/boto/boto3/issues/2126.

    要获得标签,我们需要在每个角色上调用get_role(),然后从那里过滤。这可能会导致节流,因此 我还添加了指数退避重试。

    import logging
    from typing import Dict, Iterator, List
    
    import botocore.client
    from botocore.exceptions import ClientError
    from retry import retry
    
    # Type aliases to make it more clear what type of AWS resource is being returned
    Policy = Dict
    PolicyDocument = Dict
    Role = Dict
    
    logger = logging.getLogger(__package__)
    logger.setLevel(logging.INFO)
    
    RETRY_ARGS = {
        "exceptions": ClientError,
        "tries": 5,
        "delay": 5,
        "backoff": 2,
        "jitter": (2, 15)
    }
    
    class IAMHelper:
        def __init__(self, client: botocore.client):
            self.client = client
    
        @retry(**RETRY_ARGS)
        def get_role_details(self, role_name: str) -> Role:
            """
            Since we are making a client.get_role() call for each role to filter on tags, this method is prone to
            throttling. To counter this this method uses an exponential backoff.
            """
    
            logger.info("Attempting to get details for role %s", role_name)
    
            return self.client.get_role(RoleName=role_name).get("Role")
    
        def describe_roles(self) -> Iterator[Role]:
            """
            The IAM client has no `describe_roles()` method, only `list_roles()`. The output of `list_roles()` does not
            contain tags, so we need to call `get_role()` on each.
    
            The boto3 documentation incorrectly reports that `list_roles()` returns tags:
                https://github.com/boto/boto3/issues/2126
            """
    
            for page in self.client.get_paginator('list_roles').paginate():
                for role in page["Roles"]:
                    yield self.get_role_details(role["RoleName"])
    
        def find_roles_by_tag(self, tag_key: str, tag_value: str) -> List[Role]:
            roles = []
    
            for role in self.describe_roles():
                for tag in role.get("Tags", []):
                    if tag["Key"] == tag_key and tag["Value"] == tag_value:
                        logger.info("Found %s role with tags %s: %s", role.get("RoleName"), tag_key, tag_value)
                        roles.append(role)
    
            return roles
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-13
      • 1970-01-01
      • 2020-12-06
      • 2017-09-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多