Search code examples
amazon-web-servicesunit-testingamazon-ec2boto3moto

Moto how to create EC2 instance - InvalidAMIID.NotFound


Using moto how can you create an EC2 instance since theres no AMIs available to launch an instance with. This repo seems to be "pre-loading" AMIs that are later used within tests but im not sure how these are being created https://github.com/spulec/moto/blob/master/tests/test_ec2/test_instances.py#L25 https://github.com/spulec/moto/blob/master/moto/ec2/resources/amis.json

I've tried calling .describe_images(Owners=["amazon"]) however, all the AMIs returned when used in the run_instances call give the below error.

from moto import mock_ec2


@mock_ec2
def Test_create_ec2():
    boto3.client('ec2').run_instances(ImageId="ami-1234abcd", MinCount=1, MaxCount=1)

botocore.exceptions.ClientError: An error occurred (InvalidAMIID.NotFound) when calling the RunInstances operation: The image id '[ami-1234abcd]' does not exist

This issue also relates to the unresolved question How to create ami with specific image-id using moto?


Solution

  • The call to describe_images does give a list of all available ImageId's. The following test works against the current development branch of Moto:

    @mock_ec2
    def test_all_images():
        client = boto3.client("ec2", region_name="us-east-1")
        images = client.describe_images(Owners=["amazon"])["Images"]
        for image in images:
            client.run_instances(ImageId=image["ImageId"], MinCount=1, MaxCount=1)
    

    The preloaded images come from this file: https://github.com/spulec/moto/blob/master/moto/ec2/resources/amis.json

    If you want to substitute your own AMI's, you can use the following environment variable: MOTO_AMIS_PATH=/full/path/to/amis.json

    This JSON-file has to be in the same format as the one linked above. Note that the environment variable has to be set before Moto is initialized - these AMI's are loaded the moment you call from moto import mock_ec2, so the environment variable has to be set before that import takes place.