Skip to content

Instantly share code, notes, and snippets.

@redmoses
Last active August 29, 2015 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save redmoses/10002035 to your computer and use it in GitHub Desktop.
Save redmoses/10002035 to your computer and use it in GitHub Desktop.
AWS Instance Creator
# So that python treats the directory as a package and config.py can be imported
__author__ = 'Musa Nasrullah'
#!/usr/bin/env python
# coding: utf-8
"""
AWS Instance Script
~~~~~~~~~~~~~~~~~~~
The application creates a AWS EC2 instance with the following configurations
~ Enable TCP 22 only for 203.112.73.8
~ Enable TCP 80 for rest of the world
~ Restrict access to all other TCP/UDP port
~ Create instances
~ With given
- AMI ID
- Instance Type
- Availability Zone
~ Default Configuration Values are defined in config.py
~ All logs are written in 'awic.log' file
Dependencies:
~ boto (https://pypi.python.org/pypi/boto)
Usage:
~ Help: python aws_instance_creator.py -h
~ Without any parameters default values would be used
python aws_instance_creator.py
~ With parameters
aws_instance_creator --ami=<AMI-ID> --instance_type=<INSTANCE-TYPE> --zone=<AVAILABILITY-ZONE>
:Author: Musa Nasrullah
:Email: musa.dhk@gmail.com
:Website: http://www.redmoses.org
"""
import sys
import getopt
import time
import logging
import boto.ec2
import config # Import configurations from config.py
# create security group if it doesn't exist
def create_security_group(conn, looger_tool):
looger_tool.info("Connecting to AWS EC2...")
try:
# check if the required group already exists
existing_group = conn.get_all_security_groups(['%s' % config.security_group])
if existing_group is not None:
looger_tool.info("Security group already exists. Skipping action...")
except conn.ResponseError as e:
# the group doesn't exist
if e.error_code == 'InvalidGroup.NotFound':
try:
looger_tool.info("Security group doesn't exist. Creating group...")
# create the group
req_group = conn.create_security_group('%s' % config.security_group, "Code-test group")
except conn.ResponseError as e:
looger_tool.error(e.message)
# create rules
req_group.authorize('tcp', 80, 80, '0.0.0.0/0')
# wait for the settings to be applied
time.sleep(10)
req_group.authorize('tcp', 22, 22, '203.112.73.8/32')
time.sleep(10)
looger_tool.info("Security group created and configured.")
else:
# some other error have occurred, probably authentication error
looger_tool.error(e.message)
sys.exit(2)
# create instance
def create_instance(conn, logger_tool):
# create instance
logger_tool.info("Creating instance...")
try:
# create and run the instance with given configuration
reservation = conn.run_instances(
"%s" % config.ami_id,
key_name='%s' % config.key_name,
instance_type='%s' % config.instance_type,
security_groups=['%s' % config.security_group],
placement='%s' % config.zone
)
except conn.ResponseError as e:
logger_tool.error(e.message)
sys.exit(2)
logger_tool.info("Instance created")
# get the instance object
instance = reservation.instances[0]
logger_tool.info("Instance id: %s" % instance.id)
logger_tool.info("Waiting for the instance to start running...")
# Check up on its status till its running
status = instance.update()
while status == 'pending':
time.sleep(10)
status = instance.update()
if status == 'running':
logger_tool.info("Instance status: %s" % status)
logger_tool.info("Instance IP Address: %s" % instance.ip_address)
logger_tool.info("Creating tags...")
# Add tags to the instance
instance.add_tag("name", "code-test-01")
instance.add_tag("env", "dev")
instance.add_tag("role", "code-test-instance")
time.sleep(10)
logger_tool.info("Successfully configured and created the instance.")
def show_help():
print """
If no parameters are supplied then the default values would be
aws_instance_creator --ami=%s --instance_type=%s --zone=%s
""" % (config.ami_id, config.instance_type, config.zone)
# the main function
def main(argv):
# get parameters
params, args = getopt.getopt(argv, "ha:i:z:", ["ami=", "instance_type=", "zone="])
for param, arg in params:
# help
if param == '-h':
show_help()
sys.exit()
# get AMI id
elif param in ("-a", "--ami"):
config.ami_id = arg.lower()
# get instance type
elif param in ("-i", "--instance_type"):
config.instance_type = arg.lower()
elif param in ("-z", "--zone"):
config.zone = arg.lower()
if len(arg) > 1:
config.region = arg[:-1]
else:
show_help()
# configure logger
logger = logging.getLogger('AWS_InstanceCreator')
# configure log file
file_handler = logging.FileHandler('awsic.log')
# set log formatting
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
file_handler.setFormatter(formatter)
# set log to print and write log messages
logger.addHandler(logging.StreamHandler())
logger.addHandler(file_handler)
# set logging level
logger.setLevel(logging.INFO)
# define connection object
ec2_conn = boto.ec2.connect_to_region(
"%s" % config.region,
aws_access_key_id='%s' % config.access_key,
aws_secret_access_key='%s' % config.secret_access_key
)
# first create security group
create_security_group(ec2_conn, logger)
# then create the instances
create_instance(ec2_conn, logger)
# close the connection
ec2_conn.close()
if __name__ == "__main__":
main(sys.argv[1:])
"""
Description: The constants for aws_instance_creator with their default values
"""
__author__ = 'Musa Nasrullah'
# CONFIGURATIONS #
# the region to connect to
region = "us-east-1"
# put your amazon account access key id
access_key = '<YOUR-AWS-ACCESS-KEY-ID>'
# put your amazon account secret access key
secret_access_key = '<YOUR-AWS-SECRET-ACCESS-KEY>'
## Instance Config Default Values ##
# keypair for ssh connectivity to the instance
# put your own key pair name
key_name = '<YOUR-SSH-KEY-PAIR>'
# Default availibity zone for the instance
zone = "us-east-1b"
# Default AMI for the instance
ami_id = 'ami-0b9c9f62'
# Default Instance type
instance_type = 'm1.large'
# Default Security group
security_group = 'code-test-access'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment