[英]With Boto3, how can I get volumes that are smaller than Y in a list of EC2 Instances?
[英]Python / Boto3 / How can i get a tag list with pagination?
我想使用 boto3 获得一个 rds 和每个标签列表,没有 100 个限制。
这是获取 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'])
这是分页的代码。
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")
我怎样才能结合这两个代码?
您只需要更改 for 循环以迭代您的 all_rds_instances 生成器。
您的脚本如下所示:
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'])
当您使用yield
关键字时,您的 function 将成为生成器,并且它的工作方式与 python 中的任何可迭代对象相同。
关于生成器如何在这里工作有一些很酷的答案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.