Source

Hello EC2 launch / launch_cluster.py

Full commit
#!/usr/bin/python

import config
from launch_instance import get_script

def launch_elb():
    # http://boto.cloudhackers.com/en/latest/elb_tut.html
    import boto.ec2.elb

    connection = boto.ec2.elb.connect_to_region(config.region)

    print 'Creating load balancer.'
    lb = connection.create_load_balancer(
        name=config.cluster,
        zones=config.zones,
        listeners=[(80, 80, 'http')],
    )

    hc = boto.ec2.elb.HealthCheck(
        timeout=4,
        interval=5,
        healthy_threshold=2,
        unhealthy_threshold=2,
        # Using a distinct resource for the health check makes it easier
        # to spot in the web server logs and will allow for tuning later.
        # (Any resource at all will do, because I have nginx configured
        # to return /index.html if the requested resource does not exist.)
        target='HTTP:80/health',    # Check for 200 status from /health.
    )

    lb.configure_health_check(hc)

    print 'URL = http://%s/' % lb.dns_name

def shutdown_elb():
    import boto.ec2.elb

    connection = boto.ec2.elb.connect_to_region(config.region)

    for lb in connection.get_all_load_balancers():
        if lb.name == config.cluster:
            print 'Deleting load balancer.'
            lb.delete()

def launch_autoscaling():
    # http://boto.cloudhackers.com/en/latest/autoscale_tut.html
    import boto.ec2.autoscale

    connection = boto.ec2.autoscale.connect_to_region(config.region)

    lc = boto.ec2.autoscale.LaunchConfiguration(
        name=config.cluster,
        user_data=get_script(),
        **config.instance
    )

    print 'Creating launch configuration.'
    connection.create_launch_configuration(lc)

    ag = boto.ec2.autoscale.AutoScalingGroup(
        name=config.cluster,
        launch_config=lc,
        health_check_type='ELB',
        health_check_period=300,
        load_balancers=[config.cluster],    # Load balancer must already exist.
        availability_zones=config.zones,
        min_size=config.total_instances,
        max_size=config.total_instances,
    )

    print 'Creating auto scaling group.'
    connection.create_auto_scaling_group(ag)

def shutdown_autoscaling():
    import boto.ec2.autoscale

    connection = boto.ec2.autoscale.connect_to_region(config.region)

    for group in connection.get_all_groups(names=[config.cluster]):
        print 'Deleting auto scaling group.'
        group.delete(force_delete=True)

    for lc in connection.get_all_launch_configurations(names=[config.cluster]):
        print 'Deleting launch configuration.'
        lc.delete()

def launch():
    launch_elb()
    launch_autoscaling()

def shutdown():
    shutdown_elb()
    shutdown_autoscaling()

if __name__ == '__main__':
    from sys import argv, exit

    if len(argv) == 1:
        launch()
    elif len(argv) == 2 and argv[1] == '--shutdown':
        shutdown()
    else:
        exit('usage: %s [--shutdown]' % argv[0])