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
示例#2
0
def create_load_balancer(zones, env_id):
    config = Config(env_id)
    logger = logging.getLogger(__name__)

    if config.has_option("elb_name"):
        output = "A load balancer already exists for this environment"
        logger.warning(output)
        print (output)
        exit(1)

    region = config.get("region")
    conn = boto.ec2.elb.connect_to_region(region)
    ports = [(80, 80, "http")]

    hc_res = config.get("health_check_resource")
    hc = HealthCheck(interval=30, healthy_threshold=3, unhealthy_threshold=5, target="HTTP:80/%s" % hc_res)

    name = "lb-%s" % env_id
    elb = conn.create_load_balancer(name, zones, ports)
    elb.configure_health_check(hc)
    return name, elb
示例#3
0
def elb_ensure(name, listeners, check, zones=None, *args, **kwargs):
    """Create a new ELB

    :type name: string
    :param name: the name of the elb, if exists, the same object will be
        returned, unless force parameter if set to True

    :type listeners: a list of listener object
    :param listeners: the listeners of the ELB

    :type zones: list of strings
    :param zones: the availability zones where ELB must be span.

    :type check: a elb_check
    :param check: the health check to be used.
    """

    _obj = elb_exists(name)
    if _obj:
        mico.output.info("using existent ELB: %s" % name)
        return _obj

    connection = elb_connect()

    if zones is None:
        ec2_conn = ec2_connect()
        zones = ec2_conn.get_all_zones()

    elb = connection.create_load_balancer(
            name=name,
            zones=zones,
            listeners=listeners,
            *args,
            **kwargs
    )

    elb.configure_health_check(check)
    elb = elb_exists(name)
    mico.output.info("created new ELB: %s" % name)
    return elb
示例#4
0
 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)
     conn.set_lb_policies_of_listener(elb.name, config["elb_port"], sp_name)
     access_log = AccessLogAttribute()
     access_log.enabled = True
示例#5
0
time.sleep(10)
while not instance.update() == 'running':
	time.sleep(3)
	
instance.add_tag("Project", "2.2")
LG_DNS = str(instance.dns_name)
print LG_DNS
time.sleep(10)

	
#Create ELB

print 'Creating ELB'
elb = elb_conn.create_load_balancer('Project22hongf', ZONE, PORT)
healthcheck = HealthCheck(access_point = 'Project22hongf', interval=30, healthy_threshold=2, unhealthy_threshold=10, target='HTTP:80/heartbeat?lg='+LG_DNS)
elb.configure_health_check(healthcheck)
ELB_DNS = str(elb.dns_name)
print ELB_DNS
time.sleep(10)

	
#tag ELB

client = boto3.client('elb')
response = client.add_tags(
    LoadBalancerNames=[
        'Project22hongf',
    ],
    Tags=[
        {
            'Key': 'Project',
示例#6
0
def modify(name,
           region,
           zones,
           listeners=None,
           subnets=None,
           security_groups=None,
           health_check=None,
           policies=None,
           instances=None,
           test=False,
           aws_key=None,
           aws_secret=None,
           elbconn=None,
           elb=None):
    """
    Launch an ELB

    Most arguments are the same as :meth:`.launch_or_modify`

    Parameters
    ----------
    elbconn : :class:`boto.ec2.elb.ELBConnection`, optional
        If present this function will not open a new elb connection
    elb : :class:`boto.ec2.elb.LoadBalancer`, optional
        If present this function will not make a call to fetch the load
        balancer

    """
    if elbconn is None:
        elbconn = __salt__['aws_util.elbconn'](region, aws_key, aws_secret)

    if elb is None:
        elbs = elbconn.get_all_load_balancers(load_balancer_names=[name])
        elb = elbs[0]

    changes = {}

    # Availability Zones
    if zones != elb.availability_zones:
        to_remove = set(elb.availability_zones) - set(zones)
        if to_remove:
            if not test:
                elb.disable_zones(list(to_remove))
            for zone in to_remove:
                changes['Zone {0}'.format(zone)] = "Disabled"
        to_add = set(zones) - set(elb.availability_zones)
        if to_add:
            if not test:
                elb.enable_zones(list(to_add))
            for zone in to_add:
                changes['Zone {0}'.format(zone)] = "Enabled"

    # Listeners
    elb_listeners = []
    # Convert the boto listeners to tuples
    for listener in elb.listeners:
        tup_listener = (
            listener.load_balancer_port,
            listener.instance_port,
            listener.protocol,
        )
        if listener.instance_protocol is not None:
            tup_listener += (listener.instance_protocol, )
        if listener.ssl_certificate_id is not None:
            tup_listener += (listener.ssl_certificate_id, )
        elb_listeners.append(tup_listener)
    listeners = listeners or []

    # Translate all protocols to uppercase
    for listener in listeners:
        listener[2] = listener[2].upper()
        listener[3] = listener[3].upper()

    listeners = [tuple(l) for l in listeners]
    if listeners != elb_listeners:
        to_delete = set(elb_listeners) - set(listeners)
        if to_delete:
            if not test:
                for listener in to_delete:
                    elb.delete_listener(listener[0])
            changes['Listeners Deleted'] = str(list(to_delete))
        to_create = set(listeners) - set(elb_listeners)
        if to_create:
            if not test:
                elbconn.create_load_balancer_listeners(
                    elb.name, complex_listeners=list(to_create))
            changes['Listeners Created'] = str(list(to_create))

    # Subnets
    # TODO: This is untested because my account doesn't have VPC
    elb_subnets = list(elb.subnets)
    subnets = subnets or []
    if subnets != elb_subnets:
        to_detach = set(elb_subnets) - set(subnets)
        if to_detach:
            if not test:
                elb.detach_subnets(list(to_detach))
            changes['Subnets Detached'] = str(list(to_detach))
        to_attach = set(subnets) - set(elb_subnets)
        if to_attach:
            if not test:
                elb.attach_subnets(list(to_attach))
            changes['Subnets Attached'] = str(list(to_attach))

    # Security Groups
    # TODO: This is untested because my account doesn't have VPC
    elb_security_groups = list(elb.security_groups)
    security_groups = security_groups or []
    if security_groups != elb_security_groups:
        to_remove = set(elb_security_groups) - set(security_groups)
        if to_remove:
            changes['Security Groups Removed'] = str(list(to_remove))
        to_add = set(security_groups) - set(elb_security_groups)
        if to_add:
            changes['Security Groups Added'] = str(list(to_add))
        if not test:
            elb.apply_security_groups(security_groups)

    # Health check
    if health_check is None:
        health_check = {}
    check = elb.health_check
    new_check = boto.ec2.elb.healthcheck.HealthCheck(
        access_point=name,
        interval=health_check.get('interval', 30),
        target=health_check.get('target'),
        healthy_threshold=health_check.get('healthy_threshold', 3),
        timeout=health_check.get('timeout', 5),
        unhealthy_threshold=health_check.get('unhealthy_threshold', 5))
    modified = False
    if check is None:
        modified = True
    if not modified:
        for attr in ('interval', 'target', 'healthy_threshold', 'timeout',
                     'unhealthy_threshold'):
            if getattr(new_check, attr) != getattr(check, attr):
                modified = True
                break
    if modified:
        changes['Health check'] = "Modified"
        if not test:
            elb.configure_health_check(new_check)

    # Instances
    if instances is not None:
        _convert_server_names(instances, region, aws_key, aws_secret)

        elb_instances = [i.id for i in elb.instances]
        if instances != elb_instances:
            to_remove = set(elb_instances) - set(instances)
            if to_remove:
                changes['Instances Removed'] = list(to_remove)
                if not test:
                    elb.deregister_instances(list(to_remove))
            to_add = set(instances) - set(elb_instances)
            if to_add:
                changes['Instances Added'] = list(to_add)
                if not test:
                    elb.register_instances(list(to_add))

    # Policies
    policies = policies or {}
    elb_policies = []
    for attr in ('app_cookie_stickiness_policies',
                 'lb_cookie_stickiness_policies'):
        for policy in getattr(elb.policies, attr):
            elb_policies.append(policy.policy_name)

    # Create any policies that don't exist yet
    for policy in policies.itervalues():
        if policy['type'] == 'lb':
            policy['name'] = 'lb' + str(policy['cookie_expire'])
        elif policy['type'] == 'app':
            policy['name'] = 'app' + str(hash(policy['cookie_name']))
        else:
            raise ValueError("Policy type '{0}' must be 'lb' or 'app'".format(
                policy['name']))

        if policy['name'] not in elb_policies:
            if not test:
                if policy['type'] == 'lb':
                    elb.create_cookie_stickiness_policy(
                        policy['cookie_expire'], policy['name'])
                elif policy['type'] == 'app':
                    elb.create_app_cookie_stickiness_policy(
                        policy['cookie_name'], policy['name'])

    for listener in elb.listeners:
        if listener.load_balancer_port in policies:
            port = listener.load_balancer_port
            policy = policies[port]
            if len(listener.policy_names) == 0:
                if not test:
                    elb.set_policies_of_listener(port, [policy['name']])
                changes['Port {0:d}'.format(port)] = "Added policy"
            else:
                if policy['name'] != listener.policy_names[0]:
                    if not test:
                        elb.set_policies_of_listener(port, [policy['name']])
                    changes['Port {0:d}'.format(port)] = "Changed policy"
        else:
            if len(listener.policy_names) > 0:
                if not test:
                    elb.set_policies_of_listener(port, [])
            changes['Port {0:d}'.format(port)] = "Removed policy"

    return changes
示例#7
0
def modify(
    name,
    region,
    zones,
    listeners=None,
    subnets=None,
    security_groups=None,
    health_check=None,
    policies=None,
    instances=None,
    test=False,
    aws_key=None,
    aws_secret=None,
    elbconn=None,
        elb=None):
    """
    Launch an ELB

    Most arguments are the same as :meth:`.launch_or_modify`

    Parameters
    ----------
    elbconn : :class:`boto.ec2.elb.ELBConnection`, optional
        If present this function will not open a new elb connection
    elb : :class:`boto.ec2.elb.LoadBalancer`, optional
        If present this function will not make a call to fetch the load
        balancer

    """
    if elbconn is None:
        elbconn = __salt__['aws_util.elbconn'](region, aws_key, aws_secret)

    if elb is None:
        elbs = elbconn.get_all_load_balancers(load_balancer_names=[name])
        elb = elbs[0]

    changes = {}

    # Availability Zones
    if zones != elb.availability_zones:
        to_remove = set(elb.availability_zones) - set(zones)
        if to_remove:
            if not test:
                elb.disable_zones(list(to_remove))
            for zone in to_remove:
                changes['Zone {0}'.format(zone)] = "Disabled"
        to_add = set(zones) - set(elb.availability_zones)
        if to_add:
            if not test:
                elb.enable_zones(list(to_add))
            for zone in to_add:
                changes['Zone {0}'.format(zone)] = "Enabled"

    # Listeners
    elb_listeners = []
    # Convert the boto listeners to tuples
    for listener in elb.listeners:
        tup_listener = (
            listener.load_balancer_port,
            listener.instance_port,
            listener.protocol,
        )
        if listener.instance_protocol is not None:
            tup_listener += (listener.instance_protocol,)
        if listener.ssl_certificate_id is not None:
            tup_listener += (listener.ssl_certificate_id,)
        elb_listeners.append(tup_listener)
    listeners = listeners or []

    # Translate all protocols to uppercase
    for listener in listeners:
        listener[2] = listener[2].upper()
        listener[3] = listener[3].upper()

    listeners = [tuple(l) for l in listeners]
    if listeners != elb_listeners:
        to_delete = set(elb_listeners) - set(listeners)
        if to_delete:
            if not test:
                for listener in to_delete:
                    elb.delete_listener(listener[0])
            changes['Listeners Deleted'] = str(list(to_delete))
        to_create = set(listeners) - set(elb_listeners)
        if to_create:
            if not test:
                elbconn.create_load_balancer_listeners(
                    elb.name, complex_listeners=list(to_create))
            changes['Listeners Created'] = str(list(to_create))

    # Subnets
    # TODO: This is untested because my account doesn't have VPC
    elb_subnets = list(elb.subnets)
    subnets = subnets or []
    if subnets != elb_subnets:
        to_detach = set(elb_subnets) - set(subnets)
        if to_detach:
            if not test:
                elb.detach_subnets(list(to_detach))
            changes['Subnets Detached'] = str(list(to_detach))
        to_attach = set(subnets) - set(elb_subnets)
        if to_attach:
            if not test:
                elb.attach_subnets(list(to_attach))
            changes['Subnets Attached'] = str(list(to_attach))

    # Security Groups
    # TODO: This is untested because my account doesn't have VPC
    elb_security_groups = list(elb.security_groups)
    security_groups = security_groups or []
    if security_groups != elb_security_groups:
        to_remove = set(elb_security_groups) - set(security_groups)
        if to_remove:
            changes['Security Groups Removed'] = str(list(to_remove))
        to_add = set(security_groups) - set(elb_security_groups)
        if to_add:
            changes['Security Groups Added'] = str(list(to_add))
        if not test:
            elb.apply_security_groups(security_groups)

    # Health check
    if health_check is None:
        health_check = {}
    check = elb.health_check
    new_check = boto.ec2.elb.healthcheck.HealthCheck(
        access_point=name,
        interval=health_check.get('interval', 30),
        target=health_check.get('target'),
        healthy_threshold=health_check.get('healthy_threshold', 3),
        timeout=health_check.get('timeout', 5),
        unhealthy_threshold=health_check.get('unhealthy_threshold', 5))
    modified = False
    if check is None:
        modified = True
    if not modified:
        for attr in ('interval', 'target', 'healthy_threshold', 'timeout',
                     'unhealthy_threshold'):
            if getattr(new_check, attr) != getattr(check, attr):
                modified = True
                break
    if modified:
        changes['Health check'] = "Modified"
        if not test:
            elb.configure_health_check(new_check)

    # Instances
    if instances is not None:
        _convert_server_names(instances, region, aws_key, aws_secret)

        elb_instances = [i.id for i in elb.instances]
        if instances != elb_instances:
            to_remove = set(elb_instances) - set(instances)
            if to_remove:
                changes['Instances Removed'] = list(to_remove)
                if not test:
                    elb.deregister_instances(list(to_remove))
            to_add = set(instances) - set(elb_instances)
            if to_add:
                changes['Instances Added'] = list(to_add)
                if not test:
                    elb.register_instances(list(to_add))

    # Policies
    policies = policies or {}
    elb_policies = []
    for attr in ('app_cookie_stickiness_policies',
                 'lb_cookie_stickiness_policies'):
        for policy in getattr(elb.policies, attr):
            elb_policies.append(policy.policy_name)

    # Create any policies that don't exist yet
    for policy in policies.itervalues():
        if policy['type'] == 'lb':
            policy['name'] = 'lb' + str(policy['cookie_expire'])
        elif policy['type'] == 'app':
            policy['name'] = 'app' + str(hash(policy['cookie_name']))
        else:
            raise ValueError("Policy type '{0}' must be 'lb' or 'app'"
                             .format(policy['name']))

        if policy['name'] not in elb_policies:
            if not test:
                if policy['type'] == 'lb':
                    elb.create_cookie_stickiness_policy(
                        policy['cookie_expire'],
                        policy['name'])
                elif policy['type'] == 'app':
                    elb.create_app_cookie_stickiness_policy(
                        policy['cookie_name'], policy['name'])

    for listener in elb.listeners:
        if listener.load_balancer_port in policies:
            port = listener.load_balancer_port
            policy = policies[port]
            if len(listener.policy_names) == 0:
                if not test:
                    elb.set_policies_of_listener(port, [policy['name']])
                changes['Port {0:d}'.format(port)] = "Added policy"
            else:
                if policy['name'] != listener.policy_names[0]:
                    if not test:
                        elb.set_policies_of_listener(port,
                                                     [policy['name']])
                    changes['Port {0:d}'.format(port)] = "Changed policy"
        else:
            if len(listener.policy_names) > 0:
                if not test:
                    elb.set_policies_of_listener(port, [])
            changes['Port {0:d}'.format(port)] = "Removed policy"

    return changes