简体   繁体   English

Python / Boto3 / 如何获得带有分页的标签列表?

[英]Python / Boto3 / How can i get a tag list with pagination?

I'd like to get a rds and each tag list using boto3 without 100 limits.我想使用 boto3 获得一个 rds 和每个标签列表,没有 100 个限制。

This is the code for getting the list of rds and each tag.这是获取 rds 列表和每个标签的代码。

client = boto3.client('rds')
instances = client.describe_db_instances()['DBInstances']

for i in instances:
    db_instance_name = i['DBInstanceIdentifier']
    arn = i['DBInstanceArn']
    tags = client.list_tags_for_resource(ResourceName=arn)
    for item in tags['TagList']:
        if item['Key'] == 'Name':
            print(db_instance_name,item['Value'])

And this is the code for pagination.这是分页的代码。

def all_rds_instances(page_size=20):
    client = session.client('rds')
    marker = ""
    pool = []
    while True:
        for instance in pool:
            yield instance
        if marker is None:
            break
        result = client.describe_db_instances(MaxRecords=page_size, Marker=marker)
        marker = result.get("Marker")
        pool = result.get("DBInstances")

How can I combine these 2 codes?我怎样才能结合这两个代码?

You just need to change the for loop to iterate over your all_rds_instances generator.您只需要更改 for 循环以迭代您的 all_rds_instances 生成器。

Your script would look like:您的脚本如下所示:

import boto3

client = boto3.client('rds')

def all_rds_instances(page_size=20):
    marker = ''
    pool = []
    while True:
        for instance in pool:
            yield instance
        if marker is None:
            break
        result = client.describe_db_instances(MaxRecords=page_size, Marker=marker)
        marker = result.get('Marker')
        pool = result.get('DBInstances')


for i in all_rds_instances():
    db_instance_name = i['DBInstanceIdentifier']
    arn = i['DBInstanceArn']
    tags = client.list_tags_for_resource(ResourceName=arn)
    for item in tags['TagList']:
        if item['Key'] == 'Name':
            print(db_instance_name, item['Value'])

When you use the yield keyword your function becomes a generator and it works the same way as any iterable in python.当您使用yield关键字时,您的 function 将成为生成器,并且它的工作方式与 python 中的任何可迭代对象相同。

There is some cool answer about how generator works here关于生成器如何在这里工作有一些很酷的答案

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

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