How To Create an Amazon Machine Image Instance From a Server Action


This article will provide an example script to use as a Server Action to create an Amazon Machine Image.


The Amazon Machine Image will be created from an EC2 instance, and the Server must be powered off when running this Server Action.


Use the example below to create the new Amazon Machine Image, the name of the new AMI will be specified at run time.

from common.methods import set_progress
from infrastructure.models import Server

def run(job, logger=None):
    server = job.server_set.first()
    instance_id = server.resource_handler_svr_id
    env = server.environment
    aws = server.resource_handler.cast()

    set_progress("Preparing to create an AMI from EC2 instance {}"
                 .format(instance_id), logger, job)

    # Power off VM (optional)
    if server.power_status != "POWEROFF":
        return "FAILURE", "", "Server must be powered off first."

    # Connect to AWS
    set_progress("Connecting to EC2 region {}.".format(env.aws_region), logger, job)
    boto3 = aws.get_boto3_client(env.aws_region)

    # Create AMI from instance
    boto3.create_image(InstanceId=instance_id, Name='{{ name_of_new_ami }}', Description='Created via CloudBolt')
    return "","",""
Have more questions? Submit a request


Please sign in to leave a comment.