简体   繁体   中英

snapshot id with filter boto3 within a For Loop

I am trying to pass each snapshot id into for loop and print but to no avail, each time I can get to pass it only describes on the first snapshot and describes prints the tag for all.

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'],
        ))

Ive tried a number of combinations to pass in the snapshot id from the function but to no avail like below.

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'],
        ))

How can I pass the snapshot id into the describe with filter applied to get the tag for each snapshot

was able to resolve using function below and calling in for loop in main body

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'])

thank you for the help John

It appears that your requirement is:

  • Find all snapshots that do not have a tag of mytag=TRUE

The simplest approach would be to use an if statement that checks the tags associated with the snapshot:

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'])

The above code will print the ID and Description of any Snapshot that does not have a tag of mytag=TRUE .

能够使用上面的函数解析并调用每个快照的 for 循环

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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