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.


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":
     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

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'):

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

# Stop the instance otherwise it will cost $$$$$

No comments:

Post a Comment