Search code examples
pythonamazon-web-servicesamazon-ec2boto3

How to filter Amazon EBS snapshots by image (AMI) ID?


I would like to get all Amazon EBS snapshots that are associated with a certain AMI (image).

Is that possible?

I can filter by tag ie.

previous_snapshots = ec2.describe_snapshots(Filters=[{'Name': 'tag:SnapAndDelete', 'Values': ['True']}])['Snapshots']
  for snapshot in previous_snapshots:
    print('Deleting snapshot {}'.format(snapshot['SnapshotId']))
    ec2.delete_snapshot(SnapshotId=snapshot['SnapshotId'])

Is there a filter to use an ImageId instead?

Or could it be possible to get a list of all snapshots associated to an image id using describe_images? I would be happy with either of both.

ie.

images = ec2.describe_images(Owners=['self'])['Images']

Thanks


Solution

  • When calling describe_images(), Amazon EBS Snapshots are referenced in the BlockDeviceMappings section:

    {
        'Images': [
            {
                'CreationDate': 'string',
                'ImageId': 'string',
                'Platform': 'Windows',
                'BlockDeviceMappings': [
                    {
                        'DeviceName': 'string',
                        'VirtualName': 'string',
                        'Ebs': {
                            'Iops': 123,
                            'SnapshotId': 'string',   <--- This is the Amazon EBS Snapshot
                            'VolumeSize': 123,
                            'VolumeType': 'standard'|'io1'|'io2'|'gp2'|'sc1'|'st1'|'gp3'
                            ...
    

    Therefore, if you wish to retrieve all Amazon EBS Snapshots for a given AMI you can use code like this:

    import boto3
    
    ec2_client = boto3.client('ec2')
    
    response = ec2_client.describe_images(ImageIds = ['ami-1234'])
    
    first_ami = response['Images'][0]
    
    snapshots = [device['Ebs']['SnapshotId'] for device in first_ami['BlockDeviceMappings'] if 'Ebs' in device]
    
    for snapshot in snapshots:
        print(snapshot)