def create_load_balancer(self, load_balancer_name): """ Create a load balancer :param load_balancer_name: Name of the load balance to create :return: True if created, false otherwise """ try: # First, the load balancer is created zones = ['eu-west-1b', 'eu-west-1c', 'eu-west-1a'] ports = [(80, 8080, 'http'), (443, 8443, 'tcp')] lb = self.conn.create_load_balancer(load_balancer_name, zones, ports) # Then, a health check is created and associated with it hc = HealthCheck(interval=20, healthy_threshold=3, unhealthy_threshold=5, target='HTTP:8080/health') lb.configure_health_check(hc) return True except Exception: return False
def __get_default_healthcheck__(): return HealthCheck( interval = LoadBalancers.lb_defaults["interval"], healthy_threshold = LoadBalancers.lb_defaults["healthy_threshold"], unhealthy_threshold = LoadBalancers.lb_defaults["unhealthy_threshold"], target = LoadBalancers.lb_defaults["target"] )
def set_health_check(name, health_check, region=None, key=None, keyid=None, profile=None): """ Set attributes on an ELB. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_health_check myelb '{"target": "HTTP:80/"}' """ conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 hc = HealthCheck(**health_check) while True: try: conn.configure_health_check(name, hc) log.info("Configured health check on ELB %s", name) return True except boto.exception.BotoServerError as error: if retries and e.code == "Throttling": log.debug("Throttled by AWS API, will retry in 5 seconds.") time.sleep(5) retries -= 1 continue log.exception("Failed to configure health check on ELB %s", name) return False
def health_check(self): """(:class:`boto.ec2.elb.HealthCheck`) The health check configuration. """ conf = self.config.get('health_check', {}) return HealthCheck(**conf)
def set_health_check(name, health_check, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_health_check myelb '{"target": "HTTP:80/"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) hc = HealthCheck(**health_check) try: conn.configure_health_check(name, hc) log.info('Configured health check on ELB {0}'.format(name)) except boto.exception.BotoServerError as error: log.debug(error) log.info('Failed to configure health check on ELB {0}: {1}'.format( name, error)) return False return True
def create_healthcheck(self, interval, healthy_threshold, unhealthy_threshold, target): print target self.hc = HealthCheck(interval=interval, healthy_threshold=healthy_threshold, unhealthy_threshold=unhealthy_threshold, target=target)
def create_health_check(_elb): hc = HealthCheck( interval=C['elb_interval'], timeout=C['elb_timeout'], healthy_threshold=C['healthy_threshold'], unhealthy_threshold=C['unhealthy_threshold'], target=C['elb_target'] ) return hc
def create_lb(lb_name): 'create a new load balancer' region = 'ap-southeast-1' #zones = 'ap-southeast-1a' zones = None listeners = [(80, 80, 'HTTP'), (443, 443, 'TCP')] subnets = 'subnet-0d0b3379' lb = lb_conn.create_load_balancer(lb_name, zones, listeners, subnets) hc = HealthCheck(interval=20, healthy_threshold=3, unhealthy_threshold=5, target='HTTP:80/health') lb.configure_health_check(hc) print lb.dns_name
def elb_check(target, interval=20, healthy_threshold=3, unhealthy_threshold=5): """Create a new ELB check. :type interval: int :param interval: Specifies how many seconds there are between health checks. :type target: str :param target: Determines what to check on an instance. See the Amazon HealthCheck_ documentation for possible Target values. .. _HealthCheck: http://docs.amazonwebservices.com/ElasticLoadBalancing/latest/APIReference/API_HealthCheck.html """ return HealthCheck(target=target, interval=interval, healthy_threshold=healthy_threshold, unhealthy_threshold=unhealthy_threshold)
def create_LoadBalancer(): print "Creating ELB..." elb_conn = ELBConnection(AWSAccessKeyId, AWSSecretKey) zones = ['us-east-1a'] ports = [(80, 80, 'http')] hc = HealthCheck(interval=30, healthy_threshold=2, unhealthy_threshold=10, target='HTTP:80/heartbeat?username=chihangw') global elb elb = elb_conn.create_load_balancer(name='myELB', zones=zones, listeners=ports) elb.configure_health_check(hc) ELB_DNS = elb.dns_name print "ELB created successfully" print "ELB DNS: %s" % ELB_DNS return ELB_DNS
class ELB: elb = resource_name('elb') hc = HealthCheck(interval=20, healthy_threshold=3, unhealthy_threshold=5, target='HTTP:8080/health') def __init__(self, ld_names, zones=[], ports=[]): self.ld_names = ld_names self.zones = zones self.ports = ports def create_Load_Balancer(self): lb = ELB.elb.create_load_balancer(self.ld_names, self.zones, self.ports) lb.configure_health_check(ELB.hc) print(lb.dns_name)
def test_create_health_check(): conn = boto.connect_elb() hc = HealthCheck( interval=20, healthy_threshold=3, unhealthy_threshold=5, target='HTTP:8080/health', timeout=23, ) lb = conn.create_load_balancer('my-lb', [], []) lb.configure_health_check(hc) balancer = conn.get_all_load_balancers()[0] health_check = balancer.health_check health_check.interval.should.equal(20) health_check.healthy_threshold.should.equal(3) health_check.unhealthy_threshold.should.equal(5) health_check.target.should.equal('HTTP:8080/health') health_check.timeout.should.equal(23)
def test_create_health_check(): conn = boto.connect_elb() hc = HealthCheck( interval=20, healthy_threshold=3, unhealthy_threshold=5, target="HTTP:8080/health", timeout=23, ) ports = [(80, 8080, "http"), (443, 8443, "tcp")] lb = conn.create_load_balancer("my-lb", [], ports) lb.configure_health_check(hc) balancer = conn.get_all_load_balancers()[0] health_check = balancer.health_check health_check.interval.should.equal(20) health_check.healthy_threshold.should.equal(3) health_check.unhealthy_threshold.should.equal(5) health_check.target.should.equal("HTTP:8080/health") health_check.timeout.should.equal(23)
print security_group ##################### elb boto.ec2 regions = boto.ec2.elb.regions() print regions elb = boto.ec2.elb.connect_to_region(CONNECT_REGION,aws_access_key_id=AWS_ACCESS_KEY,aws_secret_access_key=AWS_SECRET_KEY) # conn = boto.ec2.connect_to_region("us-east-1") list = elb.get_all_load_balancers() print list hc = HealthCheck( interval=15, target='HTTP:8080/upload' ) zones = [CONNECT_AVAILABILITY_ZONE] ports = [(80, 80, 'http'), (8080, 8080, 'http')] lb = elb.create_load_balancer('my-lb', zones, ports) lb.configure_health_check(hc) print lb.dns_name while throughput <=2000: reservation=conn.run_instances(AMI,key_name=KEY_NAME,instance_type=INSTANCE_TYPE,placement=CONNECT_AVAILABILITY_ZONE,security_groups=[security_group]) instance_cnt
inst2name = 'usnjlawsvcache02' security_groups = ['sg-7e38141b'] #Get Subnets subnet1 = get_subnet2("Prod_Web_East-1a-Test", region=region) subnet2 = get_subnet2("Prod_Web_East-1b-Test", region=region) subnets = [subnet1, subnet2] #Get Instance ID inst1 = get_ec2_instance(region=region, name=inst1name) inst2 = get_ec2_instance(region=region, name=inst2name) instances = [inst1, inst2] #Define Health Check hc = HealthCheck('healthCheck', interval=interval, target=target, timeout=timeout) #Create Load Balancer try: Cheng = '' Cheng = get_elb(region=region, Name=lbname1) print Cheng except BotoServerError as e: print "LB already exists" if len(Cheng) == 0: lb = create_elb(region, name=lbname1, zones=None, listeners=listeners,
def configureHealthCheck(self, target): """ Configures health check for the cluster """ self.healthCheck = HealthCheck(target=target, timeout=5) print ">>> Configured health check for: " + target
MaxCount=2,) # create VPC vpc = ec2.create_vpc(CidrBlock='10.0.0.0/16') vpc.create_tags(Tags=[{"Key":"TestVPC","Value":"default_vpc"}]) vpc.wait_until_available() print(vpc.id) subnet = ec2.create_subnet(CidrBlock = '10.0.2.0/24', VpcId= vpc.id) print(subnet.id) # create ELB conn_elb = ELBConnection(aws_access_key_id='', aws_secret_access_key='') #For a complete list of options see http://boto.cloudhackers.com/ref/ec2.html#module-boto.ec2.elb.healthcheck hc = HealthCheck('healthCheck', interval=20, target='HTTP:80/index.html', timeout=3) #For a complete list of options see http://boto.cloudhackers.com/ref/ec2.html#boto.ec2.elb.ELBConnection.create_load_balancer lb = conn_elb.create_load_balancer('my-lb', ['us-east-1a', 'us-east-1b', 'us-east-1c'], [(80, 80, 'http'), (443, 443, 'tcp')]) lb.configure_health_check(hc) #DNS name for your new load balancer print "Map the CNAME of your website to: %s" % (lb.dns_name)
def deploy_latest_app_ami(app_name, env_name): global aws aws = AWS.from_config(config) aws.connect() lb_group_ids = [aws.get_security_group_id('riker-load-balancer')] inst_group_ids = [aws.get_security_group_id('riker-instance')] app = App(env_name, app_name) health_check_target = app.config.get('health_check', 'TCP:80') name = re.sub('[^A-Za-z0-9\-]', '-', app.name) app_image = LatestAppImage(app).get() print '-----> Connecting to ELB' elb_conn = boto.connect_elb() log('info', 'Load balancer', show_header=True) load_balancer_name = name try: elb_result = elb_conn.get_all_load_balancers( load_balancer_names=[load_balancer_name]) lb = elb_result[0] log('info', 'Found {}'.format(load_balancer_name)) except boto.exception.BotoServerError: log('info', 'Not found, creating load balancer') listeners = [(80, 80, 'HTTP', 'HTTP')] lb = elb_conn.create_load_balancer(name=load_balancer_name, zones=None, complex_listeners=listeners, security_groups=lb_group_ids, subnets=[aws.subnet_id]) hc = HealthCheck(target=health_check_target) lb.configure_health_check(hc) cda = ConnectionDrainingAttribute() cda.enabled = True cda.timeout = 300 elb_conn.modify_lb_attribute(load_balancer_name=load_balancer_name, attribute='connectionDraining', value=cda) print '-----> Connecting to AutoScale' as_conn = boto.connect_autoscale() log('info', 'Launch configuration', show_header=True) launch_config_name = "{}-{}".format(name, app_image.tags['deploy-id']) lc_result = as_conn.get_all_launch_configurations( names=[launch_config_name]) if len(lc_result) == 0: log('info', 'Not found, creating LaunchConfiguration') lc = LaunchConfiguration(name=launch_config_name, image_id=app_image.id, key_name=aws.key_pair_name, security_groups=inst_group_ids, instance_type=aws.instance_type) as_conn.create_launch_configuration(lc) else: log('info', 'Found {}'.format(launch_config_name)) lc = lc_result[0] existing_group = None deploy_id = int(app_image.tags['deploy-id'] or 0) log('info', 'Getting previous auto-scaling group', show_header=True) for did in xrange(deploy_id - 1, 0, -1): existing_group_name = "{}-{}".format(name, did) log('info', '{} ?'.format(existing_group_name)) ag_result = as_conn.get_all_groups(names=[existing_group_name]) if len(ag_result) > 0: existing_group = ag_result[0] log('info', 'Found {}'.format(existing_group.name)) break else: log('info', 'No') if existing_group is not None: existing_healthy_instances = [ inst for inst in existing_group.instances if inst.lifecycle_state == 'InService' and inst.health_status == 'Healthy' ] existing_healthy_instance_count = len(existing_healthy_instances) desired_capacity = existing_group.desired_capacity min_size = existing_group.min_size max_size = existing_group.max_size if existing_healthy_instance_count == 0 and desired_capacity == 0: print '-----> WARNING: existing auto-scaling group {} has no healthy instances and a desired capacity of 0. New auto-scaling group will launch 1 instance.'.format( existing_group) desired_capacity = 1 min_size = 1 max_size = max_size if max_size > 0 else 1 else: existing_healthy_instance_count = 0 desired_capacity = 1 min_size = 1 max_size = 1 log('info', '{} existing instance(s) found'.format( existing_healthy_instance_count), show_header=True) log( 'info', 'Existing auto-scale properties: desired_capacity={}, min_size={}, max_size={}' .format(desired_capacity, min_size, max_size)) log('info', 'Auto-scaling group', show_header=True) group_name = "{}-{}".format(name, app_image.tags['deploy-id']) ag_result = as_conn.get_all_groups(names=[group_name]) if len(ag_result) == 0: log('info', 'Not found, creating autoscale group') ag = AutoScalingGroup(name=group_name, load_balancers=[load_balancer_name], launch_config=lc, desired_capacity=desired_capacity, min_size=min_size, max_size=max_size, health_check_type='ELB', health_check_period='300', vpc_zone_identifier=aws.subnet_id) as_conn.create_auto_scaling_group(ag) else: log('info', 'Found {}'.format(group_name)) ag = ag_result[0] ag.desired_capacity = desired_capacity ag.max_size = max_size ag.min_size = min_size ag.launch_config_name = launch_config_name ag.update() log('info', 'Waiting for new instances to become healthy', show_header=True) all_healthy = False for i in xrange(60): if i > 0: print ' ---' time.sleep(10) elb_result = elb_conn.get_all_load_balancers( load_balancer_names=[load_balancer_name]) lb = elb_result[0] lb_insts = lb.get_instance_health() print ' Load-balancer instances: {}'.format(lb_insts) # NOTE: re-get auto-scaling group to get updated instance info. ag = as_conn.get_all_groups(names=[group_name])[0] ag_insts = [inst for inst in ag.instances] log('info', 'Auto-scaling group Instances: {}'.format(ag_insts)) if len(ag_insts) < desired_capacity: not_yet_launched_count = desired_capacity - len(ag_insts) log( 'info', '{} new instance(s) not yet launched'.format( not_yet_launched_count)) continue ag_inst_ids = set(inst.instance_id for inst in ag_insts) lb_inst_ids = set(inst.instance_id for inst in lb_insts) asg_insts_not_in_lb = ag_inst_ids.difference(lb_inst_ids) if len(asg_insts_not_in_lb) > 0: log( 'info', '{} new instance(s) not yet in load balancer'.format( len(asg_insts_not_in_lb))) continue new_lb_insts = [ inst for inst in lb_insts if inst.instance_id in ag_inst_ids ] healthy_new_lb_insts = [ inst for inst in new_lb_insts if inst.state == 'InService' ] all_healthy = len(healthy_new_lb_insts) == len(ag_insts) log('info', '{} new instance(s) are healthy'.format(len(healthy_new_lb_insts))) diff = existing_healthy_instance_count - len(healthy_new_lb_insts) if existing_group is not None and diff >= 0: change = False if existing_group.desired_capacity != diff: existing_group.desired_capacity = diff change = True if existing_group.max_size != diff: existing_group.max_size = diff change = True if diff < existing_group.min_size: existing_group.min_size = diff change = True if change: existing_group.update() log( 'info', 'Change previous auto-scale group {} properties: desired_capacity={}, min_size={}, max_size={}' .format(existing_group, existing_group.desired_capacity, existing_group.min_size, existing_group.max_size)) if all_healthy: log('info', 'All new instances healthy!', show_header=True) healthy_lb_inst_ids = [ inst.instance_id for inst in lb_insts if inst.state == 'InService' ] previous_healthy_inst_ids = [ inst.instance_id for inst in existing_healthy_instances ] if existing_group else [] not_yet_out_of_service = set( previous_healthy_inst_ids).intersection(healthy_lb_inst_ids) if len(not_yet_out_of_service) > 0: log( 'info', 'Waiting to remove previous instances ({}) from load balancer' .format(not_yet_out_of_service)) else: log('info', 'All previous instances ({}) have been removed from load balancer' .format(previous_healthy_inst_ids), show_header=True) if all_healthy and len(not_yet_out_of_service) == 0: break else: raise Exception("Timeout") elb_result = elb_conn.get_all_load_balancers( load_balancer_names=[load_balancer_name]) lb = elb_result[0] lb_insts = [ inst for inst in lb.get_instance_health() if inst.state == 'InService' ] print '-----> Deployed {} instance(s) of {} to {}'.format( lb_insts, app.name, lb.dns_name) print '-----> DONE!'
#=================Construct a list of all availability zones for your region========= conn_reg = boto.ec2.connect_to_region(region_name=region) zones = conn_reg.get_all_zones() zoneStrings = [] for zone in zones: zoneStrings.append(zone.name) conn_elb = ELBConnection(AWS_ACCESS_KEY, AWS_SECRET_KEY) conn_as = AutoScaleConnection(AWS_ACCESS_KEY, AWS_SECRET_KEY) #=================Create a Load Balancer============================================= #For a complete list of options see http://boto.cloudhackers.com/ref/ec2.html#module-boto.ec2.elb.healthcheck hc = HealthCheck('healthCheck', interval=elastic_load_balancer['interval'], target=elastic_load_balancer['health_check_target'], timeout=elastic_load_balancer['timeout']) #For a complete list of options see http://boto.cloudhackers.com/ref/ec2.html#boto.ec2.elb.ELBConnection.create_load_balancer lb = conn_elb.create_load_balancer( elastic_load_balancer['name'], zoneStrings, elastic_load_balancer['connection_forwarding']) lb.configure_health_check(hc) #DNS name for your new load balancer print "Map the CNAME of your website to: %s" % (lb.dns_name) #=================Create a Auto Scaling Group and a Launch Configuration============================================= #For a complete list of options see http://boto.cloudhackers.com/ref/ec2.html#boto.ec2.autoscale.launchconfig.LaunchConfiguration lc = LaunchConfiguration(name=lc_name,
aws_access_key_id=AWS_ACCESS_KEY, aws_secret_access_key=AWS_SECRET_KEY) conn_reg = boto.ec2.elb.connect_to_region(regionName) conn_elb = ELBConnection(AWS_ACCESS_KEY, AWS_SECRET_KEY) conn_as = AutoScaleConnection(AWS_ACCESS_KEY, AWS_SECRET_KEY) conn_cw = boto.ec2.cloudwatch.connect_to_region(regionName) conn_cw = boto.ec2.cloudwatch.connect_to_region( regionName, aws_access_key_id=AWS_ACCESS_KEY, aws_secret_access_key=AWS_SECRET_KEY) # ============================================== # # configure a health check hc = HealthCheck( interval=elastic_load_balancer['interval'], healthy_threshold=elastic_load_balancer['healthyThreshold'], unhealthy_threshold=elastic_load_balancer['unhealthyThreshold'], target=elastic_load_balancer['healthCheckTarget']) # create a load balancer lb = conn_elb.create_load_balancer(elastic_load_balancer['name'], elastic_load_balancer['zones'], elastic_load_balancer['ports']) lb.configure_health_check(hc) print lb.dns_name + " created!" sleep(10) # ============================================== # # ============================================== # # clear the last execution results # conn_as.delete_auto_scaling_group('my_group')
import boto.ec2.elb from boto.ec2.elb import HealthCheck elb_conn = boto.ec2.elb.connect_to_region('us-east-1') # ELB requires a few pieces to be setup hc = HealthCheck(interval=20, healthy_threshold=3, unhealthy_threshold=5, target='TCP:22' # target='HTTP:8080/health' ) zones = ['us-east-1a', 'us-east-1b', 'us-east-1c', 'us-east-1d'] ports = [(80, 80, 'http')] #ports = [(80, 8080, 'http'), (443, 8443, 'tcp')] # Now create a new load balancer lb = elb_conn.create_load_balancer('pywebdev-lb', zones, ports) print 'New ELB: ', lb print 'New ELB public DNS: ', lb.dns_name # Add the health check configuration to the ELB. lb.configure_health_check(hc)
# wait for load generator to run while not lg_instance.update() == 'running': time.sleep(3) time.sleep(5) # add tag lg_instance.add_tag(TAGK, TAGV) time.sleep(5) print lg_instance.id print lg_instance.dns_name print lg_instance.tags print 'Creating ELB' # initialize elastc load balancer conn2 = ELBConnection(os.environ['AWS_ACCESS_KEY_ID'], os.environ['AWS_SECRET_KEY']) # set heartbeat page = 'HTTP:80' + '/heartbeat?lg=' + lg_instance.dns_name hc = HealthCheck(interval=20, healthy_threshold=3, unhealthy_threshold=5, target=page) # set port 80 elb = conn2.create_load_balancer('elb', [ZONE], [(80, 80, 'http')]) # allow all traffic conn2.apply_security_groups_to_lb('elb', [sg.id]) conn2.configure_health_check('elb', hc) print elb.dns_name print 'Creating ASG' # initialize launch config conn3 = AutoScaleConnection(os.environ['AWS_ACCESS_KEY_ID'], os.environ['AWS_SECRET_KEY']) config = LaunchConfiguration(name='config', image_id=DC_IMAGE, security_groups=sgs, instance_type=TYPE, instance_monitoring=True) conn3.create_launch_configuration(config) # initialize auto scaling group ag = AutoScalingGroup(connection=conn3, name='gp', load_balancers=['elb'], availability_zones=[ZONE], health_check_type='ELB', health_check_period=60, launch_config=config,
def start_elb(tag, user_data, region, auto_register, as_ami, subnet_id, security_groups, public_ip_address, iam_role, zone_strings, elastic_load_balancer): print "Using tag \"" + tag + "\"" conn_reg = boto.ec2.connect_to_region(region_name=region) # =================Construct a list of all availability zones for your region========= conn_elb = boto.ec2.elb.connect_to_region(region_name=region) conn_as = boto.ec2.autoscale.connect_to_region(region_name=region) # =================Create a Load Balancer============================================= # For a complete list of options see http://boto.cloudhackers.com/ref/ec2.html#module-boto.ec2.elb.healthcheck hc = HealthCheck('healthCheck', interval=elastic_load_balancer['interval'], target=elastic_load_balancer['health_check_target'], timeout=elastic_load_balancer['timeout']) # ELB does not accept any special characters elb_tag = tag elb_tag = elb_tag.replace("_", "") elb_tag = elb_tag.replace("-", "") elb_tag = elb_tag.replace(".", "") print "ELB name: \"" + elb_tag + "\"" # For a complete list of options see # http://boto.cloudhackers.com/ref/ec2.html#boto.ec2.elb.ELBConnection.create_load_balancer lb = conn_elb.create_load_balancer( name=elb_tag + 'Elb', zones=None, subnets=subnet_id, security_groups=security_groups, listeners=elastic_load_balancer['connection_forwarding']) if auto_register: aws_library.add_instances_to_lb(tag=tag, lb=lb, region=region) lb.configure_health_check(hc) # DNS name for your new load balancer print "Map the CNAME of your website to: %s" % lb.dns_name # =================Create a Auto Scaling Group and a Launch Configuration============================================ # For a complete list of options see # http://boto.cloudhackers.com/ref/ec2.html#boto.ec2.autoscale.launchconfig.LaunchConfiguration lc = LaunchConfiguration(name=elb_tag + "Lc", image_id=as_ami['id'], key_name=as_ami['access_key'], security_groups=as_ami['security_groups'], instance_type=as_ami['instance_type'], instance_monitoring=as_ami['instance_monitoring'], instance_profile_name=iam_role, user_data=user_data) conn_as.create_launch_configuration(lc) # For a complete list of options see # http://boto.cloudhackers.com/ref/ec2.html#boto.ec2.autoscale.group.AutoScalingGroup ag = AutoScalingGroup(group_name=elb_tag + "Sg", load_balancers=[elb_tag], availability_zones=zone_strings, launch_config=lc, min_size=autoscaling_group['min_size'], max_size=autoscaling_group['max_size'], associate_public_ip_address=public_ip_address, vpc_zone_identifier=subnet_id) conn_as.create_auto_scaling_group(ag) # =================Create Scaling Policies============================================= # Policy for scaling the number of servers up and down # For a complete list of options see # http://boto.cloudhackers.com/ref/ec2.html#boto.ec2.autoscale.policy.ScalingPolicy scaling_up_policy = ScalingPolicy(name=elb_tag + "webserverScaleUpPolicy", adjustment_type='ChangeInCapacity', as_name=ag.name, scaling_adjustment=1, cooldown=60) scaling_down_policy = ScalingPolicy(name=elb_tag + "webserverScaleDownPolicy", adjustment_type='ChangeInCapacity', as_name=ag.name, scaling_adjustment=-1, cooldown=180) conn_as.create_scaling_policy(scaling_up_policy) conn_as.create_scaling_policy(scaling_down_policy) scaling_up_policy = conn_as.get_all_policies( as_group=elb_tag + "Sg", policy_names=[elb_tag + "webserverScaleUpPolicy"])[0] scaling_down_policy = conn_as.get_all_policies( as_group=elb_tag + "Sg", policy_names=[elb_tag + "webserverScaleDownPolicy"])[0] cloudwatch = boto.ec2.cloudwatch.connect_to_region(region) alarm_dimensions = {"AutoScalingGroupName": 'my_group'} scale_up_alarm = MetricAlarm(name=elb_tag + 'scale_up_on_cpu', namespace='AWS/EC2', metric='CPUUtilization', statistic='Average', comparison='>', threshold='70', period='60', evaluation_periods=2, alarm_actions=[scaling_up_policy.policy_arn], dimensions=alarm_dimensions) scale_down_alarm = MetricAlarm( name=elb_tag + 'scale_down_on_cpu', namespace='AWS/EC2', metric='CPUUtilization', statistic='Average', comparison='<', threshold='40', period='60', evaluation_periods=2, alarm_actions=[scaling_down_policy.policy_arn], dimensions=alarm_dimensions) cloudwatch.create_alarm(scale_down_alarm) cloudwatch.create_alarm(scale_up_alarm)
print "Creating elastic load balancer %s" % name conn = boto.ec2.elb.connect_to_region(region_name) try: elb_list = conn.get_all_load_balancers(load_balancer_names=[name]) except BotoServerError, e: # ELB by the given name does not exist elb_list = [] if not len(elb_list): ports = config["ports"] elb = conn.create_load_balancer(name, None, complex_listeners=ports, subnets=[subnet.id], security_groups=[sg.id]) hc = HealthCheck( interval=config["health_check"]["interval"], healthy_threshold=config["health_check"]["healthy_threshold"], unhealthy_threshold=config["health_check"]["unhealthy_threshold"], target=config["health_check"]["target"] + config["alive-check-token"]) elb.configure_health_check(hc) pkp_name = "PublicKeyPolicy-%s-BackendCert" % elb.name conn.create_lb_policy(elb.name, pkp_name, "PublicKeyPolicyType", {"PublicKey": cert}) besap_name = "BackendAuthPolicy-%s-BackendCert" % elb.name conn.create_lb_policy(elb.name, besap_name, "BackendServerAuthenticationPolicyType", {"PublicKeyPolicyName": pkp_name}) conn.set_lb_policies_of_backend_server(elb.name, config["backend_port"], [besap_name]) sp_name = "Sticky-%s" % elb.name conn.create_lb_cookie_stickiness_policy(None, elb.name, sp_name)