python-3.x - For 循环中带有过滤器 boto3 的快照 id
问题描述
我试图将每个快照 id 传递到 for 循环和打印中,但无济于事,每次我可以传递它时,它只在第一个快照上描述并描述为所有人打印标签。
for snapshot in get_my_snapshots():
print ('Snapshot ID is equal to', snapshot['id'])
my_tag = ec2.describe_snapshots(Filters=[{'Name': 'tag:mytag', 'Values': ['TRUE']}])['Snapshots']
print (my_tag)
print('{:22} {:22}'.format(
snapshot['id'],
snapshot['description'],
))
我尝试了多种组合从函数中传递快照 id,但无济于事,如下所示。
for snapshot in get_my_snapshots():
print ('Snapshot ID is equal to', snapshot['id'])
my_tag = ec2.describe_snapshots(SnapshotId=snapshot['id'], Filters=[{'Name': 'tag:mytag', 'Values': ['TRUE']}])['Snapshots']
print (my_tag)
print('{:22} {:22}'.format(
snapshot['id'],
snapshot['description'],
))
如何将快照 id 传递到描述中,并应用过滤器来获取每个快照的标签
能够使用下面的函数并在主体中调用 for 循环来解决
def get_tag_snapshots():
'''
Get all tags.
'''
global region_tags
ec2 = boto3.client('ec2', region_name=region_tags)
snap_tag = ec2.describe_snapshots(Filters=[{'Name': 'tag:mytag', 'Values': ['TRUE']}])
print ('Snap Tag!!', snap_tag)
ls_snaptags=[]
for snapshot in snap_tag['Snapshots']:
(ls_snaptags.append(snapshot['SnapshotId']))
snap_tag_id = snapshot['SnapshotId']
yield {
'snap_id': snapshot['SnapshotId'],
}
print ("Snapshot with mytag = True !! ",snapshot['SnapshotId'])
谢谢你的帮助约翰
解决方案
看来您的要求是:
- 查找所有没有标签的快照
mytag=TRUE
最简单的方法是使用if
检查与快照关联的标签的语句:
import boto3
ec2_client = boto3.client('ec2')
for snapshot in ec2_client.describe_snapshots(OwnerIds=['self'])['Snapshots']:
if 'Tags' in snapshot:
# Skip if mytag=TRUE
if [tag for tag in snapshot['Tags'] if tag['Key'] == 'mytag' and tag['Value'] == 'TRUE']:
continue
print(snapshot['SnapshotId'])
print(snapshot['Description'])
上面的代码将打印没有标签的任何快照的 ID 和描述mytag=TRUE
。
推荐阅读
- r - 根据R中的时间范围选择数据框
- amazon-web-services - 如何在不设置 CORS 的情况下从浏览器列出 S3 存储桶中的对象?
- python - 我如何使用用户输入浮点数并在 Python 中找到平均值、最小值、最大值和范围
- php - 如何将迁移中的更改部署到分解的数据库?
- python-3.x - 无法在 Django 中加载图像
- c# - 团队中具有 MS 身份验证的服务器端 Blazor?
- java - 当忙于旋转的Java线程绑定到物理内核时,是否会因为到达代码中的新分支而发生上下文切换?
- sql - 显示计数最少的数据
- mongodb - 无法在 vs 终端中启动 mongod
- android - 当设备字体大小发生变化时,Android 不会在应用程序中增加文本