def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(dict(
        listener_port=dict(type='int', required=True, choices=[i for i in range(1, 65536)]),
		load_balancer_id=dict(type='str', aliases=['lb_id']),
        listener_type=dict(type='str', choices=['http', 'https', 'tcp', 'udp'])
    ))
    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json(msg="Package 'footmark' required for this module.")

    load_balancer_id = module.params['load_balancer_id']
    listener_port = module.params['listener_port']
    listener_type = module.params['listener_type']

    try:
        slb = slb_connect(module)

        # check whether server load balancer exist or not
        laod_balancer = slb.describe_load_balancers(load_balancer_id=load_balancer_id)
        if laod_balancer and len(laod_balancer) == 1:

            # list load balancers listeners
            listener = slb.describe_load_balancer_listener_attribute(load_balancer_id,
                                                                     listener_port,
                                                                     listener_type)
            if listener is None:
                module.fail_json(msg="Unable to describe slb listeners, no listeners found")
            else:
                module.exit_json(changed=False, listener=get_info(listener))
        else:
            module.fail_json(msg="Unable to describe slb listeners, invalid load balancer id")
    except Exception as e:
        module.fail_json(msg="Unable to describe slb listeners, and got an error: {0}.".format(e))
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(load_balancer_name=dict(type='list', aliases=['name']),
             load_balancer_ids=dict(type='list', aliases=['ids']),
             name_prefix=dict(type='str'),
             filters=dict(type='dict')))

    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json(msg="Package 'footmark' required for this module.")

    lb_ids = module.params['load_balancer_ids']
    if not lb_ids:
        lb_ids = []
    name_prefix = module.params['name_prefix']
    filters = module.params['filters']
    if not filters:
        filters = {}
    for key, value in filters.items():
        if key in ["LoadBalancerId", "load-balancer-id", "load_balancer_id"
                   ] and value not in lb_ids:
            lb_ids.append(value)
    lbs = []
    ids = []

    try:
        slb = slb_connect(module)
        if len(lb_ids) > 0:
            for index in range(0, len(lb_ids), 10):
                ids_tmp = lb_ids[index:index + 10]
                if not ids_tmp:
                    break
                id_str = ""
                for id in ids_tmp:
                    id_str += id + ','
                filters['load_balancer_id'] = id_str[:-1]

                for lb in slb.describe_load_balancers(**filters):
                    if name_prefix and not str(
                            lb.load_balancer_name).startswith(name_prefix):
                        continue
                    lbs.append(lb.read())
                    ids.append(lb.load_balancer_id)
        else:
            for lb in slb.describe_load_balancers(**filters):
                if name_prefix and not str(
                        lb.load_balancer_name).startswith(name_prefix):
                    continue
                lbs.append(lb.read())
                ids.append(lb.load_balancer_id)

        module.exit_json(changed=False, load_balancers=lbs, ids=ids)
    except Exception as e:
        module.fail_json(
            msg=
            "Unable to describe server load balancers, and got an error: {0}.".
            format(e))
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(
            load_balancer_id=dict(required=True, aliases=['lb_id']),
            listener_ports=dict(type='list', elements='int',
                                aliases=['ports']),
        ))

    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json(msg="Package 'footmark' required for this module.")

    load_balancer_id = module.params['load_balancer_id']
    ports = module.params['listener_ports']
    result = []

    if ports and (not isinstance(ports, list) or len(ports)) < 1:
        module.fail_json(
            msg=
            'backend_server_ports should be a list of backend server ports, aborting'
        )

    try:
        slb = slb_connect(module)

        # check whether server load balancer exist or not
        laod_balancer = slb.describe_load_balancers(
            load_balancer_id=load_balancer_id)
        if laod_balancer and len(laod_balancer) == 1:
            if ports:
                # list slb servers by port no.
                for port in ports:
                    for backend_server in slb.describe_backend_servers_health_status(
                            load_balancer_id=load_balancer_id, port=port):
                        result.append(get_info(backend_server))

            else:
                # list all slb servers
                for backend_server in slb.describe_backend_servers_health_status(
                        load_balancer_id=load_balancer_id):
                    result.append(get_info(backend_server))

            module.exit_json(changed=False,
                             load_balancer_id=load_balancer_id,
                             backend_servers=result)

        else:
            module.fail_json(
                msg=
                "Unable to list slb backend server health status, invalid load balancer id"
            )
    except Exception as e:
        module.fail_json(
            msg=
            "Unable to list slb backend server health status, and got an error: {0}."
            .format(e))
예제 #4
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(dict(
        load_balancer_id=dict(type='str', aliases=['lb_id'], required=True),
        vserver_group_ids=dict(type='list', aliases=['group_ids'])
    ))
    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json(msg="Package 'footmark' required for this module.")

    load_balancer_id = module.params['load_balancer_id']
    vserver_group_ids = module.params['vserver_group_ids']
    ids = []
    result = []
    all_vserver_group_ids = []

    if vserver_group_ids and (not isinstance(vserver_group_ids, list) or len(vserver_group_ids)) < 1:
        module.fail_json(msg='vserver_group_ids should be a list of vserver group ids, aborting')

    try:
        slb = slb_connect(module)
        laod_balancer = slb.describe_load_balancers(load_balancer_id=load_balancer_id)

        if laod_balancer and len(laod_balancer) == 1:

            # list all vserver groups in selected load balancer
            for vserver_group_obj in slb.describe_vserver_groups(load_balancer_id=load_balancer_id):
                all_vserver_group_ids.append(vserver_group_obj.vserver_group_id)

            # if list of vserver group id provided
            if vserver_group_ids:

                for vserver_group_id in vserver_group_ids:

                    # check whether provided vserver grooup id is valid or not
                    if vserver_group_id in all_vserver_group_ids:
                        vserver_group = slb.describe_vserver_group_attribute(vserver_group_id)
                        result.append(get_info(vserver_group))
                        ids.append(vserver_group_id)

            # list all vserver group in specified slb
            else:
                for vserver_group_id in all_vserver_group_ids:
                    vserver_group = slb.describe_vserver_group_attribute(vserver_group_id)
                    result.append(get_info(vserver_group))
                    ids.append(vserver_group.vserver_group_id)

            module.exit_json(changed=False, vserver_group_ids=ids,
                             vserver_groups=result, total=len(result))
        else:
            module.fail_json(msg="Unable to describe slb vserver groups, invalid load balancer id")
    except Exception as e:
        module.fail_json(msg=str("Unable to describe slb vserver group, error:{0}".format(e)))
예제 #5
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(dict(
        state=dict(choices=['present', 'absent'], default='present'),
        backend_servers=dict(required=True, type='list', aliases=['servers']),
        load_balancer_id=dict(required=True, aliases=['lb_id']),
    ))

    # handling region parameter which is not required by this module
    del argument_spec['alicloud_region']

    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json(msg="'footmark' is required for the module ali_slb_server. "
                             "Please install 'footmark' by using 'sudo pip install footmark'.")

    # handling region parameter which is required by common utils file to login but not required by this module
    module.params['alicloud_region'] = 'cn-hangzhou'
    slb = slb_connect(module)

    state = module.params['state']
    backend_servers = module.params['backend_servers']
    load_balancer_id = module.params['load_balancer_id']

    if state == 'present':

        if len(backend_servers) > 0:

            validate_backend_server_info(module, backend_servers, 100)

            changed, current_backend_servers = add_set_backend_servers(module, slb, load_balancer_id, backend_servers)

            result_servers = []
            for server in current_backend_servers:
                result_servers.append(get_backen_server_weight(server))
            module.exit_json(changed=changed, backend_servers=result_servers, load_balancer_id=load_balancer_id)
        else:
            module.fail_json(msg='backend servers information is mandatory to state=present')

    if len(backend_servers) > 0:

        if isinstance(backend_servers, list) is False:
            module.fail_json(msg='Invalid backend_server parameter type [%s] for state=absent.' % type(backend_servers))

        changed, backend_servers = remove_backend_servers(module, slb, load_balancer_id, backend_servers)
        result_servers = []
        for server in backend_servers:
            result_servers.append(get_backen_server_weight(server))
        module.exit_json(changed=changed, backend_servers=result_servers, load_balancer_id=load_balancer_id)
    else:
        module.fail_json(msg='backend server ID(s) information is mandatory to state=absent')
예제 #6
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(load_balancer_id=dict(type='str',
                                   aliases=['lb_id'],
                                   required=True),
             vserver_group_ids=dict(type='list',
                                    elements='str',
                                    aliases=['group_ids', 'ids']),
             name_prefix=dict(type='str')))
    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json(msg="Package 'footmark' required for this module.")

    vsg_ids = module.params['vserver_group_ids']
    name_prefix = module.params['name_prefix']

    ids = []
    vsgs = []
    names = []

    try:
        slb = slb_connect(module)
        groups = slb.describe_vserver_groups(
            **{'load_balancer_id': module.params['load_balancer_id']})

        if groups:
            for group in groups:
                if vsg_ids and group.id not in vsg_ids:
                    continue
                if name_prefix and not str(group.name).startswith(name_prefix):
                    continue
                vsgs.append(group.read())
                ids.append(group.id)
                names.append(group.name)

        module.exit_json(changed=False,
                         vserver_groups=vsgs,
                         ids=ids,
                         names=names)
    except Exception as e:
        module.fail_json(msg=str(
            "Unable to describe slb vserver groups, error:{0}".format(e)))
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(state=dict(default='present', choices=['present', 'absent']),
             resource_ids=dict(type='list', elements='str'),
             resource_type=dict(type='str', default='instance'),
             tags=dict(type='dict')))

    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json(msg='footmark required for the module ali_slb_tag.')

    slb_conn = slb_connect(module)
    slbs = slb_exists(module, slb_conn)

    if not slbs:
        module.fail_json(
            msg='No matching SLB was found based on the IDS provided.')

    # Get values of variable
    tags = module.params['tags']

    if module.params['state'] == "present":
        slb_changed = slb_conn.tag_resources(
            resource_ids=module.params['resource_ids'],
            tags=tags,
            resource_type=module.params['resource_type'])
    else:
        slb_changed = slb_conn.untag_resources(
            resource_ids=module.params['resource_ids'],
            tags=tags,
            resource_type=module.params['resource_type'])

    result = []
    for slb in slbs:
        result.append(slb.get().read())

    module.exit_json(changed=slb_changed, tags=result)
예제 #8
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(state=dict(type='str',
                        default='present',
                        choices=['present', 'absent']),
             load_balancer_id=dict(type='str',
                                   required=True,
                                   aliases=['lb_id']),
             vserver_group_name=dict(type='str',
                                     required=True,
                                     aliases=['group_name', 'name']),
             backend_servers=dict(type='list'),
             vserver_group_id=dict(type='str', aliases=['group_id']),
             purge_backend_servers=dict(type='bool', default=False),
             multi_ok=dict(type='bool', default=False)))

    module = AnsibleModule(argument_spec=argument_spec,
                           required_if=([('state', 'present',
                                          ['backend_servers'])]))

    if HAS_FOOTMARK is False:
        module.fail_json(msg='footmark required for the module ali_slb_vsg.')

    slb = slb_connect(module)
    state = module.params['state']
    lb_id = module.params['load_balancer_id']
    vsg_name = module.params['vserver_group_name']

    changed = False
    matching = None

    if not module.params['multi_ok']:
        try:
            matching_vsgs = []
            for group in slb.describe_vserver_groups(
                    **{'load_balancer_id': lb_id}):
                if group.name != vsg_name:
                    continue
                matching_vsgs.append(group)
            if len(matching_vsgs) == 1:
                matching = matching_vsgs[0]
            elif len(matching_vsgs) > 1:
                module.fail_json(
                    msg=
                    'Currently there are {0} virtual server groups that have the same name {1}. '
                    'If you would like to create anyway '
                    'please pass True to the multi_ok param.'.format(
                        len(matching_vsgs), vsg_name))
        except Exception as e:
            module.fail_json(
                msg=str("Unable to describe vserver group attribute, error:{0}"
                        .format(e)))

    if state == 'absent':
        if matching:
            try:
                changed = matching.delete()
            except Exception as e:
                module.fail_json(msg=str(
                    "Unable to delete vserver group, error: {0}".format(e)))
        module.exit_json(changed=changed, vserver_group={})

    backend_servers = module.params['backend_servers']
    check_backend_servers(module, backend_servers)

    if not matching:
        try:
            params = module.params
            params['backend_servers'] = format_backend_servers(
                backend_servers[:20])
            matching = slb.create_vserver_group(**params)
            changed = True
        except Exception as e:
            module.fail_json(
                msg=str("Unable to create vserver group error:{0}".format(e)))

    if backend_servers:
        old, new, removed = filter_backend_servers(
            matching.backend_servers['backend_server'], backend_servers)
        if old:
            try:
                if matching.modify(backend_servers=old):
                    changed = True
            except Exception as e:
                module.fail_json(
                    msg='Modify backend servers failed: {0}'.format(e))

        if new:
            try:
                if matching.add(backend_servers=new):
                    changed = True
            except Exception as e:
                module.fail_json(
                    msg='Add backend servers failed: {0}'.format(e))

        if module.params['purge_backend_servers'] and removed:
            try:
                if matching.remove(backend_servers=removed):
                    changed = True
            except Exception as e:
                module.fail_json(
                    msg='Remove backend servers failed: {0}'.format(e))
    module.exit_json(changed=changed, vserver_group=matching.get().read())
예제 #9
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(state=dict(type='str',
                        default='present',
                        choices=['present', 'absent', 'list']),
             load_balancer_id=dict(type='str'),
             vserver_group_name=dict(type='str', aliases=['group_name']),
             backend_servers=dict(type='list'),
             vserver_group_id=dict(type='str', aliases=['group_id']),
             old_backend_servers=dict(type='list'),
             new_backend_servers=dict(type='list')))

    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json(
            msg='footmark required for the module alicloud_slb_vsg.')

    slb = slb_connect(module)
    state = module.params['state']
    load_balancer_id = module.params['load_balancer_id']
    vserver_group_name = module.params['vserver_group_name']
    backend_servers = module.params['backend_servers']
    vserver_group_id = module.params['vserver_group_id']
    changed = False
    current_vserver_group = None

    if vserver_group_id:
        try:
            current_vserver_group = slb.describe_vserver_group_attribute(
                vserver_group_id)
        except Exception as e:
            module.fail_json(
                msg=str("Unable to describe vserver group attribute, error:{0}"
                        .format(e)))
    if state == "present":
        if current_vserver_group:
            set_data = []
            add_data = []
            if backend_servers:
                server_info = {}
                decode_infos = convert_to_utf8(
                    current_vserver_group.backend_servers)
                for info in decode_infos['backend_server']:
                    server_info[info['port']] = info
                for server in backend_servers:
                    if server['port'] in server_info.keys():
                        if server_info[
                                server['port']]['weight'] != server['weight']:
                            set_data.append(server)
                    else:
                        add_data.append(server)
            if set_data or vserver_group_name:
                try:
                    current_vserver_group.set_attribute(
                        backend_servers=set_data,
                        vserver_group_name=vserver_group_name)
                except Exception as e:
                    module.fail_json(msg=str(
                        "Unable to set vserver group attribute, error:{0}".
                        format(e)))
            if add_data:
                try:
                    current_vserver_group.add_backend_servers(
                        backend_servers=add_data)
                except Exception as e:
                    module.fail_json(msg=str(
                        "Unable to add vserver group backend server, error:{0}"
                        .format(e)))
            try:
                current_vserver_group = slb.describe_vserver_group_attribute(
                    vserver_group_id)
            except Exception as e:
                module.fail_json(msg=str(
                    "Unable to describe vserver group attribute, error:{0}".
                    format(e)))
            module.exit_json(changed=True,
                             vserver_group=get_info(current_vserver_group))
        else:
            try:
                current_vserver_group = slb.create_vserver_group(
                    load_balancer_id, vserver_group_name, backend_servers)
            except Exception as e:
                module.fail_json(msg=str(
                    "Unable to create vserver group error:{0}".format(e)))
            module.exit_json(changed=True,
                             vserver_group=get_info(current_vserver_group))
    if not current_vserver_group:
        module.fail_json(
            msg=
            "The specified vserver group is not exist. Please check your vserver_group_id and try again."
        )
    elif state == "list":
        module.exit_json(changed=True,
                         vserver_group=get_info(current_vserver_group))
    elif state == 'absent':
        if backend_servers:
            try:
                current_vserver_group = current_vserver_group.remove_backend_servers(
                    backend_servers)
            except Exception as e:
                module.fail_json(msg=str(
                    "Unable to remove vserver group backend server, error:{0}".
                    format(e)))
            module.exit_json(changed=True,
                             vserver_group=get_info(current_vserver_group))
        else:
            try:
                changed = current_vserver_group.delete()
            except Exception as e:
                module.fail_json(msg=str(
                    "Unable to delete vserver group, error:{0}".format(e)))
            module.exit_json(changed=changed,
                             vserver_group=get_info(current_vserver_group))
예제 #10
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(
            listener_port=dict(type='int',
                               required=True,
                               aliases=['frontend_port']),
            state=dict(type='str',
                       required=True,
                       choices=['present', 'absent', 'stopped', 'running']),
            load_balancer_id=dict(type='str', required=True, aliases=['id']),
            backend_server_port=dict(type='int', aliases=['backend_port']),
            bandwidth=dict(type='int'),
            sticky_session=dict(type='str',
                                choices=['on', 'off'],
                                default='off'),
            protocol=dict(type='str', choices=['http', 'https', 'tcp', 'udp']),
            health_check=dict(type='str', default='on', choices=['on', 'off']),
            scheduler=dict(type='str', default='wrr', choices=['wrr', 'wlc']),
            sticky_session_type=dict(type='str', choices=['insert', 'server']),
            cookie_timeout=dict(type='str'),
            cookie=dict(type='str'),
            health_check_domain=dict(type='str'),
            health_check_uri=dict(type='str', default='/'),
            health_check_connect_port=dict(type='int'),
            healthy_threshold=dict(type='int', default=3),
            unhealthy_threshold=dict(type='int', default=3),
            health_check_timeout=dict(type='int', default=5),
            health_check_interval=dict(type='int', default=2),
            health_check_http_code=dict(
                type='str',
                default='http_2xx',
                choices=['http_2xx', 'http_3xx', 'http_4xx', 'http_5xx']),
            vserver_group_id=dict(type='str'),
            persistence_timeout=dict(type='int', default=0),
            server_certificate_id=dict(type='str'),
            health_check_type=dict(type='str',
                                   default='tcp',
                                   choices=['tcp', 'http']),
        ))

    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json(
            msg='footmark required for the module ali_slb_listener.')

    slb = slb_connect(module)
    state = module.params['state']
    load_balancer_id = module.params['load_balancer_id']
    listener_port = module.params['listener_port']
    backend_server_port = module.params['backend_server_port']
    bandwidth = module.params['bandwidth']
    sticky_session = module.params['sticky_session']
    protocol = module.params['protocol']
    health_check = module.params['health_check']
    scheduler = module.params['scheduler']
    sticky_session_type = module.params['sticky_session_type']
    cookie_timeout = module.params['cookie_timeout']
    cookie = module.params['cookie']
    health_check_domain = module.params['health_check_domain']
    health_check_uri = module.params['health_check_uri']
    health_check_connect_port = module.params['health_check_connect_port']
    healthy_threshold = module.params['healthy_threshold']
    unhealthy_threshold = module.params['unhealthy_threshold']
    health_check_timeout = module.params['health_check_timeout']
    health_check_interval = module.params['health_check_interval']
    health_check_http_code = module.params['health_check_http_code']
    vserver_group_id = module.params['vserver_group_id']
    server_certificate_id = module.params['server_certificate_id']
    persistence_timeout = module.params['persistence_timeout']
    health_check_type = module.params['health_check_type']

    current_listener = slb.describe_load_balancer_listener_attribute(
        load_balancer_id, listener_port, protocol)
    changed = False
    if state == "present":
        if current_listener:
            changed = current_listener.set_attribute(
                load_balancer_id=load_balancer_id,
                bandwidth=bandwidth,
                sticky_session=sticky_session,
                protocol=protocol,
                health_check=health_check,
                scheduler=scheduler,
                sticky_session_type=sticky_session_type,
                cookie_timeout=cookie_timeout,
                cookie=cookie,
                health_check_domain=health_check_domain,
                health_check_uri=health_check_uri,
                health_check_connect_port=health_check_connect_port,
                healthy_threshold=healthy_threshold,
                unhealthy_threshold=unhealthy_threshold,
                health_check_timeout=health_check_timeout,
                health_check_interval=health_check_interval,
                health_check_http_code=health_check_http_code,
                vserver_group_id=vserver_group_id,
                server_certificate_id=server_certificate_id,
                persistence_timeout=persistence_timeout,
                health_check_type=health_check_type)
            module.exit_json(changed=changed,
                             listener=get_info(
                                 current_listener.describe_attribute(
                                     load_balancer_id, protocol)))
        else:
            changed = slb.create_load_balancer_listener(
                load_balancer_id=load_balancer_id,
                listener_port=listener_port,
                backend_server_port=backend_server_port,
                bandwidth=bandwidth,
                sticky_session=sticky_session,
                protocol=protocol,
                health_check=health_check,
                scheduler=scheduler,
                sticky_session_type=sticky_session_type,
                cookie_timeout=cookie_timeout,
                cookie=cookie,
                health_check_domain=health_check_domain,
                health_check_uri=health_check_uri,
                health_check_connect_port=health_check_connect_port,
                healthy_threshold=healthy_threshold,
                unhealthy_threshold=unhealthy_threshold,
                health_check_timeout=health_check_timeout,
                health_check_interval=health_check_interval,
                health_check_http_code=health_check_http_code,
                vserver_group_id=vserver_group_id,
                server_certificate_id=server_certificate_id,
                persistence_timeout=persistence_timeout)
            new_current_listener = slb.describe_load_balancer_listener_attribute(
                load_balancer_id, listener_port, protocol)
            module.exit_json(changed=changed,
                             listener=get_info(new_current_listener))
    if not current_listener:
        module.fail_json(
            msg=
            "The specified load balancer listener is not exist. Please check your load_balancer_id or listener_port and try again."
        )
    if state == "absent":
        changed = current_listener.delete(load_balancer_id)
        module.exit_json(changed=changed, listener=get_info(current_listener))
    if state == "running":
        if current_listener.status == "stopped":
            # start
            changed = current_listener.start(load_balancer_id)
        module.exit_json(changed=changed,
                         listener=get_info(
                             current_listener.describe_attribute(
                                 load_balancer_id, protocol)))
    if state == "stopped":
        if current_listener.status == "running":
            # stop
            changed = current_listener.stop(load_balancer_id)
        module.exit_json(changed=changed,
                         listener=get_info(
                             current_listener.describe_attribute(
                                 load_balancer_id, protocol)))
예제 #11
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(dict(
        listener_port=dict(type='int', required=True, choices=[i for i in range(1, 65536)]),
        state=dict(type='str', required=True, choices=['present', 'absent', 'list', 'stopped', 'running']),
        load_balancer_id=dict(type='str', required=True, aliases=['id']),
        backend_server_port=dict(type='int', choices=[i for i in range(1, 65536)]),
        bandwidth=dict(type='int', choices=([i for i in range(1, 1001)]).append(-1)),
        sticky_session=dict(type='str', choices=['on', 'off']),
        listener_type=dict(type='str', choices=['http', 'https', 'tcp', 'udp']),
        health_check=dict(type='str', choices=['on', 'off']),
        access_control_status=dict(type='str', choices=['on', 'off']),
        scheduler=dict(type='str', default='wrr', choices=['wrr', 'wlc']),
        source_items=dict(type='str'),
        sticky_session_type=dict(type='str', choices=['insert', 'server']),
        cookie_timeout=dict(type='str', choices=[i for i in range(1, 86401)]),
        cookie=dict(type='str'),
        health_check_domain=dict(type='str'),
        health_check_uri=dict(type='str'),
        health_check_connect_port=dict(type='int', choices=([i for i in range(1, 65536)]).append(-520)),
        healthy_threshold=dict(type='int', choices=[i for i in range(1, 11)]),
        unhealthy_threshold=dict(type='int', choices=[i for i in range(1, 11)]),
        health_check_timeout=dict(type='int', choices=[i for i in range(1, 51)]),
        health_check_interval=dict(type='int', choices=[i for i in range(1, 6)]),
        health_check_http_code=dict(type='str'),
        vserver_group_id=dict(type='str'),
        gzip=dict(type='str', default='on', choices=['on', 'off']),
        server_certificate_id=dict(type='str'),
        master_slave_server_group_id=dict(type='str'),
        persistence_timeout=dict(type='int', default=0, choices=[i for i in range(0, 3601)]),
        health_check_connect_timeout=dict(type='int', default=5, choices=[i for i in range(0, 51)]),
        ca_certificate_id=dict(type='str'),
        syn_proxy=dict(type='str', default='disable', choice=['disable', 'enable']),
        health_check_type=dict(type='str', default='tcp', choice=['tcp', 'http']),
        vserver_group=dict(type='str', default='off', choice=['on', 'off']),
        master_slave_server_group=dict(type='str', default='off', choice=['on', 'off'])
    ))

    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json(msg='footmark required for the module alicloud_slb_listener.')

    slb = slb_connect(module)
    state = module.params['state']
    load_balancer_id = module.params['load_balancer_id']
    listener_port = module.params['listener_port']
    backend_server_port = module.params['backend_server_port']
    bandwidth = module.params['bandwidth']
    sticky_session = module.params['sticky_session']
    listener_type = module.params['listener_type']
    health_check = module.params['health_check']
    access_control_status = module.params['access_control_status']
    scheduler = module.params['scheduler']
    source_items = module.params['source_items']
    sticky_session_type = module.params['sticky_session_type']
    cookie_timeout = module.params['cookie_timeout']
    cookie = module.params['cookie']
    health_check_domain = module.params['health_check_domain']
    health_check_uri = module.params['health_check_uri']
    health_check_connect_port = module.params['health_check_connect_port']
    healthy_threshold = module.params['healthy_threshold']
    unhealthy_threshold = module.params['unhealthy_threshold']
    health_check_timeout = module.params['health_check_timeout']
    health_check_interval = module.params['health_check_interval']
    health_check_http_code = module.params['health_check_http_code']
    vserver_group_id = module.params['vserver_group_id']
    gzip = module.params['gzip']
    server_certificate_id = module.params['server_certificate_id']
    master_slave_server_group_id = module.params['master_slave_server_group_id']
    persistence_timeout = module.params['persistence_timeout']
    health_check_connect_timeout = module.params['health_check_connect_timeout']
    ca_certificate_id = module.params['ca_certificate_id']
    syn_proxy = module.params['syn_proxy']
    health_check_type = module.params['health_check_type']
    vserver_group = module.params['vserver_group']
    master_slave_server_group = module.params['master_slave_server_group']

    changed = False
    current_listener = slb.describe_load_balancer_listener_attribute(load_balancer_id, listener_port, listener_type)

    if state == "present":
        if current_listener:
            if access_control_status:
                # set access_control_status
                if access_control_status == "on":
                    access_control_status = "open_white_list"
                elif access_control_status == "off":
                    access_control_status = "close"
                changed = current_listener.set_access_control_status(load_balancer_id, access_control_status)
            elif source_items:
                # add listener_white_list_item
                changed = current_listener.add_white_list_item(load_balancer_id, source_items)
            else:
                # set attribute
                changed = current_listener.set_attribute(load_balancer_id=load_balancer_id,
                                                         bandwidth=bandwidth,
                                                         sticky_session=sticky_session,
                                                         listener_type=listener_type,
                                                         health_check=health_check,
                                                         scheduler=scheduler,
                                                         sticky_session_type=sticky_session_type,
                                                         cookie_timeout=cookie_timeout,
                                                         cookie=cookie,
                                                         health_check_domain=health_check_domain,
                                                         health_check_uri=health_check_uri,
                                                         health_check_connect_port=health_check_connect_port,
                                                         healthy_threshold=healthy_threshold,
                                                         unhealthy_threshold=unhealthy_threshold,
                                                         health_check_timeout=health_check_timeout,
                                                         health_check_interval=health_check_interval,
                                                         health_check_http_code=health_check_http_code,
                                                         vserver_group_id=vserver_group_id,
                                                         gzip=gzip,
                                                         server_certificate_id=server_certificate_id,
                                                         master_slave_server_group_id=master_slave_server_group_id,
                                                         persistence_timeout=persistence_timeout,
                                                         health_check_connect_timeout=health_check_connect_timeout,
                                                         ca_certificate_id=ca_certificate_id,
                                                         syn_proxy=syn_proxy,
                                                         health_check_type=health_check_type,
                                                         vserver_group=vserver_group,
                                                         master_slave_server_group=master_slave_server_group)
            module.exit_json(changed=changed, listener=get_info(current_listener.describe_attribute(load_balancer_id, listener_type)))
        else:
            changed = slb.create_load_balancer_listener(load_balancer_id=load_balancer_id,
                                                        listener_port=listener_port,
                                                        backend_server_port=backend_server_port,
                                                        bandwidth=bandwidth,
                                                        sticky_session=sticky_session,
                                                        listener_type=listener_type,
                                                        health_check=health_check,
                                                        scheduler=scheduler,
                                                        sticky_session_type=sticky_session_type,
                                                        cookie_timeout=cookie_timeout,
                                                        cookie=cookie,
                                                        health_check_domain=health_check_domain,
                                                        health_check_uri=health_check_uri,
                                                        health_check_connect_port=health_check_connect_port,
                                                        healthy_threshold=healthy_threshold,
                                                        unhealthy_threshold=unhealthy_threshold,
                                                        health_check_timeout=health_check_timeout,
                                                        health_check_interval=health_check_interval,
                                                        health_check_http_code=health_check_http_code,
                                                        vserver_group_id=vserver_group_id,
                                                        gzip=gzip,
                                                        server_certificate_id=server_certificate_id,
                                                        master_slave_server_group_id=master_slave_server_group_id,
                                                        persistence_timeout=persistence_timeout,
                                                        health_check_connect_timeout=health_check_connect_timeout,
                                                        ca_certificate_id=ca_certificate_id)
            new_current_listener = slb.describe_load_balancer_listener_attribute(load_balancer_id, listener_port, listener_type)
            module.exit_json(changed=changed, listener=get_info(new_current_listener))
    if not current_listener:
        module.fail_json(msg="The specified load balancer listener is not exist. Please check your load_balancer_id or listener_port and try again.")
    if state == "absent":
        if source_items:
            # remove listener white list item
            changed = current_listener.remove_white_list_item(load_balancer_id, source_items)
            module.exit_json(changed=changed, listener=get_info(current_listener.describe_attribute(load_balancer_id, listener_type)))
        # delete
        changed = current_listener.delete(load_balancer_id)
        module.exit_json(changed=changed, listener=get_info(current_listener))
    if state == "running":
        # start
        changed = current_listener.start(load_balancer_id)
        module.exit_json(changed=changed, listener=get_info(current_listener.describe_attribute(load_balancer_id, listener_type)))
    if state == "stopped":
        # stop
        changed = current_listener.stop(load_balancer_id)
        module.exit_json(changed=changed, listener=get_info(current_listener.describe_attribute(load_balancer_id, listener_type)))
    if state == 'list':
        # list attribute
        module.exit_json(changed=True, listener=get_info(current_listener))
예제 #12
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(dict(
        internet_charge_type=dict(type='str', required=False, choices=['paybybandwidth', 'paybytraffic'], default='paybytraffic'),
        state=dict(type='str', required=True, choices=['present', 'absent', 'running', 'stopped']),
        load_balancer_name=dict(type='str', required=False, aliases=['name']),
        load_balancer_id=dict(type='str', required=False, aliases=['id']),
        is_internet=dict(type='bool', required=False, default=True),
        bandwidth=dict(type='int', required=False, default=1),
        vswitch_id=dict(type='str', required=False, aliases=['subnet_id']),
        master_zone_id=dict(type='str', required=False),
        slave_zone_id=dict(type='str', required=False)
    ))

    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json(msg='footmark required for the module alicloud_slb_lb.')

    slb = slb_connect(module)
    state = module.params['state']
    load_balancer_id = module.params['load_balancer_id']
    load_balancer_name = module.params['load_balancer_name']
    is_internet = module.params['is_internet']
    vswitch_id = module.params['vswitch_id']
    master_zone_id = module.params['master_zone_id']
    slave_zone_id = module.params['slave_zone_id']
    internet_charge_type = module.params['internet_charge_type']
    bandwidth = module.params['bandwidth']

    changed = False
    cur_slb = None

    if load_balancer_id and load_balancer_name:
        name_test = ""
    else:
        name_test = load_balancer_name
    res_objs = slb.describe_load_balancers(load_balancer_id=load_balancer_id, load_balancer_name=name_test)
    if len(res_objs) == 1:
        cur_slb = slb.describe_load_balancer_attribute(res_objs[0].id)

    if state == "present":
        if cur_slb:
            if load_balancer_name != cur_slb.name:
                changed = cur_slb.modify_name(load_balancer_name)
                if changed:
                    cur_slb.load_balancer_name = load_balancer_name

            if internet_charge_type != cur_slb.internet_charge_type or \
                    (cur_slb.internet_charge_type == "paybybandwidth" and bandwidth != cur_slb.bandwidth):
                print (cur_slb.__dict__)
                print (cur_slb.internet_charge_type, cur_slb.bandwidth)
                changed = cur_slb.modify_spec(internet_charge_type=internet_charge_type, bandwidth=bandwidth)
                if changed:
                    cur_slb.internet_charge_type = internet_charge_type
                    cur_slb.bandwidth = bandwidth
        else:
            client_token = "Ansible-Alicloud-%s-%s" % (hash(str(module.params)), str(time.time()))
            address_type = "internet"
            if not is_internet:
                address_type = "intranet"
            cur_slb = slb.create_load_balancer(load_balancer_name=load_balancer_name,
                                               address_type=address_type, vswitch_id=vswitch_id,
                                               internet_charge_type=internet_charge_type,
                                               master_zone_id=master_zone_id, slave_zone_id=slave_zone_id,
                                               bandwidth=bandwidth, client_token=client_token)
            changed = True
        module.exit_json(changed=changed, load_balancer=get_info(cur_slb), load_balancer_id=cur_slb.id)

    if not cur_slb:
        module.fail_json(msg="The specified load balancer is not exist. Please check your load_balancer_id or load_balancer_name and try again.")

    if state == "absent":
        changed = cur_slb.delete()
        module.exit_json(changed=changed, load_balancer_id=cur_slb.load_balancer_id)
    if state == "running":
        if cur_slb.status != "active":
            changed = cur_slb.set_status("active")
        if changed:
            cur_slb.load_balancer_status = "active"
        module.exit_json(changed=changed, load_balancer=get_info(cur_slb), load_balancer_id=cur_slb.load_balancer_id)

    if state == "stopped":
        if cur_slb.status != "inactive":
            changed = cur_slb.set_status("inactive")
        if changed:
            cur_slb.load_balancer_status = "inactive"
        module.exit_json(changed=changed, load_balancer=get_info(cur_slb), load_balancer_id=cur_slb.load_balancer_id)
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(internet_charge_type=dict(
            type='str',
            choices=['PayByBandwidth', 'PayByTraffic'],
            default='PayByTraffic'),
             state=dict(type='str',
                        choices=['present', 'absent', 'running', 'stopped'],
                        default='present'),
             load_balancer_name=dict(type='str',
                                     required=True,
                                     aliases=['name', 'lb_name']),
             load_balancer_id=dict(type='str', aliases=['id']),
             is_internet=dict(type='bool', default=False),
             bandwidth=dict(type='int', default=1),
             vswitch_id=dict(type='str', aliases=['subnet_id']),
             master_zone_id=dict(type='str'),
             slave_zone_id=dict(type='str'),
             load_balancer_spec=dict(type='str',
                                     aliases=['spec', 'lb_spec'],
                                     choices=[
                                         'slb.s1.small', 'slb.s2.small',
                                         'slb.s2.medium', 'slb.s3.small',
                                         'slb.s3.medium', 'slb.s3.large'
                                     ]),
             multi_ok=dict(type='bool', default=False),
             tags=dict(type='dict'),
             purge_tags=dict(type='bool', default=False)))

    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json(msg='footmark required for the module ali_slb_lb.')

    slb = slb_connect(module)
    state = module.params['state']
    name = module.params['load_balancer_name']
    load_balancer_id = module.params['load_balancer_id']
    is_internet = module.params['is_internet']
    internet_charge_type = str(module.params['internet_charge_type']).lower()

    changed = False
    matching = None

    filters = {}
    if name:
        filters['load_balancer_name'] = name
    if load_balancer_id:
        filters['load_balancer_id'] = load_balancer_id
    if not module.params['multi_ok']:
        try:
            matching_slbs = slb.describe_load_balancers(**filters)
            if len(matching_slbs) == 1:
                matching = matching_slbs[0]
            elif len(matching_slbs) > 1:
                module.fail_json(
                    msg=
                    'Currently there are {0} Load Balancers that have the same name {1}. '
                    'If you would like to create anyway '
                    'please pass True to the multi_ok param.'.format(
                        len(matching_slbs), name))
        except Exception as e:
            module.fail_json(
                msg="Failed to describe Load Balancers: {0}".format(e))

    if state == "absent":
        if matching:
            try:
                changed = matching.delete()
            except Exception as e:
                module.fail_json(
                    msg="Failed to delete Load Balancers: {0}".format(e))
        module.exit_json(changed=changed, load_balancer={})

    if state == "present":
        if not matching:
            params = module.params
            params['internet_charge_type'] = internet_charge_type
            params['client_token'] = "Ansible-Alicloud-%s-%s" % (hash(
                str(module.params)), str(time.time()))
            address_type = "intranet"
            if is_internet:
                address_type = "internet"
            params['address_type'] = address_type
            try:
                matching = slb.create_load_balancer(**params)
                changed = True
            except Exception as e:
                module.fail_json(
                    msg="Failed to create Load Balancer: {0}".format(e))

    if not matching:
        module.fail_json(
            msg=
            "The specified load balancer {0} is not exist. Please check your name and try again."
            .format(name))

    if not internet_charge_type:
        internet_charge_type = str(matching.internet_charge_type).lower()

    bandwidth = module.params['bandwidth']
    if not bandwidth:
        bandwidth = matching.bandwidth
    try:
        if matching.modify_spec(internet_charge_type=internet_charge_type,
                                bandwidth=bandwidth):
            changed = True
        matching = matching.get()
    except Exception as e:
        module.fail_json(
            msg="Failed to modify Load Balancer spec: {0}".format(e))

    status = "active"
    if state == "stopped":
        status = "inactive"

    try:
        if matching.set_status(status):
            changed = True
    except Exception as e:
        module.fail_json(
            msg="Failed to modify Load Balancer status: {0}".format(e))

    tags = module.params['tags']
    if module.params['purge_tags']:
        if not tags:
            tags = matching.tags
        try:
            if matching.remove_tags(tags):
                changed = True
            module.exit_json(changed=changed,
                             load_balancer=matching.get().read())
        except Exception as e:
            module.fail_json(msg="{0}".format(e))

    if tags:
        try:
            if matching.add_tags(tags):
                changed = True
        except Exception as e:
            module.fail_json(msg="{0}".format(e))

    module.exit_json(changed=changed, load_balancer=matching.get().read())
예제 #14
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(load_balancer_name=dict(type='list', aliases=['name']),
             load_balancer_ids=dict(type='list', aliases=['ids'])))

    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json(msg="Package 'footmark' required for this module.")

    load_balancer_ids = module.params['load_balancer_ids']
    load_balancer_names = module.params['load_balancer_name']
    result = []
    ids = []

    try:
        slb = slb_connect(module)

        if load_balancer_ids and (not isinstance(load_balancer_ids, list)
                                  or len(load_balancer_ids)) < 1:
            module.fail_json(
                msg=
                'load_balancer_ids should be a list of load balancer ids, aborting'
            )

        if load_balancer_names and (not isinstance(load_balancer_names, list)
                                    or len(load_balancer_names)) < 1:
            module.fail_json(
                msg=
                'load_balancer_name should be a list of load balancer name, aborting'
            )

        # list load balancers by name
        if load_balancer_names:
            result = []
            ids = []
            for load_balancer_name in load_balancer_names:
                for slb_res in slb.describe_load_balancers(
                        load_balancer_name=load_balancer_name):
                    result.append(get_info(slb_res))
                    ids.append(slb_res.load_balancer_id)

        # list load balancers by ids
        elif load_balancer_ids:
            slb_lb_ids = ",".join(load_balancer_ids)
            for slb_res in slb.describe_load_balancers(
                    load_balancer_id=slb_lb_ids):
                result.append(get_info(slb_res))
                ids.append(slb_res.load_balancer_id)
        # list all load balancers
        else:
            for slb_res in slb.describe_load_balancers():
                result.append(get_info(slb_res))
                ids.append(slb_res.load_balancer_id)

        module.exit_json(changed=False,
                         load_balancer_ids=ids,
                         load_balancers=result,
                         total=len(result))
    except Exception as e:
        module.fail_json(
            msg=
            "Unable to describe server load balancers, and got an error: {0}.".
            format(e))
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(internet_charge_type=dict(
            type='str',
            required=False,
            choices=['paybybandwidth', 'paybytraffic'],
            default='paybytraffic'),
             state=dict(type='str',
                        required=True,
                        choices=['present', 'absent', 'list']),
             load_balancer_name=dict(type='str',
                                     required=False,
                                     aliases=['name']),
             load_balancer_id=dict(type='str',
                                   required=False,
                                   aliases=['ecs_slb']),
             address_type=dict(type='str',
                               required=False,
                               default='internet',
                               choices=['internet', 'intranet']),
             bandwidth=dict(type='int', required=False, default=1),
             vswitch_id=dict(type='str', required=False),
             load_balancer_status=dict(type='str',
                                       required=False,
                                       choices=['active', 'inactive']),
             master_zone_id=dict(type='str', required=False),
             slave_zone_id=dict(type='str', required=False)))

    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json(
            msg='footmark required for the module alicloud_slb_lb.')

    slb = slb_connect(module)
    state = module.params['state']
    load_balancer_id = module.params['load_balancer_id']
    load_balancer_name = module.params['load_balancer_name']
    address_type = module.params['address_type']
    vswitch_id = module.params['vswitch_id']
    master_zone_id = module.params['master_zone_id']
    slave_zone_id = module.params['slave_zone_id']
    internet_charge_type = module.params['internet_charge_type']
    load_balancer_status = module.params['load_balancer_status']
    bandwidth = module.params['bandwidth']
    res_objs = []
    changed = False
    cur_slb = None

    if load_balancer_id and load_balancer_name:
        name_test = ""
    else:
        name_test = load_balancer_name
    res_objs = slb.describe_load_balancers(load_balancer_id=load_balancer_id,
                                           load_balancer_name=name_test)
    if len(res_objs) == 1:
        cur_slb = res_objs[0]

    if state == "absent":
        if cur_slb:
            changed = cur_slb.delete()
            module.exit_json(changed=changed,
                             load_balancer_id=cur_slb.load_balancer_id)
        else:
            module.fail_json(
                msg=
                "The specified load balancer is not exist. Please check your load_balancer_id or load_balancer_name and try again."
            )
    elif state == "present":
        if load_balancer_status and cur_slb:
            # set status
            changed = cur_slb.set_status(load_balancer_status)
            if changed:
                cur_slb.load_balancer_status = load_balancer_status
            module.exit_json(changed=changed,
                             load_balancer=get_info(cur_slb),
                             load_balancer_id=cur_slb.load_balancer_id)
        elif load_balancer_name and cur_slb:
            # set name
            changed = cur_slb.modify_name(load_balancer_name)
            if changed:
                cur_slb.load_balancer_name = load_balancer_name
            module.exit_json(changed=changed,
                             load_balancer=get_info(cur_slb),
                             load_balancer_id=cur_slb.load_balancer_id)
        elif (internet_charge_type or bandwidth) and cur_slb:
            # set spec
            changed = cur_slb.modify_spec(
                internet_charge_type=internet_charge_type, bandwidth=bandwidth)
            if changed:
                cur_slb.internet_charge_type = internet_charge_type
                cur_slb.bandwidth = bandwidth
            module.exit_json(changed=changed,
                             load_balancer=get_info(cur_slb),
                             load_balancer_id=cur_slb.load_balancer_id)
        elif not cur_slb:
            res_obj = slb.create_load_balancer(
                load_balancer_name=load_balancer_name,
                address_type=address_type,
                vswitch_id=vswitch_id,
                internet_charge_type=internet_charge_type,
                master_zone_id=master_zone_id,
                slave_zone_id=slave_zone_id,
                bandwidth=bandwidth)
            changed = True
            module.exit_json(changed=changed,
                             load_balancer=get_info(res_obj),
                             load_balancer_id=res_obj.load_balancer_id)
        else:
            module.exit_json(changed=changed,
                             load_balancer=get_info(cur_slb),
                             load_balancer_id=cur_slb.load_balancer_id)
    elif state == "list":
        load_balancers = []
        for res_obj in res_objs:
            load_balancers.append(get_info(res_obj))
        module.exit_json(changed=True, load_balancers=load_balancers)