Friday, March 11, 2016

Python Boto - Creating EC2 Instance

Python Boto is a powerful python module to interact with AWS environment. In this we will look into a simple way to create an instance.


#!/usr/bin/python

import boto.ec2

# Create a connection to a region. For example us-west-1
# Check in your AWS console or with your AWS administrator
ec2conn = boto.ec2.connect_to_region(<aws-region>)


# Create EC2 instance
createdInstance =  ec2conn.run_instances(
              <AMI to be used for Instance creation>,
              key_name= <Security Key to be used>,
              instance_type=<Type of instance e.g. t2.micro>,
              security_groups= <Array of security groups to be attached>,
              instance_profile_name= <IAM Role to be associated>)

# Get the instance details object
 instance = createdInstance.instances[0]

# Before doing anything make sure the instance is in running instance
while instance.update() != "running":
     time.sleep(10)
     print("Instance is still not up")

# Finally instance is in running.
print("Instance is running")

# Still we need to wait. The instance may not be reachable Find the status
status=ec2conn.get_all_instance_status(instance_ids=instance.id)

Instance has to be fully up so that it is reachable. 
# Keep trying till is is reachable
while (status[0].system_status.details["reachability"] != 'passed'):
            time.sleep(10)

print("Add the tag")
instance.add_tag('Name', 'My EC2 Instance' )

# Stop the instance otherwise it will cost $$$$$
ec2conn.stop_instances(instance.id)

No comments:

Post a Comment