Esempio n. 1
0
def validate_servers(module, servers):
    for item in servers:
        for key in item:
            if key not in VALID_SERVER_FIELDS:
                module.fail_json(
                    msg="invalid server field (%s), must be one of: %s" %
                    (key, ','.join(VALID_SERVER_FIELDS)))

        # validate the server name is present
        if 'server' not in item:
            module.fail_json(
                msg="server definitions must define the server field")

        # validate the port number is present and an integer
        if 'port' in item:
            try:
                item['port'] = int(item['port'])
            except:
                module.fail_json(
                    msg="server port definitions must be integers")
        else:
            module.fail_json(
                msg="server definitions must define the port field")

        # convert the status to the internal API integer value
        if 'status' in item:
            item['status'] = axapi_enabled_disabled(item['status'])
        else:
            item['status'] = 1
Esempio n. 2
0
def validate_ports(module, ports):
    for item in ports:
        for key in item:
            if key not in VALID_PORT_FIELDS:
                module.fail_json(msg="invalid port field (%s), must be one of: %s" % (key, ",".join(VALID_PORT_FIELDS)))

        # validate the port number is present and an integer
        if "port_num" in item:
            try:
                item["port_num"] = int(item["port_num"])
            except:
                module.fail_json(msg="port_num entries in the port definitions must be integers")
        else:
            module.fail_json(msg="port definitions must define the port_num field")

        # validate the port protocol is present, and convert it to
        # the internal API integer value (and validate it)
        if "protocol" in item:
            protocol = axapi_get_port_protocol(item["protocol"])
            if not protocol:
                module.fail_json(msg="invalid port protocol, must be one of: %s" % ",".join(AXAPI_PORT_PROTOCOLS))
            else:
                item["protocol"] = protocol
        else:
            module.fail_json(msg="port definitions must define the port protocol (%s)" % ",".join(AXAPI_PORT_PROTOCOLS))

        # convert the status to the internal API integer value
        if "status" in item:
            item["status"] = axapi_enabled_disabled(item["status"])
        else:
            item["status"] = 1
def validate_ports(module, ports):
    for item in ports:
        for key in item:
            if key not in VALID_PORT_FIELDS:
                module.fail_json(msg="invalid port field (%s), must be one of: %s" % (key, ','.join(VALID_PORT_FIELDS)))

        # validate the port number is present and an integer
        if 'port' in item:
            try:
                item['port'] = int(item['port'])
            except:
                module.fail_json(msg="port definitions must be integers")
        else:
            module.fail_json(msg="port definitions must define the port field")

        # validate the port protocol is present, and convert it to
        # the internal API integer value (and validate it)
        if 'protocol' in item:
            protocol = axapi_get_vport_protocol(item['protocol'])
            if not protocol:
                module.fail_json(msg="invalid port protocol, must be one of: %s" % ','.join(AXAPI_VPORT_PROTOCOLS))
            else:
                item['protocol'] = protocol
        else:
            module.fail_json(msg="port definitions must define the port protocol (%s)" % ','.join(AXAPI_VPORT_PROTOCOLS))

        # convert the status to the internal API integer value
        if 'status' in item:
            item['status'] = axapi_enabled_disabled(item['status'])
        else:
            item['status'] = 1

        # ensure the service_group field is at least present
        if 'service_group' not in item:
            item['service_group'] = ''
Esempio n. 4
0
def validate_servers(module, servers):
    for item in servers:
        for key in item:
            if key not in VALID_SERVER_FIELDS:
                module.fail_json(msg="invalid server field (%s), must be one of: %s" % (key, ','.join(VALID_SERVER_FIELDS)))

        # validate the server name is present
        if 'server' not in item:
            module.fail_json(msg="server definitions must define the server field")

        # validate the port number is present and an integer
        if 'port' in item:
            try:
                item['port'] = int(item['port'])
            except:
                module.fail_json(msg="server port definitions must be integers")
        else:
            module.fail_json(msg="server definitions must define the port field")

        # convert the status to the internal API integer value
        if 'status' in item:
            item['status'] = axapi_enabled_disabled(item['status'])
        else:
            item['status'] = 1
Esempio n. 5
0
def main():
    argument_spec = a10_argument_spec()
    argument_spec.update(url_argument_spec())
    argument_spec.update(
        dict(
            state=dict(type='str',
                       default='present',
                       choices=['present', 'absent']),
            virtual_server=dict(type='str',
                                aliases=['vip', 'virtual'],
                                required=True),
            virtual_server_ip=dict(type='str',
                                   aliases=['ip', 'address'],
                                   required=True),
            virtual_server_status=dict(type='str',
                                       default='enabled',
                                       aliases=['status'],
                                       choices=['enabled', 'disabled']),
            virtual_server_ports=dict(type='list', required=True),
            partition=dict(type='str', default=[]),
        ))

    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=False)

    host = module.params['host']
    username = module.params['username']
    password = module.params['password']
    partition = module.params['partition']
    state = module.params['state']
    write_config = module.params['write_config']
    slb_virtual = module.params['virtual_server']
    slb_virtual_ip = module.params['virtual_server_ip']
    slb_virtual_status = module.params['virtual_server_status']
    slb_virtual_ports = module.params['virtual_server_ports']

    if slb_virtual is None:
        module.fail_json(msg='virtual_server is required')

    validate_ports(module, slb_virtual_ports)

    axapi_base_url = 'https://%s/services/rest/V2.1/?format=json' % host
    session_url = axapi_authenticate(module, axapi_base_url, username,
                                     password)

    slb_server_partition = axapi_call(
        module, session_url + '&method=system.partition.active',
        json.dumps({'name': partition}))
    slb_virtual_data = axapi_call(
        module, session_url + '&method=slb.virtual_server.search',
        json.dumps({'name': slb_virtual}))
    slb_virtual_exists = not axapi_failure(slb_virtual_data)

    changed = False
    if state == 'present':
        json_post = {
            'virtual_server': {
                'name': slb_virtual,
                'address': slb_virtual_ip,
                'status': axapi_enabled_disabled(slb_virtual_status),
                'vport_list': slb_virtual_ports,
            }
        }

        # before creating/updating we need to validate that any
        # service groups defined in the ports list exist since
        # since the API will still create port definitions for
        # them while indicating a failure occurred
        checked_service_groups = []
        for port in slb_virtual_ports:
            if 'service_group' in port and port[
                    'service_group'] not in checked_service_groups:
                # skip blank service group entries
                if port['service_group'] == '':
                    continue
                result = axapi_call(
                    module, session_url + '&method=slb.service_group.search',
                    json.dumps({'name': port['service_group']}))
                if axapi_failure(result):
                    module.fail_json(
                        msg=
                        "the service group %s specified in the ports list does not exist"
                        % port['service_group'])
                checked_service_groups.append(port['service_group'])

        if not slb_virtual_exists:
            result = axapi_call(
                module, session_url + '&method=slb.virtual_server.create',
                json.dumps(json_post))
            if axapi_failure(result):
                module.fail_json(
                    msg="failed to create the virtual server: %s" %
                    result['response']['err']['msg'])
            changed = True
        else:

            def needs_update(src_ports, dst_ports):
                '''
                Checks to determine if the port definitions of the src_ports
                array are in or different from those in dst_ports. If there is
                a difference, this function returns true, otherwise false.
                '''
                for src_port in src_ports:
                    found = False
                    different = False
                    for dst_port in dst_ports:
                        if src_port['port'] == dst_port['port']:
                            found = True
                            for valid_field in VALID_PORT_FIELDS:
                                if src_port[valid_field] != dst_port[
                                        valid_field]:
                                    different = True
                                    break
                            if found or different:
                                break
                    if not found or different:
                        return True
                # every port from the src exists in the dst, and none of them were different
                return False

            defined_ports = slb_virtual_data.get('virtual_server',
                                                 {}).get('vport_list', [])

            # we check for a needed update both ways, in case ports
            # are missing from either the ones specified by the user
            # or from those on the device
            if needs_update(defined_ports, slb_virtual_ports) or needs_update(
                    slb_virtual_ports, defined_ports):
                result = axapi_call(
                    module, session_url + '&method=slb.virtual_server.update',
                    json.dumps(json_post))
                if axapi_failure(result):
                    module.fail_json(
                        msg="failed to create the virtual server: %s" %
                        result['response']['err']['msg'])
                changed = True

        # if we changed things, get the full info regarding
        # the service group for the return data below
        if changed:
            result = axapi_call(
                module, session_url + '&method=slb.virtual_server.search',
                json.dumps({'name': slb_virtual}))
        else:
            result = slb_virtual_data
    elif state == 'absent':
        if slb_virtual_exists:
            result = axapi_call(
                module, session_url + '&method=slb.virtual_server.delete',
                json.dumps({'name': slb_virtual}))
            changed = True
        else:
            result = dict(msg="the virtual server was not present")

    # if the config has changed, save the config unless otherwise requested
    if changed and write_config:
        write_result = axapi_call(
            module, session_url + '&method=system.action.write_memory')
        if axapi_failure(write_result):
            module.fail_json(msg="failed to save the configuration: %s" %
                             write_result['response']['err']['msg'])

    # log out of the session nicely and exit
    axapi_call(module, session_url + '&method=session.close')
    module.exit_json(changed=changed, content=result)
Esempio n. 6
0
def main():
    argument_spec = a10_argument_spec()
    argument_spec.update(url_argument_spec())
    argument_spec.update(
        dict(
            state=dict(type='str', default='present', choices=['present', 'absent']),
            virtual_server=dict(type='str', aliases=['vip', 'virtual'], required=True),
            virtual_server_ip=dict(type='str', aliases=['ip', 'address'], required=True),
            virtual_server_status=dict(type='str', default='enabled', aliases=['status'], choices=['enabled', 'disabled']),
            virtual_server_ports=dict(type='list', required=True),
            partition=dict(type='str', default=[]),
        )
    )

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=False
    )

    host = module.params['host']
    username = module.params['username']
    password = module.params['password']
    partition = module.params['partition']
    state = module.params['state']
    write_config = module.params['write_config']
    slb_virtual = module.params['virtual_server']
    slb_virtual_ip = module.params['virtual_server_ip']
    slb_virtual_status = module.params['virtual_server_status']
    slb_virtual_ports = module.params['virtual_server_ports']

    if slb_virtual is None:
        module.fail_json(msg='virtual_server is required')

    validate_ports(module, slb_virtual_ports)

    axapi_base_url = 'https://%s/services/rest/V2.1/?format=json' % host
    session_url = axapi_authenticate(module, axapi_base_url, username, password)

    axapi_call(module, session_url + '&method=system.partition.active', json.dumps({'name': partition}))
    slb_virtual_data = axapi_call(module, session_url + '&method=slb.virtual_server.search', json.dumps({'name': slb_virtual}))
    slb_virtual_exists = not axapi_failure(slb_virtual_data)

    changed = False
    if state == 'present':
        json_post = {
            'virtual_server': {
                'name': slb_virtual,
                'address': slb_virtual_ip,
                'status': axapi_enabled_disabled(slb_virtual_status),
                'vport_list': slb_virtual_ports,
            }
        }

        # before creating/updating we need to validate that any
        # service groups defined in the ports list exist since
        # since the API will still create port definitions for
        # them while indicating a failure occurred
        checked_service_groups = []
        for port in slb_virtual_ports:
            if 'service_group' in port and port['service_group'] not in checked_service_groups:
                # skip blank service group entries
                if port['service_group'] == '':
                    continue
                result = axapi_call(module, session_url + '&method=slb.service_group.search', json.dumps({'name': port['service_group']}))
                if axapi_failure(result):
                    module.fail_json(msg="the service group %s specified in the ports list does not exist" % port['service_group'])
                checked_service_groups.append(port['service_group'])

        if not slb_virtual_exists:
            result = axapi_call(module, session_url + '&method=slb.virtual_server.create', json.dumps(json_post))
            if axapi_failure(result):
                module.fail_json(msg="failed to create the virtual server: %s" % result['response']['err']['msg'])
            changed = True
        else:
            def needs_update(src_ports, dst_ports):
                '''
                Checks to determine if the port definitions of the src_ports
                array are in or different from those in dst_ports. If there is
                a difference, this function returns true, otherwise false.
                '''
                for src_port in src_ports:
                    found = False
                    different = False
                    for dst_port in dst_ports:
                        if src_port['port'] == dst_port['port']:
                            found = True
                            for valid_field in VALID_PORT_FIELDS:
                                if src_port[valid_field] != dst_port[valid_field]:
                                    different = True
                                    break
                            if found or different:
                                break
                    if not found or different:
                        return True
                # every port from the src exists in the dst, and none of them were different
                return False

            defined_ports = slb_virtual_data.get('virtual_server', {}).get('vport_list', [])

            # we check for a needed update both ways, in case ports
            # are missing from either the ones specified by the user
            # or from those on the device
            if needs_update(defined_ports, slb_virtual_ports) or needs_update(slb_virtual_ports, defined_ports):
                result = axapi_call(module, session_url + '&method=slb.virtual_server.update', json.dumps(json_post))
                if axapi_failure(result):
                    module.fail_json(msg="failed to create the virtual server: %s" % result['response']['err']['msg'])
                changed = True

        # if we changed things, get the full info regarding
        # the service group for the return data below
        if changed:
            result = axapi_call(module, session_url + '&method=slb.virtual_server.search', json.dumps({'name': slb_virtual}))
        else:
            result = slb_virtual_data
    elif state == 'absent':
        if slb_virtual_exists:
            result = axapi_call(module, session_url + '&method=slb.virtual_server.delete', json.dumps({'name': slb_virtual}))
            changed = True
        else:
            result = dict(msg="the virtual server was not present")

    # if the config has changed, save the config unless otherwise requested
    if changed and write_config:
        write_result = axapi_call(module, session_url + '&method=system.action.write_memory')
        if axapi_failure(write_result):
            module.fail_json(msg="failed to save the configuration: %s" % write_result['response']['err']['msg'])

    # log out of the session nicely and exit
    axapi_call(module, session_url + '&method=session.close')
    module.exit_json(changed=changed, content=result)
Esempio n. 7
0
def main():
    argument_spec = a10_argument_spec()
    argument_spec.update(url_argument_spec())
    argument_spec.update(
        dict(
            state=dict(type='str',
                       default='present',
                       choices=['present', 'absent']),
            server_name=dict(type='str', aliases=['server'], required=True),
            server_ip=dict(type='str', aliases=['ip', 'address']),
            server_status=dict(type='str',
                               default='enabled',
                               aliases=['status'],
                               choices=['enabled', 'disabled']),
            server_ports=dict(type='list', aliases=['port'], default=[]),
            partition=dict(type='str', default=[]),
        ))

    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=False)

    host = module.params['host']
    partition = module.params['partition']
    username = module.params['username']
    password = module.params['password']
    state = module.params['state']
    write_config = module.params['write_config']
    slb_server = module.params['server_name']
    slb_server_ip = module.params['server_ip']
    slb_server_status = module.params['server_status']
    slb_server_ports = module.params['server_ports']

    if slb_server is None:
        module.fail_json(msg='server_name is required')

    axapi_base_url = 'https://%s/services/rest/V2.1/?format=json' % host
    session_url = axapi_authenticate(module, axapi_base_url, username,
                                     password)

    # validate the ports data structure
    validate_ports(module, slb_server_ports)

    json_post = {
        'server': {
            'name': slb_server,
        }
    }

    # add optional module parameters
    if slb_server_ip:
        json_post['server']['host'] = slb_server_ip

    if slb_server_ports:
        json_post['server']['port_list'] = slb_server_ports

    if slb_server_status:
        json_post['server']['status'] = axapi_enabled_disabled(
            slb_server_status)

    slb_server_partition = axapi_call(
        module, session_url + '&method=system.partition.active',
        json.dumps({'name': partition}))

    slb_server_data = axapi_call(module,
                                 session_url + '&method=slb.server.search',
                                 json.dumps({'name': slb_server}))
    slb_server_exists = not axapi_failure(slb_server_data)

    changed = False
    if state == 'present':
        if not slb_server_exists:
            if not slb_server_ip:
                module.fail_json(
                    msg='you must specify an IP address when creating a server'
                )

            result = axapi_call(module,
                                session_url + '&method=slb.server.create',
                                json.dumps(json_post))
            if axapi_failure(result):
                module.fail_json(msg="failed to create the server: %s" %
                                 result['response']['err']['msg'])
            changed = True
        else:

            def port_needs_update(src_ports, dst_ports):
                '''
                Checks to determine if the port definitions of the src_ports
                array are in or different from those in dst_ports. If there is
                a difference, this function returns true, otherwise false.
                '''
                for src_port in src_ports:
                    found = False
                    different = False
                    for dst_port in dst_ports:
                        if src_port['port_num'] == dst_port['port_num']:
                            found = True
                            for valid_field in VALID_PORT_FIELDS:
                                if src_port[valid_field] != dst_port[
                                        valid_field]:
                                    different = True
                                    break
                            if found or different:
                                break
                    if not found or different:
                        return True
                # every port from the src exists in the dst, and none of them were different
                return False

            def status_needs_update(current_status, new_status):
                '''
                Check to determine if we want to change the status of a server.
                If there is a difference between the current status of the server and
                the desired status, return true, otherwise false.
                '''
                if current_status != new_status:
                    return True
                return False

            defined_ports = slb_server_data.get('server',
                                                {}).get('port_list', [])
            current_status = slb_server_data.get('server', {}).get('status')

            # we check for a needed update several ways
            # - in case ports are missing from the ones specified by the user
            # - in case ports are missing from those on the device
            # - in case we are change the status of a server
            if port_needs_update(
                    defined_ports, slb_server_ports) or port_needs_update(
                        slb_server_ports,
                        defined_ports) or status_needs_update(
                            current_status,
                            axapi_enabled_disabled(slb_server_status)):
                result = axapi_call(module,
                                    session_url + '&method=slb.server.update',
                                    json.dumps(json_post))
                if axapi_failure(result):
                    module.fail_json(msg="failed to update the server: %s" %
                                     result['response']['err']['msg'])
                changed = True

        # if we changed things, get the full info regarding
        # the service group for the return data below
        if changed:
            result = axapi_call(module,
                                session_url + '&method=slb.server.search',
                                json.dumps({'name': slb_server}))
        else:
            result = slb_server_data
    elif state == 'absent':
        if slb_server_exists:
            result = axapi_call(module,
                                session_url + '&method=slb.server.delete',
                                json.dumps({'name': slb_server}))
            changed = True
        else:
            result = dict(msg="the server was not present")

    # if the config has changed, save the config unless otherwise requested
    if changed and write_config:
        write_result = axapi_call(
            module, session_url + '&method=system.action.write_memory')
        if axapi_failure(write_result):
            module.fail_json(msg="failed to save the configuration: %s" %
                             write_result['response']['err']['msg'])

    # log out of the session nicely and exit
    axapi_call(module, session_url + '&method=session.close')
    module.exit_json(changed=changed, content=result)
Esempio n. 8
0
def main():
    argument_spec = a10_argument_spec()
    argument_spec.update(url_argument_spec())
    argument_spec.update(
        dict(
            state=dict(type="str", default="present", choices=["present", "absent"]),
            server_name=dict(type="str", aliases=["server"], required=True),
            server_ip=dict(type="str", aliases=["ip", "address"]),
            server_status=dict(type="str", default="enabled", aliases=["status"], choices=["enabled", "disabled"]),
            server_ports=dict(type="list", aliases=["port"], default=[]),
            partition=dict(type="str", default=[]),
        )
    )

    module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False)

    host = module.params["host"]
    partition = module.params["partition"]
    username = module.params["username"]
    password = module.params["password"]
    state = module.params["state"]
    write_config = module.params["write_config"]
    slb_server = module.params["server_name"]
    slb_server_ip = module.params["server_ip"]
    slb_server_status = module.params["server_status"]
    slb_server_ports = module.params["server_ports"]

    if slb_server is None:
        module.fail_json(msg="server_name is required")

    axapi_base_url = "https://%s/services/rest/V2.1/?format=json" % host
    session_url = axapi_authenticate(module, axapi_base_url, username, password)

    # validate the ports data structure
    validate_ports(module, slb_server_ports)

    json_post = {"server": {"name": slb_server}}

    # add optional module parameters
    if slb_server_ip:
        json_post["server"]["host"] = slb_server_ip

    if slb_server_ports:
        json_post["server"]["port_list"] = slb_server_ports

    if slb_server_status:
        json_post["server"]["status"] = axapi_enabled_disabled(slb_server_status)

    slb_server_partition = axapi_call(
        module, session_url + "&method=system.partition.active", json.dumps({"name": partition})
    )

    slb_server_data = axapi_call(module, session_url + "&method=slb.server.search", json.dumps({"name": slb_server}))
    slb_server_exists = not axapi_failure(slb_server_data)

    changed = False
    if state == "present":
        if not slb_server_exists:
            if not slb_server_ip:
                module.fail_json(msg="you must specify an IP address when creating a server")

            result = axapi_call(module, session_url + "&method=slb.server.create", json.dumps(json_post))
            if axapi_failure(result):
                module.fail_json(msg="failed to create the server: %s" % result["response"]["err"]["msg"])
            changed = True
        else:

            def port_needs_update(src_ports, dst_ports):
                """
                Checks to determine if the port definitions of the src_ports
                array are in or different from those in dst_ports. If there is
                a difference, this function returns true, otherwise false.
                """
                for src_port in src_ports:
                    found = False
                    different = False
                    for dst_port in dst_ports:
                        if src_port["port_num"] == dst_port["port_num"]:
                            found = True
                            for valid_field in VALID_PORT_FIELDS:
                                if src_port[valid_field] != dst_port[valid_field]:
                                    different = True
                                    break
                            if found or different:
                                break
                    if not found or different:
                        return True
                # every port from the src exists in the dst, and none of them were different
                return False

            def status_needs_update(current_status, new_status):
                """
                Check to determine if we want to change the status of a server.
                If there is a difference between the current status of the server and
                the desired status, return true, otherwise false.
                """
                if current_status != new_status:
                    return True
                return False

            defined_ports = slb_server_data.get("server", {}).get("port_list", [])
            current_status = slb_server_data.get("server", {}).get("status")

            # we check for a needed update several ways
            # - in case ports are missing from the ones specified by the user
            # - in case ports are missing from those on the device
            # - in case we are change the status of a server
            if (
                port_needs_update(defined_ports, slb_server_ports)
                or port_needs_update(slb_server_ports, defined_ports)
                or status_needs_update(current_status, axapi_enabled_disabled(slb_server_status))
            ):
                result = axapi_call(module, session_url + "&method=slb.server.update", json.dumps(json_post))
                if axapi_failure(result):
                    module.fail_json(msg="failed to update the server: %s" % result["response"]["err"]["msg"])
                changed = True

        # if we changed things, get the full info regarding
        # the service group for the return data below
        if changed:
            result = axapi_call(module, session_url + "&method=slb.server.search", json.dumps({"name": slb_server}))
        else:
            result = slb_server_data
    elif state == "absent":
        if slb_server_exists:
            result = axapi_call(module, session_url + "&method=slb.server.delete", json.dumps({"name": slb_server}))
            changed = True
        else:
            result = dict(msg="the server was not present")

    # if the config has changed, save the config unless otherwise requested
    if changed and write_config:
        write_result = axapi_call(module, session_url + "&method=system.action.write_memory")
        if axapi_failure(write_result):
            module.fail_json(msg="failed to save the configuration: %s" % write_result["response"]["err"]["msg"])

    # log out of the session nicely and exit
    axapi_call(module, session_url + "&method=session.close")
    module.exit_json(changed=changed, content=result)
Esempio n. 9
0
def main():
    argument_spec = a10_argument_spec()
    argument_spec.update(url_argument_spec())
    argument_spec.update(
        dict(
            state=dict(type='str', default='present', choices=['present', 'absent']),
            server_name=dict(type='str', aliases=['server'], required=True),
            server_ip=dict(type='str', aliases=['ip', 'address']),
            server_status=dict(type='str', default='enabled', aliases=['status'], choices=['enabled', 'disabled']),
            server_ports=dict(type='list', aliases=['port'], default=[]),
            partition=dict(type='str', default=[]),
        )
    )

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=False
    )

    host = module.params['host']
    partition = module.params['partition']
    username = module.params['username']
    password = module.params['password']
    state = module.params['state']
    write_config = module.params['write_config']
    slb_server = module.params['server_name']
    slb_server_ip = module.params['server_ip']
    slb_server_status = module.params['server_status']
    slb_server_ports = module.params['server_ports']

    if slb_server is None:
        module.fail_json(msg='server_name is required')

    axapi_base_url = 'https://%s/services/rest/V2.1/?format=json' % host
    session_url = axapi_authenticate(module, axapi_base_url, username, password)

    # validate the ports data structure
    validate_ports(module, slb_server_ports)

    json_post = {
        'server': {
            'name': slb_server,
        }
    }

    # add optional module parameters
    if slb_server_ip:
        json_post['server']['host'] = slb_server_ip

    if slb_server_ports:
        json_post['server']['port_list'] = slb_server_ports

    if slb_server_status:
        json_post['server']['status'] = axapi_enabled_disabled(slb_server_status)

    axapi_call(module, session_url + '&method=system.partition.active', json.dumps({'name': partition}))

    slb_server_data = axapi_call(module, session_url + '&method=slb.server.search', json.dumps({'name': slb_server}))
    slb_server_exists = not axapi_failure(slb_server_data)

    changed = False
    if state == 'present':
        if not slb_server_exists:
            if not slb_server_ip:
                module.fail_json(msg='you must specify an IP address when creating a server')

            result = axapi_call(module, session_url + '&method=slb.server.create', json.dumps(json_post))
            if axapi_failure(result):
                module.fail_json(msg="failed to create the server: %s" % result['response']['err']['msg'])
            changed = True
        else:
            def port_needs_update(src_ports, dst_ports):
                '''
                Checks to determine if the port definitions of the src_ports
                array are in or different from those in dst_ports. If there is
                a difference, this function returns true, otherwise false.
                '''
                for src_port in src_ports:
                    found = False
                    different = False
                    for dst_port in dst_ports:
                        if src_port['port_num'] == dst_port['port_num']:
                            found = True
                            for valid_field in VALID_PORT_FIELDS:
                                if src_port[valid_field] != dst_port[valid_field]:
                                    different = True
                                    break
                            if found or different:
                                break
                    if not found or different:
                        return True
                # every port from the src exists in the dst, and none of them were different
                return False

            def status_needs_update(current_status, new_status):
                '''
                Check to determine if we want to change the status of a server.
                If there is a difference between the current status of the server and
                the desired status, return true, otherwise false.
                '''
                if current_status != new_status:
                    return True
                return False

            defined_ports = slb_server_data.get('server', {}).get('port_list', [])
            current_status = slb_server_data.get('server', {}).get('status')

            # we check for a needed update several ways
            # - in case ports are missing from the ones specified by the user
            # - in case ports are missing from those on the device
            # - in case we are change the status of a server
            if (port_needs_update(defined_ports, slb_server_ports) or
                    port_needs_update(slb_server_ports, defined_ports) or
                    status_needs_update(current_status, axapi_enabled_disabled(slb_server_status))):
                result = axapi_call(module, session_url + '&method=slb.server.update', json.dumps(json_post))
                if axapi_failure(result):
                    module.fail_json(msg="failed to update the server: %s" % result['response']['err']['msg'])
                changed = True

        # if we changed things, get the full info regarding
        # the service group for the return data below
        if changed:
            result = axapi_call(module, session_url + '&method=slb.server.search', json.dumps({'name': slb_server}))
        else:
            result = slb_server_data
    elif state == 'absent':
        if slb_server_exists:
            result = axapi_call(module, session_url + '&method=slb.server.delete', json.dumps({'name': slb_server}))
            changed = True
        else:
            result = dict(msg="the server was not present")

    # if the config has changed, save the config unless otherwise requested
    if changed and write_config:
        write_result = axapi_call(module, session_url + '&method=system.action.write_memory')
        if axapi_failure(write_result):
            module.fail_json(msg="failed to save the configuration: %s" % write_result['response']['err']['msg'])

    # log out of the session nicely and exit
    axapi_call(module, session_url + '&method=session.close')
    module.exit_json(changed=changed, content=result)
def main():
    argument_spec = a10_argument_spec()
    argument_spec.update(url_argument_spec())
    argument_spec.update(
        dict(
            state=dict(type='str',
                       default='present',
                       choices=['present', 'absent']),
            partition=dict(type='str', aliases=['partition', 'part']),
            virtual_server=dict(type='str',
                                aliases=['vip', 'virtual'],
                                required=True),
            virtual_server_ip=dict(type='str',
                                   aliases=['ip', 'address'],
                                   required=True),
            virtual_server_status=dict(type='str',
                                       default='enabled',
                                       aliases=['status'],
                                       choices=['enabled', 'disabled']),
            disable_vserver_on_condition=dict(
                type='str',
                choices=[
                    'enable', 'disable', 'disable-when-all-ports-down',
                    'disable-when-any-port-down'
                ],
                required=False,
                default='enable'),
            redistribution_flagged=dict(type='int',
                                        choices=[0, 1, 2],
                                        required=False,
                                        default=0),
            acl_id=dict(type='str', required=False, default=None),
            acl_name=dict(type='str', required=False, default=None),
            virtual_server_ports=dict(type='list', required=True),
            overwrite=dict(type='bool', default=False, required=False),
        ))

    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=False)

    host = module.params['host']
    username = module.params['username']
    password = module.params['password']
    part = module.params['partition']
    state = module.params['state']
    write_config = module.params['write_config']
    slb_virtual = module.params['virtual_server']
    slb_virtual_ip = module.params['virtual_server_ip']
    slb_virtual_status = module.params['virtual_server_status']
    slb_virtual_ports = module.params['virtual_server_ports']
    redistribution_flagged = module.params['redistribution_flagged']
    acl_id = module.params['acl_id']
    acl_name = module.params['acl_name']
    disable_vserver_on_condition = module.params[
        'disable_vserver_on_condition']
    overwrite = module.params['overwrite']

    # check mandatory fields
    if slb_virtual is None:
        module.fail_json(msg='virtual_server is required')

    axapi_base_url = 'http://%s/axapi/v3/' % host

    # first we authenticate to get a session id
    signature = axapi_authenticate_v3(module, axapi_base_url + 'auth',
                                      username, password)

    # change partitions if we need to
    if part:
        result = axapi_call_v3(module,
                               axapi_base_url + 'active-partition/' + part,
                               method="POST",
                               signature=signature,
                               body="")
        if (result['response']['status'] == 'fail'):
            # log out of the session nicely and exit with an error
            logoff_result = axapi_call_v3(module,
                                          axapi_base_url + 'logoff',
                                          method="POST",
                                          signature=signature,
                                          body="")
            module.fail_json(msg=result['response']['err']['msg'])

    json_post = {
        'virtual-server': {
            'name': slb_virtual,
            'enable-disable-action':
            axapi_enabled_disabled(slb_virtual_status),
            'port-list': slb_virtual_ports,
            'enable-disable-action': disable_vserver_on_condition,
            'redistribution-flagged': redistribution_flagged,
        }
    }

    # is this an IPv4 or IPv6 VIP?
    if "::" in slb_virtual_ip or len(slb_virtual_ip) > 16:
        ip_address_field = "ipv6-address"
        acl_name_field = "ipv6-acl"
    else:
        ip_address_field = "ip-address"
        acl_name_field = "acl-name"

    # if acl id or acl name was passed in bind it to the vip, otherwise assign the ip address passed in
    if acl_id or acl_name:
        if acl_id:
            json_post['virtual-server']['acl-id'] = acl_id
        else:
            json_post['virtual-server'][acl_name_field] = acl_name
#    else:
    json_post['virtual-server'][ip_address_field] = slb_virtual_ip

    result = axapi_call_v3(module,
                           axapi_base_url + 'slb/virtual-server/' +
                           slb_virtual,
                           method="GET",
                           signature=signature)

    if ('response' in result and result['response']['status'] == 'fail'):
        if (result['response']['code'] == 404):
            slb_virtual_exists = False
        else:
            logoff_result = axapi_call_v3(module,
                                          axapi_base_url + 'logoff',
                                          method="POST",
                                          signature=signature,
                                          body="")
            module.fail_json(msg=result['response']['err']['msg'])
    else:
        slb_virtual_exists = True

    # clear the 'changed' flag
    changed = False
    msg = ""

    if state == 'present':

        if slb_virtual_exists and not overwrite:
            msg = 'virtual server exists but not modified'

        elif slb_virtual_exists and overwrite:
            # overwrite the properties of the virtual server
            result = axapi_call_v3(module,
                                   axapi_base_url + 'slb/virtual-server/' +
                                   slb_virtual,
                                   method="PUT",
                                   signature=signature,
                                   body=json_post)
            if ('response' in result and 'err' in result['response']):
                logoff_result = axapi_call_v3(module,
                                              axapi_base_url + 'logoff',
                                              method="POST",
                                              signature=signature,
                                              body="")
                module.fail_json(msg=result['response']['err']['msg'])

            changed = True
            msg = "virtual server %s updated" % slb_virtual

        elif not slb_virtual_exists:
            # create a new server
            result = axapi_call_v3(module,
                                   axapi_base_url + 'slb/virtual-server/',
                                   method="POST",
                                   signature=signature,
                                   body=json_post)
            if ('response' in result and 'err' in result['response']):
                logoff_result = axapi_call_v3(module,
                                              axapi_base_url + 'logoff',
                                              method="POST",
                                              signature=signature,
                                              body="")
                module.fail_json(msg=result['response']['err']['msg'])

            changed = True
            msg = "virtual server %s created" % slb_virtual

    elif state == 'absent':
        if slb_virtual_exists:
            result = axapi_call_v3(module,
                                   axapi_base_url + 'slb/virtual-server/' +
                                   slb_virtual,
                                   method="DELETE",
                                   signature=signature)
            changed = True
        else:
            changed = False
            msg = "the virtual server was not present"

    # if the config has changed, save the config unless otherwise requested
    if changed and write_config:
        result = axapi_call_v3(module,
                               axapi_base_url + 'write/memory',
                               method="POST",
                               signature=signature)

        if ('response' in result and 'err' in result['response']):
            logoff_result = axapi_call_v3(module,
                                          axapi_base_url + 'logoff',
                                          method="POST",
                                          signature=signature,
                                          body="")
            module.fail_json(msg=result['response']['err']['msg'])

    # log out of the session nicely and exit
    result = axapi_call_v3(module,
                           axapi_base_url + 'logoff',
                           method="POST",
                           signature=signature,
                           body="")
    module.exit_json(changed=changed, content=result, msg=msg)