I usually store my AMI images on amazon S3, then I deploy them to my AWS EC2 account whenever I want, but recently I got bored from doing this importing process manually and I decided to write a python script that will automate it for me.

I am going to use Nuage NSG AMI image as an example for the AMI image that I want to import. If you are not familiar with Nuage NSG, then check their SDWAN solution (here).

Here is the python script details:

  1. Verifies AWS is installed on the running machine
  2. Configures “aws configure” command to connect to your AWS account
  3. Creates a trusted policy to be able to perform certain AWS operation
  4. Creates a role named vmimport and give VM Import/Export access to it
  5. Attaches the policy to the role
  6. Creates a file, which contains information about the image
  7. Executes the role policy
  8. Checks the status of loading the AMI image to your EC2.

Prepare your environment:

Before you run the script, you should have Python, pexpect, and AWS CLI installed. If pexpect and AWS cli are not installed, just type:

  • pip install pexpect
  • pip install –upgrade –user awscli

Quick Start

To use the script, type the script name and pass the aws parameters.

Mandatory parameters are:

  • access_key               Enter your AWS Access Key (i.e., BKIAIB6QLXA536P2U4BQ)
  • secret_key                 Enter your AWS Secret Key (i.e., oJdKhwd204uJgP0+2v96TDV6rs)
  • region_name             Enter your AWS S3 Region (i.e., us-west-2)
  • nsg_filename             Enter your NSG file name (i.e., Nuage-NSG-4.0.7-129-AWS.raw)
  • bucket_name             Enter your AWS S3 Bucket Name (i.e., nsgami)

Note: For AWS root account credentials, you get credentials, such as access keys or key pairs, from the Security Credentials page in the AWS Management Console. For more information, please go to AWS webpage: http://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html

Here is an example of how to run it:

python import_ami_to_ec2.py <access_key> <secret_key> <region_name> <nsg_filename> <bucket_name>

python import_ami_to_ec2.py BKIAIB6QLXA536P2U4BQ oJdKhwd204uJ96TDV6rs us-west-2 Nuage-NSG-4.0.7-129-AWS.raw nsgami

 

P.S. The script is available in github for anyone to use. Here is the github link: https://github.com/moostech/import-image-to-ec2-aws