首页 > 解决方案 > 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'])

谢谢你的帮助约翰

标签: python-3.xamazon-web-servicesaws-lambdaboto3boto

解决方案


看来您的要求是:

  • 查找所有没有标签的快照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


推荐阅读