Skip to content

Instantly share code, notes, and snippets.

@srs81
Created September 26, 2012 17:29
Show Gist options
  • Save srs81/3789366 to your computer and use it in GitHub Desktop.
Save srs81/3789366 to your computer and use it in GitHub Desktop.
Python: Run new EC2 instances, giving them names and assigning IP addresses
#!/usr/bin/python
#
# Start new EC2 instances
#
import boto, sys, time
print "Please enter your AWS credentials below."
# AWS credentials
aws_key = raw_input("AWS key: ")
aws_secret = raw_input("AWS secret: ")
# Your SSH key name (configured on AWS)
keyName = raw_input("AWS key pair: ")
# AMI number
amiID = 'ami-123abc'
# The instances that we want to start
instances = [
# You can have tuples in this format:
# [Name, IP address, instance type, security group]
["Test 1", "1.2.3.4", "t1.micro", "MySecurityGroup"]
]
# Get the IP addresses
print
print "Please enter IP addresses for the nodes and hit ENTER."
print "If you do not enter an IP address, the IP address shown ",
print "will be applied to the box."
for i in range(0,len(instances)):
prompt = instances[i][0]
if not (instances[i][0] == ""):
prompt += " [" + instances[i][1] + "]"
prompt += ": "
instances[i][1] = raw_input(prompt)
# --------------------------------------------
# Connect to EC2
conn = boto.connect_ec2(aws_key, aws_secret)
print "Setting up instances..."
# Sleep for a few seconds to make sure instances are there
time.sleep(10)
# Issue a request to start each instance
reservations = []
for (name, ip, itype, group) in instances:
reservations.append(conn.run_instances(amiID,
key_name=keyName, instance_type=itype, security_groups=[group]))
print "Making sure instances are running..."
# Check to make sure *all* instances are running before doing anything
stillPending = True
while stillPending:
time.sleep(5)
stillPending = False
instancesToCheck = []
# Get instance ID of all instances from startup time
for reservation in reservations:
instancesToCheck.append(reservation.instances[0].id)
# Check whether all are running. If any are not, continue
for i in conn.get_all_instances(instancesToCheck):
if i.instances[0].state != "running":
stillPending = True
break
print "Assigning names (and IPs) to nodes..."
# If we get here, all instances should be running
# Iterate over each request
for i in range(0, len(reservations)):
reservation = reservations[i]
# Get instance ID
instance = conn.get_all_instances([reservation.instances[0].id])[0].instances[0].id
# Set the visible name on AWS
conn.create_tags([instance], {'Name': instances[i][0]})
# Associate the IP address, if it exists
if not (instances[i][1] == ""):
conn.associate_address(instance, instances[i][1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment