Skip to content

Instantly share code, notes, and snippets.

@gurchik
Last active May 11, 2023 14:26
Show Gist options
  • Save gurchik/6af9a66a5c4a24b865f0d7dde7b34753 to your computer and use it in GitHub Desktop.
Save gurchik/6af9a66a5c4a24b865f0d7dde7b34753 to your computer and use it in GitHub Desktop.
Get AMIs used by all EC2s in an account

Get AMIs used by all EC2s in an account

Example output:

{
    "ami-123redacted": {
        "id": "ami-123redacted",
        "name": "The name of the AMI",
        "instances": {
            "us-east-1": [
                "i-123redacted"
            ],
            "us-east-2": [
                "i-456redacted"
            ]
        }
    },
    "ami-456redacted": {
        "id": "ami-456redacted",
        "name": "The name of the AMI",
        "instances": {
            "us-east-1": [
                "i-789redacted"
            ]
        }
    }
}
import boto3
import json
ret = {}
def get_ec2_regions():
client = boto3.client('ec2')
return [r['RegionName'] for r in client.describe_regions()['Regions']]
def append(ec2, image_id, instance_id, region):
if image_id not in ret:
image = ec2.Image(image_id)
ret[image_id] = {
"id": image_id,
"name": image.name,
"instances": {}
}
if region not in ret[image_id]['instances']:
ret[image_id]['instances'][region] = []
ret[image_id]['instances'][region].append(instance_id)
def get_ec2_images(region):
ec2 = boto3.resource('ec2', region)
instances = ec2.instances.all()
for instance in instances:
append(ec2, instance.image_id, instance.instance_id, region)
for region in get_ec2_regions():
get_ec2_images(region)
print(json.dumps(ret))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment