I want to find all Amazon Elastic Compute Cloud (Amazon EC2) instances that run Amazon Linux 1 (AL1) in my AWS account.
Resolution
Note: If you receive errors when you run AWS Command Line Interface (AWS CLI) commands, then see Troubleshooting errors for the AWS CLI. Also, make sure that you're using the most recent AWS CLI version. The following command and script list AL1 instances that use only the Amazon Machine Image (AMI) that Amazon owns. They don't include custom or customer-owned AMIs.
To identify EC2 instances that run AL1 in your account, use the AWS CLI, or run a Python script.
AWS CLI
To get information about the image for each instance across all AWS Regions in your account, run the following describe-regions, describe-images, and describe-instances commands:
for REGION in $(aws ec2 describe-regions --output text --query 'Regions[].[RegionName]'); do for AMI in $(aws ec2 describe-instances --output text --query 'Reservations[*].Instances[*].[ImageId]' --region $REGION --output text); do aws ec2 describe-images --region $REGION --image-ids $AMI --output text --query 'Images[*].[ImageId, Description]' --filters 'Name=owner-alias,Values=amazon'; done; done
Example output:
ami-0afa794ecbe858568 Provided by Red Hat, Inc.
ami-0430580de6244e02e Canonical, Ubuntu, 20.04 LTS, amd64 focal image build on 2023-05-17
ami-002c2b8d1f5b1eb47 Amazon Linux 2 Kernel 5.10 AMI 2.0.20230822.0 x86_64 HVM gp2
ami-0e25ae59fc523298e Amazon Linux AMI 2018.03.0.20230905.0 x86_64 HVM gp2
To view all instances that run AL1, run the following describe-regions, describe-images, and describe-instances commands:
for REGION in $(aws ec2 describe-regions --output text --query 'Regions[].[RegionName]'); do aws ec2 describe-instances --filter Name=image-id,Values=ami-0e25ae59fc523298e --region $REGION --query 'Reservations[*].Instances[*].[InstanceId, State.Name, ImageId]'; done
Note: Replace ami-0e25ae59fc523298e with the ID for the AMI that runs Amazon Linux 1.
Example output:
i-123a4bc5d67e8910 running ami-0e25ae59fc523298e
Python
To identify instances that run AL1, complete the following steps:
-
Use a Linux or bash terminal to create the following Python script file that identifies instances that run AL1:
import argparse
import boto3
import json
from collections import defaultdict
def filter_regions(regions):
enabled_regions_raw = boto3.client('account').list_regions(
RegionOptStatusContains=['ENABLED', 'ENABLED_BY_DEFAULT'],
MaxResults=50)
enabled_regions = set([r['RegionName'] for r in enabled_regions_raw['Regions']])
valid_regions = enabled_regions.intersection(set(regions)) if regions else enabled_regions
print(f"Identified valid AWS regions: {valid_regions}")
return valid_regions
def instances_ordered_by_amis(ec2, region):
result = defaultdict(list)
for instance in ec2.instances.all():
if instance.state['Name'] not in ['shutting-down', 'terminated']:
result[instance.image_id].append(instance.id)
return result
def filter_al1_amis(ec2, amis):
result = []
for ami in amis:
try:
if ec2.Image(ami).image_owner_alias == 'amazon' and ec2.Image(ami).name.startswith('amzn-ami-'):
result.append(ami)
except:
# properties not set, cannot determine if this AMI is Amazon Linux 1 or not
continue
return result
def find_al1_instances(regions):
result = defaultdict(list)
for region in regions:
ec2 = boto3.resource('ec2', region_name=region)
amis_instances_dict = instances_ordered_by_amis(ec2, region)
al1_amis = filter_al1_amis(ec2, amis_instances_dict.keys())
result[region].extend(
[instance_id for instance_ids in
[instances for ami, instances in amis_instances_dict.items() if ami in al1_amis]
for instance_id in instance_ids]
)
return result
def main():
parser = argparse.ArgumentParser(
prog='find_al1_instances',
description='Find all EC2 instances running official Amazon Linux 1 AMIs',
epilog='Note: This python script does not list EC2 instances running derived Amazon Linux 1 AMIs')
parser.add_argument(
'-r', '--regions', nargs='+',
help='Space separated list of AWS regions names to search')
args = parser.parse_args()
account_id = boto3.client('sts').get_caller_identity()['Account']
print(f"Using AWS account: {account_id}")
regions = filter_regions(args.regions)
output = find_al1_instances(regions)
print("Found following EC2 instances in your AWS account running official Amazon Linux 1 AMIs:")
print(json.dumps(output, indent=4, sort_keys=True))
if __name__ == "__main__":
main()
-
Run the following command to install dependencies in yum/apt-get/dnf:
sudo yum install python3-pippython3 -m pip install boto3
Note: The preceding command uses the yum package management utility, but you can also use the apt-get or dnf tools. If you don't have Boto3 credentials, then see Credentials on the Boto3 website.
-
Run the following command to run the script:
python3 find_al1_instances.py [-r REGIONS [REGIONS ...]]