Sunday, July 19, 2015

AWS boto ..getting started

Hello Guys,
I have recently started working with aws boto .so i thought lets also make some program and share it with you hope this  will help you.

# /usr/bin/python2.7
# copyleft free software

import boto.ec2
import sys
import os
import subprocess

from boto.ec2.connection import EC2Connection
# specify AWS keys
auth = {"aws_access_key_id": "<aws_user_keyid>", "aws_secret_access_key": "<aws_access_key>"}

def main():
    # read arguments from the command line and
    # check whether at least two elements were entered
    if len(sys.argv) < 2:
print "Usage: python aws.py {start|stop|launch|copy|list} argument\n"
sys.exit(0)
    else:
action = sys.argv[1]
    if action == "start":
startInstance(str(sys.argv[2]))
    elif action == "stop":
    stopInstance(str(sys.argv[2]))
    elif action == "launch":
launchInstance(str(sys.argv[2]))
    elif action == "copy":
copyInstance(str(sys.argv[2]))
    elif action == "list":
          listAMI()
    else:
    print "Usage: python aws.py {start|stop|launch|copy|list} argument\n"
listAMI()

def launchInstance(instance_id):
    print "launching a new instance"
 

    # change "eu-west-1 region if different"
    try:
ec2 = boto.ec2.connect_to_region("eu-west-1",**auth)
dev_sda1 = boto.ec2.blockdevicemapping.EBSBlockDeviceType()
dev_sda1.size = 25 # size in Gigabytes
bdm = boto.ec2.blockdevicemapping.BlockDeviceMapping()
bdm['/dev/sda1'] = dev_sda1
        my_code = """#!/bin/bash
sudo apt-get update -y && sudo apt-get upgrade -y

"""
    except Exception, e1:
error1 ="Error1: %s" % str(e1)
print(error1)
sys.exit(0)
    #Change Instance ID
    try:
        print "instance id is accepted using function %s " % instance_id
      #  sys.exit(0)

        instance = ec2.run_instances(image_id=instance_id,instance_type="m3.medium",key_name="<aws_key_name>",security_group_ids=['<group_id>'],subnet_id="<subnet_id>", instance_initiated_shutdown_behavior='stop',block_device_map=bdm,user_data = my_code)

    except Exception, e2:
        error2 = "Error2: %s" % str(e2)
        print(error2)
        sys.exit(0)

def startInstance(imageid):
    print "Starting the instance..."

    # change "eu-west-1" region if different
    try:
        ec2 = boto.ec2.connect_to_region("eu-west-1", **auth)

    except Exception, e1:
        error1 = "Error1: %s" % str(e1)
        print(error1)
        sys.exit(0)

    # change instance ID appropriately
    try:
         ec2.start_instances(instance_ids=imageid)

    except Exception, e2:
        error2 = "Error2: %s" % str(e2)
        print(error2)
        sys.exit(0)

def stopInstance(imageid):
    print "Stopping the instance..."

    try:
        ec2 = boto.ec2.connect_to_region("eu-west-1", **auth)

    except Exception, e1:
        error1 = "Error1: %s" % str(e1)
        print(error1)
        sys.exit(0)

    try:
         ec2.stop_instances(instance_ids=imageid)

    except Exception, e2:
        error2 = "Error2: %s" % str(e2)
        print(error2)
        sys.exit(0)

def copyInstance(imageid):
    print "Copying  the instance..."

    try:
        ec2 = boto.ec2.connect_to_region("eu-west-1", **auth)

    except Exception, e1:
        error1 = "Error1: %s" % str(e1)
        print(error1)
        sys.exit(0)

    try:
        ec2.copy_image("ap-southeast-1", imageid, name=imageid)
    except Exception, e2:
        error2 = "Error2: %s" % str(e2)
        print(error2)
        sys.exit(0)



def listAMI():

    #ami=idami
    # change "eu-west-1" region if different
    try:
          ec2 = boto.ec2.connect_to_region("eu-west-1", **auth)
          print "connected"
    except Exception, e1:
          error1 = "Error1: %s" % str(e1)
          print(error1)
          sys.exit(0)

    try:
        images = ec2.get_all_images(filters={'owner-id': '<aws_account_no>'})
for img in images:
          # a = str(img.location)
#           print(img.name)
            a=str(img)
            imgname=a[6:]
            print "%s ,%s \n" %(img.name, imgname)
          # print(img.__dict__)
    except Exception, e2:
        error2 = "Error2: %s" % str(e2)
        print(error2)
sys.exit(0)

if __name__ == '__main__':
    main()

No comments:

Post a Comment