How can I identify Amazon Linux 1 EC2 instances in my AWS account?

3 minute read
0

I want to find all Amazon Elastic Compute Cloud (Amazon EC2) instances that run Amazon Linux 1 (AL1) in my AWS account.

Short description

Maintenance support for AL1 ends on December 31, 2023. After this date, you can continue to run AL1 on your EC2 instances and use AL1 AMIs to launch new EC2 instances. However, critical security updates for AL1 provided by AWS are discontinued.

Resolution

Complete the following steps to identify EC2 instances that run AL 1 in your AWS account:

Important: The following script lists only AL1 instances that use the AMI owned by Amazon. It doesn't include custom or customer-owned AMIs.

  1. Create the following Python script file on Linux or bash terminal (for example: find_al1_instances.py).

    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()
  2. Run the following commands to install dependencies in yum/apt-get/dnf:

    Note: The following commands use the yum package management utility. These commands also work with the apt-get or dnf tools.

    sudo yum install python3-pip
    python3 -m pip install boto3

    Note: If you don't have boto3 credentials, then see Credentials on the Boto2 1.34.7 documentation website.

  3. Use the following command to run the script:

    python3 find_al1_instances.py [-r REGIONS [REGIONS ...]]
AWS OFFICIAL
AWS OFFICIALUpdated 2 months ago
1 Comment

For anyone who'd rather use AWS CLI, the below commands might help if you don't have an overwhelming amount of instances using various images.

Describe all instances original configured AMI for all regions:

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]'; done; done

Example Result:

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

Describe all instances running a specific AMI (Amazon Linux 1 in this example):

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 --output text --query 'Reservations[*].Instances[*].[InstanceId, State.Name, ImageId]'; done  

Example Result:

i-123a4bc5d67e8910 running ami-0e25ae59fc523298e
profile pictureAWS
tjrj
replied 8 days ago