Search code examples
pythonamazon-web-servicesamazon-ec2boto3amazon-ami

How to get free-tier AMI in AWS using python with boto3


I'm trying to build a function in python that creates a new ec2 instance in a specific region. For the function to work I need to specify the AMI of this new instance. The problem is that the same AMI (for example Amazon Linux) has a different id in different regions and I can't use an image of one region in another region instance.

and I can't understand how do I get this AMI id in this specific region

def create_instance(region):
        ec2 = boto3.resource('ec2', region)
        instances = ec2.create_instances(InstanceType='t2.micro',
                                         MinCount=1, MaxCount=1,
                                         ImageId='AMI-id') # What do I put here?

For now, it's not really important what the AMI is besides the fact that it is Linux and free-tier, So maybe searching a specific known free-tier Linux AMI will work.

I know you can get all AMI using describe_images() function but how do I filter only those that are Linux (Could be a specific version) and free-tier

boto3.client('ec2').describe_images(Filters["""What do I write here to get only linux free-tier AMI"""])

Solution

  • AWS System Manager maintains the curated list of AWS Linux 2 AMIs at /aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2

    Here is the CLI call:

    $ aws ssm get-parameters --names /aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2 --region us-east-1
    
    {
        "Parameters": [
            {
                "Name": "/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2",
                "Type": "String",
                "Value": "ami-0323c3dd2da7fb37d",
                "Version": 27,
                "LastModifiedDate": 1586395100.713,
                "ARN": "arn:aws:ssm:us-east-1::parameter/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2"
            }
        ],
        "InvalidParameters": []
    }
    

    You should be able to do the same in Python with SSM BOTO3 API.