Example #1
0
def get_configured_policybindings(client, module):
    log('Getting configured policy bindigs')
    bindings = {}
    if module.params['policybindings'] is None:
        return bindings

    for binding in module.params['policybindings']:
        binding['name'] = module.params['name']
        key = binding['policyname']
        binding_proxy = ConfigProxy(
            actual=csvserver_cspolicy_binding(),
            client=client,
            readwrite_attrs=[
                'priority',
                'bindpoint',
                'policyname',
                'labelname',
                'gotopriorityexpression',
                'targetlbvserver',
                'name',
                'invoke',
                'labeltype',
            ],
            readonly_attrs=[],
            attribute_values_dict=binding
        )
        bindings[key] = binding_proxy
    return bindings
Example #2
0
def sync_domain_bindings(client, module):
    log('sync_domain_bindings')

    actual_domain_bindings = get_actual_domain_bindings(client, module)
    configured_domain_proxys = get_configured_domain_bindings_proxys(client, module)

    # Delete actual bindings not in configured bindings
    for domainname, actual_domain_binding in actual_domain_bindings.items():
        if domainname not in configured_domain_proxys.keys():
            log('Deleting absent binding for domain %s' % domainname)
            gslbvserver_domain_binding.delete(client, actual_domain_binding)

    # Delete actual bindings that differ from configured
    for proxy_key, binding_proxy in configured_domain_proxys.items():
        if proxy_key in actual_domain_bindings:
            actual_binding = actual_domain_bindings[proxy_key]
            if not binding_proxy.has_equal_attributes(actual_binding):
                log('Deleting differing binding for domain %s' % binding_proxy.domainname)
                gslbvserver_domain_binding.delete(client, actual_binding)
                log('Adding anew binding for domain %s' % binding_proxy.domainname)
                binding_proxy.add()

    # Add configured domains that are missing from actual
    for proxy_key, binding_proxy in configured_domain_proxys.items():
        if proxy_key not in actual_domain_bindings.keys():
            log('Adding domain binding for domain %s' % binding_proxy.domainname)
            binding_proxy.add()
 def test_log_function(self):
     messages = [
         'First message',
         'Second message',
     ]
     log(messages[0])
     log(messages[1])
     self.assertListEqual(messages, loglines, msg='Log messages not recorded correctly')
Example #4
0
def do_state_change(client, module, server_proxy):
    if module.params['disabled']:
        log('Disabling server')
        result = server.disable(client, server_proxy.actual)
    else:
        log('Enabling server')
        result = server.enable(client, server_proxy.actual)
    return result
Example #5
0
def servicegroup_exists(client, module):
    log('Checking if service group exists')
    count = servicegroup.count_filtered(
        client, 'servicegroupname:%s' % module.params['servicegroupname'])
    log('count is %s' % count)
    if count > 0:
        return True
    else:
        return False
Example #6
0
def server_identical(client, module, server_proxy):
    log('Checking if configured server is identical')
    if server.count_filtered(client, 'name:%s' % module.params['name']) == 0:
        return False
    server_list = server.get_filtered(client, 'name:%s' % module.params['name'])
    if server_proxy.has_equal_attributes(server_list[0]):
        return True
    else:
        return False
Example #7
0
def key_exists(client, module):
    log('Checking if key exists')
    log('certkey is %s' % module.params['certkey'])
    all_certificates = sslcertkey.get(client)
    certkeys = [item.certkey for item in all_certificates]
    if module.params['certkey'] in certkeys:
        return True
    else:
        return False
 def test_log_function(self):
     messages = [
         'First message',
         'Second message',
     ]
     log(messages[0])
     log(messages[1])
     self.assertListEqual(messages,
                          loglines,
                          msg='Log messages not recorded correctly')
Example #9
0
def server_identical(client, module, server_proxy):
    log('Checking if configured server is identical')
    if server.count_filtered(client, 'name:%s' % module.params['name']) == 0:
        return False
    server_list = server.get_filtered(client,
                                      'name:%s' % module.params['name'])
    if server_proxy.has_equal_attributes(server_list[0]):
        return True
    else:
        return False
Example #10
0
def get_actual_monitor_bindings(client, module):
    log('get_actual_monitor_bindings')
    # Get actual monitor bindings and index them by monitor_name
    actual_monitor_bindings = {}
    if gslbservice_lbmonitor_binding.count(client, servicename=module.params['servicename']) != 0:
        # Get all monitor bindings associated with the named gslb vserver
        fetched_bindings = gslbservice_lbmonitor_binding.get(client, servicename=module.params['servicename'])
        # index by monitor name
        for binding in fetched_bindings:
            # complete_missing_attributes(binding, gslbservice_lbmonitor_binding_rw_attrs, fill_value=None)
            actual_monitor_bindings[binding.monitor_name] = binding
    return actual_monitor_bindings
def get_actual_monitor_bindings(client, module):
    log('get_actual_monitor_bindings')
    # Get actual monitor bindings and index them by monitor_name
    actual_monitor_bindings = {}
    if gslbservice_lbmonitor_binding.count(client, servicename=module.params['servicename']) != 0:
        # Get all monitor bindings associated with the named gslb vserver
        fetched_bindings = gslbservice_lbmonitor_binding.get(client, servicename=module.params['servicename'])
        # index by monitor name
        for binding in fetched_bindings:
            # complete_missing_attributes(binding, gslbservice_lbmonitor_binding_rw_attrs, fill_value=None)
            actual_monitor_bindings[binding.monitor_name] = binding
    return actual_monitor_bindings
Example #12
0
def policy_identical(client, module, cspolicy_proxy):
    log('Checking if defined policy is identical to configured')
    if cspolicy.count_filtered(client, 'policyname:%s' % module.params['policyname']) == 0:
        return False
    policy_list = cspolicy.get_filtered(client, 'policyname:%s' % module.params['policyname'])
    diff_dict = cspolicy_proxy.diff_object(policy_list[0])
    if 'ip' in diff_dict:
        del diff_dict['ip']
    if len(diff_dict) == 0:
        return True
    else:
        return False
 def service_identical():
     service_list = service.get_filtered(client, 'name:%s' % module.params['name'])
     diff_dict = service_proxy.diff_object(service_list[0])
     log('other ipaddress is %s' % service_list[0].ipaddress)
     # the actual ip address is stored in the ipaddress attribute
     # of the retrieved object
     if 'ip' in diff_dict:
         del diff_dict['ip']
     if len(diff_dict) == 0:
         return True
     else:
         return False
Example #14
0
    def get_actual_service_bindings():
        log('entering get_actual_service_bindings')
        if lbmonbindings_service_binding.count(client, module.params['monitorname']) == 0:
            return {}
        bindigs_list = lbmonbindings_service_binding.get(client, module.params['monitorname'])
        bindings = {}
        for item in bindigs_list:
            key = item.servicename
            log('bound service name %s' % key)
            bindings[key] = item

        return bindings
Example #15
0
def get_actual_domain_bindings(client, module):
    log('get_actual_domain_bindings')
    # Get actual domain bindings and index them by domainname
    actual_domain_bindings = {}
    if gslbvserver_domain_binding.count(client, name=module.params['name']) != 0:
        # Get all domain bindings associated with the named gslb vserver
        fetched_domain_bindings = gslbvserver_domain_binding.get(client, name=module.params['name'])
        # index by domainname
        for binding in fetched_domain_bindings:
            complete_missing_attributes(binding, gslbvserver_domain_binding_rw_attrs, fill_value=None)
            actual_domain_bindings[binding.domainname] = binding
    return actual_domain_bindings
Example #16
0
def key_identical(client, module, sslcertkey_proxy):
    log('Checking if configured key is identical')
    sslcertkey_list = sslcertkey.get_filtered(client, 'certkey:%s' % module.params['certkey'])
    diff_dict = sslcertkey_proxy.diff_object(sslcertkey_list[0])
    if 'password' in diff_dict:
        del diff_dict['password']
    if 'passplain' in diff_dict:
        del diff_dict['passplain']
    if len(diff_dict) == 0:
        return True
    else:
        return False
Example #17
0
def key_identical(client, module, sslcertkey_proxy):
    log('Checking if configured key is identical')
    sslcertkey_list = sslcertkey.get_filtered(client, 'certkey:%s' % module.params['certkey'])
    diff_dict = sslcertkey_proxy.diff_object(sslcertkey_list[0])
    if 'password' in diff_dict:
        del diff_dict['password']
    if 'passplain' in diff_dict:
        del diff_dict['passplain']
    if len(diff_dict) == 0:
        return True
    else:
        return False
Example #18
0
def get_actual_domain_bindings(client, module):
    log('get_actual_domain_bindings')
    # Get actual domain bindings and index them by domainname
    actual_domain_bindings = {}
    if gslbvserver_domain_binding.count(client, name=module.params['name']) != 0:
        # Get all domain bindings associated with the named gslb vserver
        fetched_domain_bindings = gslbvserver_domain_binding.get(client, name=module.params['name'])
        # index by domainname
        for binding in fetched_domain_bindings:
            complete_missing_attributes(binding, gslbvserver_domain_binding_rw_attrs, fill_value=None)
            actual_domain_bindings[binding.domainname] = binding
    return actual_domain_bindings
    def get_actual_monitor_bindings():
        log('Entering get_actual_monitor_bindings')
        bindings = {}
        if service_lbmonitor_binding.count(client, module.params['name']) == 0:
            return bindings

        # Fallthrough to rest of execution
        for binding in service_lbmonitor_binding.get(client, module.params['name']):
            log('Gettign actual monitor with name %s' % binding.monitor_name)
            key = binding.monitor_name
            bindings[key] = binding

        return bindings
def policy_identical(client, module, cspolicy_proxy):
    log('Checking if defined policy is identical to configured')
    if cspolicy.count_filtered(client, 'policyname:%s' %
                               module.params['policyname']) == 0:
        return False
    policy_list = cspolicy.get_filtered(
        client, 'policyname:%s' % module.params['policyname'])
    diff_dict = cspolicy_proxy.diff_object(policy_list[0])
    if 'ip' in diff_dict:
        del diff_dict['ip']
    if len(diff_dict) == 0:
        return True
    else:
        return False
Example #21
0
def main():

    argument_spec = copy.deepcopy(netscaler_common_arguments)

    # Delete common arguments irrelevant to this module
    del argument_spec['state']
    del argument_spec['save_config']

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

    module_result = dict(
        changed=False,
        failed=False,
        loglines=loglines,
    )

    # Fail the module if imports failed
    if not PYTHON_SDK_IMPORTED:
        module.fail_json(msg='Could not load nitro python sdk')

    # Fallthrough to rest of execution
    client = get_nitro_client(module)

    try:
        client.login()
    except nitro_exception as e:
        msg = "nitro exception during login. errorcode=%s, message=%s" % (str(
            e.errorcode), e.message)
        module.fail_json(msg=msg)
    except Exception as e:
        if str(type(e)) == "<class 'requests.exceptions.ConnectionError'>":
            module.fail_json(msg='Connection error %s' % str(e))
        elif str(type(e)) == "<class 'requests.exceptions.SSLError'>":
            module.fail_json(msg='SSL Error %s' % str(e))
        else:
            module.fail_json(msg='Unexpected error during login %s' % str(e))

    try:
        log('Saving configuration')
        client.save_config()
    except nitro_exception as e:
        msg = "nitro exception errorcode=" + str(
            e.errorcode) + ",message=" + e.message
        module.fail_json(msg=msg, **module_result)

    client.logout()
    module.exit_json(**module_result)
Example #22
0
def main():

    argument_spec = copy.deepcopy(netscaler_common_arguments)

    # Delete common arguments irrelevant to this module
    del argument_spec['state']
    del argument_spec['save_config']

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

    module_result = dict(
        changed=False,
        failed=False,
        loglines=loglines,
    )

    # Fail the module if imports failed
    if not PYTHON_SDK_IMPORTED:
        module.fail_json(msg='Could not load nitro python sdk')

    # Fallthrough to rest of execution
    client = get_nitro_client(module)

    try:
        client.login()
    except nitro_exception as e:
        msg = "nitro exception during login. errorcode=%s, message=%s" % (str(e.errorcode), e.message)
        module.fail_json(msg=msg)
    except Exception as e:
        if str(type(e)) == "<class 'requests.exceptions.ConnectionError'>":
            module.fail_json(msg='Connection error %s' % str(e))
        elif str(type(e)) == "<class 'requests.exceptions.SSLError'>":
            module.fail_json(msg='SSL Error %s' % str(e))
        else:
            module.fail_json(msg='Unexpected error during login %s' % str(e))

    try:
        log('Saving configuration')
        client.save_config()
    except nitro_exception as e:
        msg = "nitro exception errorcode=" + str(e.errorcode) + ",message=" + e.message
        module.fail_json(msg=msg, **module_result)

    client.logout()
    module.exit_json(**module_result)
Example #23
0
def get_configured_service_bindings(client, module):
    log('get_configured_service_bindings_proxys')
    configured_proxys = {}
    # Get configured domain bindings and index them by domainname
    if module.params['service_bindings'] is not None:
        for configured_binding in module.params['service_bindings']:
            binding_values = copy.deepcopy(configured_binding)
            binding_values['name'] = module.params['name']
            gslbvserver_service_binding_proxy = ConfigProxy(
                actual=gslbvserver_gslbservice_binding(),
                client=client,
                attribute_values_dict=binding_values,
                readwrite_attrs=gslbvserver_gslbservice_binding_rw_attrs,
                readonly_attrs=[],
            )
            configured_proxys[configured_binding['servicename']] = gslbvserver_service_binding_proxy
    return configured_proxys
Example #24
0
def sync_monitor_bindings(client, module):
    log('Entering sync_monitor_bindings')
    # Delete existing bindings
    for binding in get_actual_monitor_bindings(client, module).values():
        b = lbmonitor_servicegroup_binding()
        b.monitorname = binding.monitor_name
        b.servicegroupname = module.params['servicegroupname']
        # Cannot remove default monitor bindings
        if b.monitorname in ('tcp-default', 'ping-default'):
            continue
        lbmonitor_servicegroup_binding.delete(client, b)

    # Apply configured bindings

    for binding in get_configured_monitor_bindings(client, module).values():
        log('Adding %s' % binding.monitorname)
        binding.add()
Example #25
0
def get_configured_service_bindings(client, module):
    log('get_configured_service_bindings_proxys')
    configured_proxys = {}
    # Get configured domain bindings and index them by domainname
    if module.params['service_bindings'] is not None:
        for configured_binding in module.params['service_bindings']:
            binding_values = copy.deepcopy(configured_binding)
            binding_values['name'] = module.params['name']
            gslbvserver_service_binding_proxy = ConfigProxy(
                actual=gslbvserver_gslbservice_binding(),
                client=client,
                attribute_values_dict=binding_values,
                readwrite_attrs=gslbvserver_gslbservice_binding_rw_attrs,
                readonly_attrs=[],
            )
            configured_proxys[configured_binding['servicename']] = gslbvserver_service_binding_proxy
    return configured_proxys
Example #26
0
    def ssl_certkey_bindings_sync():
        vservername = module.params['name']
        if sslvserver_sslcertkey_binding.count(client, vservername) == 0:
            bindings = []
        else:
            bindings = sslvserver_sslcertkey_binding.get(client, vservername)
        log('bindings len is %s' % len(bindings))

        # Delete existing bindings
        for binding in bindings:
            sslvserver_sslcertkey_binding.delete(client, binding)

        # Add binding if appropriate
        if module.params['ssl_certkey'] is not None:
            binding = sslvserver_sslcertkey_binding()
            binding.vservername = module.params['name']
            binding.certkeyname = module.params['ssl_certkey']
            sslvserver_sslcertkey_binding.add(client, binding)
def get_actual_policybindings(client, module):
    log('Getting actual policy bindigs')
    bindings = {}
    try:
        count = csvserver_cspolicy_binding.count(client, name=module.params['name'])
        if count == 0:
            return bindings
    except nitro_exception as e:
        if e.errorcode == 258:
            return bindings
        else:
            raise

    for binding in csvserver_cspolicy_binding.get(client, name=module.params['name']):
        key = binding.policyname
        bindings[key] = binding

    return bindings
Example #28
0
def get_actual_policybindings(client, module):
    log('Getting actual policy bindigs')
    bindings = {}
    try:
        count = csvserver_cspolicy_binding.count(client, name=module.params['name'])
        if count == 0:
            return bindings
    except nitro_exception as e:
        if e.errorcode == 258:
            return bindings
        else:
            raise

    for binding in csvserver_cspolicy_binding.get(client, name=module.params['name']):
        key = binding.policyname
        bindings[key] = binding

    return bindings
def ssl_certkey_bindings_identical(client, module):
    log('Checking if ssl cert key bindings are identical')
    vservername = module.params['name']
    if sslvserver_sslcertkey_binding.count(client, vservername) == 0:
        bindings = []
    else:
        bindings = sslvserver_sslcertkey_binding.get(client, vservername)

    if module.params['ssl_certkey'] is None:
        if len(bindings) == 0:
            return True
        else:
            return False
    else:
        certificate_list = [item.certkeyname for item in bindings]
        if certificate_list == [module.params['ssl_certkey']]:
            return True
        else:
            return False
Example #30
0
def cs_policybindings_identical(client, module):
    log('Checking policy bindings identical')
    actual_bindings = get_actual_policybindings(client, module)
    configured_bindings = get_configured_policybindings(client, module)

    actual_keyset = set(actual_bindings.keys())
    configured_keyset = set(configured_bindings.keys())
    if len(actual_keyset ^ configured_keyset) > 0:
        return False

    # Compare item to item
    for key in actual_bindings.keys():
        configured_binding_proxy = configured_bindings[key]
        actual_binding_object = actual_bindings[key]
        if not configured_binding_proxy.has_equal_attributes(actual_binding_object):
            return False

    # Fallthrough to success
    return True
Example #31
0
def ssl_certkey_bindings_identical(client, module):
    log('Checking if ssl cert key bindings are identical')
    vservername = module.params['name']
    if sslvserver_sslcertkey_binding.count(client, vservername) == 0:
        bindings = []
    else:
        bindings = sslvserver_sslcertkey_binding.get(client, vservername)

    if module.params['ssl_certkey'] is None:
        if len(bindings) == 0:
            return True
        else:
            return False
    else:
        certificate_list = [item.certkeyname for item in bindings]
        if certificate_list == [module.params['ssl_certkey']]:
            return True
        else:
            return False
def cs_policybindings_identical(client, module):
    log('Checking policy bindings identical')
    actual_bindings = get_actual_policybindings(client, module)
    configured_bindings = get_configured_policybindings(client, module)

    actual_keyset = set(actual_bindings.keys())
    configured_keyset = set(configured_bindings.keys())
    if len(actual_keyset ^ configured_keyset) > 0:
        return False

    # Compare item to item
    for key in actual_bindings.keys():
        configured_binding_proxy = configured_bindings[key]
        actual_binding_object = actual_bindings[key]
        if not configured_binding_proxy.has_equal_attributes(actual_binding_object):
            return False

    # Fallthrough to success
    return True
    def service_group_servicemembers_identical():
        log('service_group_servicemembers_identical')
        service_group_members = servicegroup_servicegroupmember_binding.get(
            client, module.params['servicegroupname'])
        module_service_groups = get_servicegroups_from_module_params()
        log('Number of service group members %s' % len(service_group_members))
        if len(service_group_members) != len(module_service_groups):
            return False

        # Fallthrough to member evaluation
        identical_count = 0
        for actual_member in service_group_members:
            for member in module_service_groups:
                if member.has_equal_attributes(actual_member):
                    identical_count += 1
                    break
        if identical_count != len(service_group_members):
            return False

        # Fallthrough to success
        return True
Example #34
0
def sync_service_bindings(client, module):
    actual = get_actual_service_bindings(client, module)
    configured = get_configured_service_bindings(client, module)

    # Delete extraneous
    extraneous_service_bindings = list(set(actual.keys()) - set(configured.keys()))
    for servicename in extraneous_service_bindings:
        log('Deleting missing binding from service %s' % servicename)
        binding = actual[servicename]
        binding.name = module.params['name']
        gslbvserver_gslbservice_binding.delete(client, binding)

    # Recreate different
    common_service_bindings = list(set(actual.keys()) & set(configured.keys()))
    for servicename in common_service_bindings:
        proxy = configured[servicename]
        binding = actual[servicename]
        if not proxy.has_equal_attributes(actual):
            log('Recreating differing service binding %s' % servicename)
            gslbvserver_gslbservice_binding.delete(client, binding)
            proxy.add()

    # Add missing
    missing_service_bindings = list(set(configured.keys()) - set(actual.keys()))
    for servicename in missing_service_bindings:
        proxy = configured[servicename]
        log('Adding missing service binding %s' % servicename)
        proxy.add()
Example #35
0
def sync_monitor_bindings(client, module, monitor_bindings_rw_attrs):
    configured_proxys = get_configured_monitor_bindings(
        client, module, monitor_bindings_rw_attrs)
    actual_bindings = get_actual_monitor_bindings(client, module)
    configured_keyset = set(configured_proxys.keys())
    actual_keyset = set(actual_bindings.keys())

    # Delete extra
    delete_keys = list(actual_keyset - configured_keyset)
    for monitor_name in delete_keys:
        log('Deleting binding for monitor %s' % monitor_name)
        lbmonitor_service_binding.delete(client, actual_bindings[monitor_name])

    # Delete and re-add modified
    common_keyset = list(configured_keyset & actual_keyset)
    for monitor_name in common_keyset:
        proxy = configured_proxys[monitor_name]
        actual = actual_bindings[monitor_name]
        if not proxy.has_equal_attributes(actual):
            log('Deleting and re adding binding for monitor %s' % monitor_name)
            lbmonitor_service_binding.delete(client, actual)
            proxy.add()

    # Add new
    new_keys = list(configured_keyset - actual_keyset)
    for monitor_name in new_keys:
        log('Adding binding for monitor %s' % monitor_name)
        configured_proxys[monitor_name].add()
Example #36
0
def servicemembers_identical(client, module):
    log('servicemembers_identical')
    try:
        # count() raises nitro exception instead of returning 0
        count = servicegroup_servicegroupmember_binding.count(
            client, module.params['servicegroupname'])
        if count > 0:
            servicegroup_members = servicegroup_servicegroupmember_binding.get(
                client, module.params['servicegroupname'])
        else:
            servicegroup_members = []
    except nitro_exception as e:
        if e.errorcode == 258:
            servicegroup_members = []
        else:
            raise

    log('servicemembers %s' % servicegroup_members)
    module_servicegroups = get_configured_service_members(client, module)
    log('Number of service group members %s' % len(servicegroup_members))
    if len(servicegroup_members) != len(module_servicegroups):
        return False

    # Fallthrough to member evaluation
    identical_count = 0
    for actual_member in servicegroup_members:
        for member in module_servicegroups:
            if member.has_equal_attributes(actual_member):
                identical_count += 1
                break
    if identical_count != len(servicegroup_members):
        return False

    # Fallthrough to success
    return True
Example #37
0
def sync_service_bindings(client, module):
    actual = get_actual_service_bindings(client, module)
    configured = get_configured_service_bindings(client, module)

    # Delete extraneous
    extraneous_service_bindings = list(set(actual.keys()) - set(configured.keys()))
    for servicename in extraneous_service_bindings:
        log('Deleting missing binding from service %s' % servicename)
        binding = actual[servicename]
        binding.name = module.params['name']
        gslbvserver_gslbservice_binding.delete(client, binding)

    # Recreate different
    common_service_bindings = list(set(actual.keys()) & set(configured.keys()))
    for servicename in common_service_bindings:
        proxy = configured[servicename]
        binding = actual[servicename]
        if not proxy.has_equal_attributes(actual):
            log('Recreating differing service binding %s' % servicename)
            gslbvserver_gslbservice_binding.delete(client, binding)
            proxy.add()

    # Add missing
    missing_service_bindings = list(set(configured.keys()) - set(actual.keys()))
    for servicename in missing_service_bindings:
        proxy = configured[servicename]
        log('Adding missing service binding %s' % servicename)
        proxy.add()
Example #38
0
def sync_monitor_bindings(client, module, monitor_bindings_rw_attrs):
    configured_proxys = get_configured_monitor_bindings(client, module, monitor_bindings_rw_attrs)
    actual_bindings = get_actual_monitor_bindings(client, module)
    configured_keyset = set(configured_proxys.keys())
    actual_keyset = set(actual_bindings.keys())

    # Delete extra
    delete_keys = list(actual_keyset - configured_keyset)
    for monitor_name in delete_keys:
        log('Deleting binding for monitor %s' % monitor_name)
        lbmonitor_service_binding.delete(client, actual_bindings[monitor_name])

    # Delete and re-add modified
    common_keyset = list(configured_keyset & actual_keyset)
    for monitor_name in common_keyset:
        proxy = configured_proxys[monitor_name]
        actual = actual_bindings[monitor_name]
        if not proxy.has_equal_attributes(actual):
            log('Deleting and re adding binding for monitor %s' % monitor_name)
            lbmonitor_service_binding.delete(client, actual)
            proxy.add()

    # Add new
    new_keys = list(configured_keyset - actual_keyset)
    for monitor_name in new_keys:
        log('Adding binding for monitor %s' % monitor_name)
        configured_proxys[monitor_name].add()
def get_configured_monitor_bindings(client, module):
    log('get_configured_monitor_bindings')
    configured_monitor_proxys = {}
    gslbservice_lbmonitor_binding_rw_attrs = [
        'weight',
        'servicename',
        'monitor_name',
    ]
    # Get configured monitor bindings and index them by monitor_name
    if module.params['monitor_bindings'] is not None:
        for configured_monitor_bindings in module.params['monitor_bindings']:
            binding_values = copy.deepcopy(configured_monitor_bindings)
            binding_values['servicename'] = module.params['servicename']
            proxy = ConfigProxy(
                actual=gslbservice_lbmonitor_binding(),
                client=client,
                attribute_values_dict=binding_values,
                readwrite_attrs=gslbservice_lbmonitor_binding_rw_attrs,
                readonly_attrs=[],
            )
            configured_monitor_proxys[configured_monitor_bindings['monitor_name']] = proxy
    return configured_monitor_proxys
Example #40
0
def get_configured_monitor_bindings(client, module):
    log('get_configured_monitor_bindings')
    configured_monitor_proxys = {}
    gslbservice_lbmonitor_binding_rw_attrs = [
        'weight',
        'servicename',
        'monitor_name',
    ]
    # Get configured monitor bindings and index them by monitor_name
    if module.params['monitor_bindings'] is not None:
        for configured_monitor_bindings in module.params['monitor_bindings']:
            binding_values = copy.deepcopy(configured_monitor_bindings)
            binding_values['servicename'] = module.params['servicename']
            proxy = ConfigProxy(
                actual=gslbservice_lbmonitor_binding(),
                client=client,
                attribute_values_dict=binding_values,
                readwrite_attrs=gslbservice_lbmonitor_binding_rw_attrs,
                readonly_attrs=[],
            )
            configured_monitor_proxys[configured_monitor_bindings['monitor_name']] = proxy
    return configured_monitor_proxys
Example #41
0
def domain_bindings_identical(client, module):
    log('domain_bindings_identical')
    actual_domain_bindings = get_actual_domain_bindings(client, module)
    configured_domain_proxys = get_configured_domain_bindings_proxys(client, module)

    actual_keyset = set(actual_domain_bindings.keys())
    configured_keyset = set(configured_domain_proxys.keys())

    symmetric_difference = actual_keyset ^ configured_keyset

    log('symmetric difference %s' % symmetric_difference)
    if len(symmetric_difference) != 0:
        return False

    # Item for item equality test
    for key, proxy in configured_domain_proxys.items():
        diff = proxy.diff_object(actual_domain_bindings[key])
        if 'backupipflag' in diff:
            del diff['backupipflag']
        if not len(diff) == 0:
            return False
    # Fallthrough to True result
    return True
Example #42
0
def domain_bindings_identical(client, module):
    log('domain_bindings_identical')
    actual_domain_bindings = get_actual_domain_bindings(client, module)
    configured_domain_proxys = get_configured_domain_bindings_proxys(client, module)

    actual_keyset = set(actual_domain_bindings.keys())
    configured_keyset = set(configured_domain_proxys.keys())

    symmetric_difference = actual_keyset ^ configured_keyset

    log('symmetric difference %s' % symmetric_difference)
    if len(symmetric_difference) != 0:
        return False

    # Item for item equality test
    for key, proxy in configured_domain_proxys.items():
        diff = proxy.diff_object(actual_domain_bindings[key])
        if 'backupipflag' in diff:
            del diff['backupipflag']
        if not len(diff) == 0:
            return False
    # Fallthrough to True result
    return True
Example #43
0
    def get_servicegroups_from_module_params():
        log('get_servicegroups_from_module_params')
        readwrite_attrs = [
            u'servicegroupname', u'ip', u'port', u'state', u'hashid',
            u'serverid', u'servername', u'customserverid', u'weight'
        ]
        readonly_attrs = [
            u'delay', u'statechangetimesec', u'svrstate',
            u'tickssincelaststatechange', u'graceful', u'__count'
        ]

        members = []
        for config in module.params['servicemembers']:
            # Make a copy to update
            config = copy.deepcopy(config)
            config['servicegroupname'] = module.params['servicegroupname']
            member_proxy = ConfigProxy(
                actual=servicegroup_servicegroupmember_binding(),
                client=client,
                attribute_values_dict=config,
                readwrite_attrs=readwrite_attrs,
                readonly_attrs=readonly_attrs)
            members.append(member_proxy)
        return members
Example #44
0
def lbmonitor_identical(client, module, lbmonitor_proxy):
    log('Checking if monitor is identical')

    count = lbmonitor.count_filtered(client, 'monitorname:%s' % module.params['monitorname'])
    if count == 0:
        return False

    lbmonitor_list = lbmonitor.get_filtered(client, 'monitorname:%s' % module.params['monitorname'])
    diff_dict = lbmonitor_proxy.diff_object(lbmonitor_list[0])

    # Skipping hashed fields since the cannot be compared directly
    hashed_fields = [
        'password',
        'secondarypassword',
        'radkey',
    ]
    for key in hashed_fields:
        if key in diff_dict:
            del diff_dict[key]

    if diff_dict == {}:
        return True
    else:
        return False
    def monitor_bindings_identical():
        log('Entering monitor_bindings_identical')
        configured_bindings = get_configured_monitor_bindings()
        actual_bindings = get_actual_monitor_bindings()

        configured_key_set = set(configured_bindings.keys())
        actual_key_set = set(actual_bindings.keys())
        symmetrical_diff = configured_key_set ^ actual_key_set
        for default_monitor in ('tcp-default', 'ping-default'):
            if default_monitor in symmetrical_diff:
                log('Excluding %s monitor from key comparison' % default_monitor)
                symmetrical_diff.remove(default_monitor)
        if len(symmetrical_diff) > 0:
            return False

        # Compare key to key
        for key in configured_key_set:
            configured_proxy=configured_bindings[key]
            if any([configured_proxy.monitorname != actual_bindings[key].monitor_name,
                    configured_proxy.servicename !=  actual_bindings[key].name]):
                return False

        # Fallthrought to success
        return True
Example #46
0
def get_actual_monitor_bindings(client, module):
    log('Entering get_actual_monitor_bindings')
    bindings = {}
    try:
        # count() raises nitro exception instead of returning 0
        count = servicegroup_lbmonitor_binding.count(
            client, module.params['servicegroupname'])
    except nitro_exception as e:
        if e.errorcode == 258:
            return bindings
        else:
            raise

    if count == 0:
        return bindings

    # Fallthrough to rest of execution
    for binding in servicegroup_lbmonitor_binding.get(
            client, module.params['servicegroupname']):
        log('Gettign actual monitor with name %s' % binding.monitor_name)
        key = binding.monitor_name
        bindings[key] = binding

    return bindings
def sync_cs_policybindings(client, module):
    log('Syncing cs policybindings')

    # Delete all actual bindings
    for binding in get_actual_policybindings(client, module).values():
        log('Deleting binding for policy %s' % binding.policyname)
        csvserver_cspolicy_binding.delete(client, binding)

    # Add all configured bindings

    for binding in get_configured_policybindings(client, module).values():
        log('Adding binding for policy %s' % binding.policyname)
        binding.add()
Example #48
0
def sync_cs_policybindings(client, module):
    log('Syncing cs policybindings')

    # Delete all actual bindings
    for binding in get_actual_policybindings(client, module).values():
        log('Deleting binding for policy %s' % binding.policyname)
        csvserver_cspolicy_binding.delete(client, binding)

    # Add all configured bindings

    for binding in get_configured_policybindings(client, module).values():
        log('Adding binding for policy %s' % binding.policyname)
        binding.add()
Example #49
0
    def service_bindings_identical():
        log('service_bindings_identical')

        # Compare servicegroup keysets
        configured_servicegroup_bindings = get_configured_servicegroup_bindings()
        servicegroup_bindings = get_actual_servicegroup_bindings()
        configured_keyset = set(configured_servicegroup_bindings.keys())
        service_keyset = set(servicegroup_bindings.keys())
        log('len %s' % len(configured_keyset ^ service_keyset))
        if len(configured_keyset ^ service_keyset) > 0:
            return False

        # Compare servicegroup item to item
        for key in configured_servicegroup_bindings.keys():
            conf = configured_servicegroup_bindings[key]
            serv = servicegroup_bindings[key]
            log('sg diff %s' % conf.diff_object(serv))
            if not conf.has_equal_attributes(serv):
                return False

        # Compare service keysets
        configured_service_bindings = get_configured_service_bindings()
        service_bindings = get_actual_service_bindings()
        configured_keyset = set(configured_service_bindings.keys())
        service_keyset = set(service_bindings.keys())
        if len(configured_keyset ^ service_keyset) > 0:
            return False

        # Compare service item to item
        for key in configured_service_bindings.keys():
            conf = configured_service_bindings[key]
            serv = service_bindings[key]
            log('s diff %s' % conf.diff_object(serv))
            if not conf.has_equal_attributes(serv):
                return False

        # Fallthrough to success
        return True
    def sync_monitor_bindings():
        log('Entering sync_monitor_bindings')
        # Delete existing bindings
        for binding in get_actual_monitor_bindings().values():
            b = lbmonitor_service_binding()
            b.monitorname = binding.monitor_name
            b.servicename = module.params['name']
            # Cannot remove default monitor bindings
            if b.monitorname in ('tcp-default', 'ping-default'):
                continue
            lbmonitor_service_binding.delete(client, b)
            continue

            binding.monitorname = binding.monitor_name
            log('Will delete %s' % dir(binding))
            log('Name %s' % binding.name)
            log('monitor Name %s' % binding.monitor_name)
            binding.delete(client, binding)
            #service_lbmonitor_binding.delete(client, binding)

        # Apply configured bindings

        for binding in get_configured_monitor_bindings().values():
            binding.add()
def sync_cs_policybindings(client, module):
    log('Syncing cs policybindings')
    actual_bindings = get_actual_policybindings(client, module)
    configured_bindings = get_configured_policybindings(client, module)

    # Delete actual bindings not in configured
    delete_keys = list(set(actual_bindings.keys()) - set(configured_bindings.keys()))
    for key in delete_keys:
        log('Deleting binding for policy %s' % key)
        csvserver_cspolicy_binding.delete(client, actual_bindings[key])

    # Add configured bindings not in actual
    add_keys = list(set(configured_bindings.keys()) - set(actual_bindings.keys()))
    for key in add_keys:
        log('Adding binding for policy %s' % key)
        configured_bindings[key].add()

    # Update existing if changed
    modify_keys = list(set(configured_bindings.keys()) & set(actual_bindings.keys()))
    for key in modify_keys:
        if not configured_bindings[key].has_equal_attributes(actual_bindings[key]):
            log('Updating binding for policy %s' % key)
            csvserver_cspolicy_binding.delete(client, actual_bindings[key])
            configured_bindings[key].add()
Example #52
0
def ssl_certkey_bindings_sync(client, module):
    log('Syncing certkey bindings')
    vservername = module.params['name']
    if sslvserver_sslcertkey_binding.count(client, vservername) == 0:
        bindings = []
    else:
        bindings = sslvserver_sslcertkey_binding.get(client, vservername)

    # Delete existing bindings
    for binding in bindings:
        log('Deleting existing binding for certkey %s' % binding.certkeyname)
        sslvserver_sslcertkey_binding.delete(client, binding)

    # Add binding if appropriate
    if module.params['ssl_certkey'] is not None:
        log('Adding binding for certkey %s' % module.params['ssl_certkey'])
        binding = sslvserver_sslcertkey_binding()
        binding.vservername = module.params['name']
        binding.certkeyname = module.params['ssl_certkey']
        sslvserver_sslcertkey_binding.add(client, binding)
Example #53
0
def monitor_bindings_identical(client, module):
    log('monitor_bindings_identical')
    actual_bindings = get_actual_monitor_bindings(client, module)
    configured_proxys = get_configured_monitor_bindings(client, module)

    actual_keyset = set(actual_bindings.keys())
    configured_keyset = set(configured_proxys.keys())

    symmetric_difference = actual_keyset ^ configured_keyset
    if len(symmetric_difference) != 0:
        log('Symmetric difference %s' % symmetric_difference)
        return False

    # Item for item equality test
    for key, proxy in configured_proxys.items():
        if not proxy.has_equal_attributes(actual_bindings[key]):
            log('monitor binding difference %s' % proxy.diff_object(actual_bindings[key]))
            return False

    # Fallthrough to True result
    return True
Example #54
0
def main():

    module_specific_arguments = dict(
        name=dict(type='str'),
        ip=dict(type='str'),
        servername=dict(type='str'),
        servicetype=dict(
            type='str',
            choices=[
                'HTTP',
                'FTP',
                'TCP',
                'UDP',
                'SSL',
                'SSL_BRIDGE',
                'SSL_TCP',
                'DTLS',
                'NNTP',
                'RPCSVR',
                'DNS',
                'ADNS',
                'SNMP',
                'RTSP',
                'DHCPRA',
                'ANY',
                'SIP_UDP',
                'SIP_TCP',
                'SIP_SSL',
                'DNS_TCP',
                'ADNS_TCP',
                'MYSQL',
                'MSSQL',
                'ORACLE',
                'RADIUS',
                'RADIUSListener',
                'RDP',
                'DIAMETER',
                'SSL_DIAMETER',
                'TFTP',
                'SMPP',
                'PPTP',
                'GRE',
                'SYSLOGTCP',
                'SYSLOGUDP',
                'FIX',
                'SSL_FIX'
            ]
        ),
        port=dict(type='int'),
        cleartextport=dict(type='int'),
        cachetype=dict(
            type='str',
            choices=[
                'TRANSPARENT',
                'REVERSE',
                'FORWARD',
            ]
        ),
        maxclient=dict(type='float'),
        healthmonitor=dict(
            type='bool',
            default=True,
        ),
        maxreq=dict(type='float'),
        cacheable=dict(
            type='bool',
            default=False,
        ),
        cip=dict(
            type='str',
            choices=[
                'enabled',
                'disabled',
            ]
        ),
        cipheader=dict(type='str'),
        usip=dict(type='bool'),
        useproxyport=dict(type='bool'),
        sp=dict(type='bool'),
        rtspsessionidremap=dict(
            type='bool',
            default=False,
        ),
        clttimeout=dict(type='float'),
        svrtimeout=dict(type='float'),
        customserverid=dict(
            type='str',
            default='None',
        ),
        cka=dict(type='bool'),
        tcpb=dict(type='bool'),
        cmp=dict(type='bool'),
        maxbandwidth=dict(type='float'),
        accessdown=dict(
            type='bool',
            default=False
        ),
        monthreshold=dict(type='float'),
        downstateflush=dict(
            type='str',
            choices=[
                'enabled',
                'disabled',
            ],
        ),
        tcpprofilename=dict(type='str'),
        httpprofilename=dict(type='str'),
        hashid=dict(type='float'),
        comment=dict(type='str'),
        appflowlog=dict(
            type='str',
            choices=[
                'enabled',
                'disabled',
            ],
        ),
        netprofile=dict(type='str'),
        processlocal=dict(
            type='str',
            choices=[
                'enabled',
                'disabled',
            ],
        ),
        dnsprofilename=dict(type='str'),
        ipaddress=dict(type='str'),
        graceful=dict(
            type='bool',
            default=False,
        ),
    )

    hand_inserted_arguments = dict(
        monitor_bindings=dict(type='list'),
        disabled=dict(
            type='bool',
            default=False,
        ),
    )

    argument_spec = dict()

    argument_spec.update(netscaler_common_arguments)

    argument_spec.update(module_specific_arguments)

    argument_spec.update(hand_inserted_arguments)

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    module_result = dict(
        changed=False,
        failed=False,
        loglines=loglines,
    )

    # Fail the module if imports failed
    if not PYTHON_SDK_IMPORTED:
        module.fail_json(msg='Could not load nitro python sdk')

    client = get_nitro_client(module)

    try:
        client.login()
    except nitro_exception as e:
        msg = "nitro exception during login. errorcode=%s, message=%s" % (str(e.errorcode), e.message)
        module.fail_json(msg=msg)
    except Exception as e:
        if str(type(e)) == "<class 'requests.exceptions.ConnectionError'>":
            module.fail_json(msg='Connection error %s' % str(e))
        elif str(type(e)) == "<class 'requests.exceptions.SSLError'>":
            module.fail_json(msg='SSL Error %s' % str(e))
        else:
            module.fail_json(msg='Unexpected error during login %s' % str(e))

    # Fallthrough to rest of execution

    # Instantiate Service Config object
    readwrite_attrs = [
        'name',
        'ip',
        'servername',
        'servicetype',
        'port',
        'cleartextport',
        'cachetype',
        'maxclient',
        'healthmonitor',
        'maxreq',
        'cacheable',
        'cip',
        'cipheader',
        'usip',
        'useproxyport',
        'sp',
        'rtspsessionidremap',
        'clttimeout',
        'svrtimeout',
        'customserverid',
        'cka',
        'tcpb',
        'cmp',
        'maxbandwidth',
        'accessdown',
        'monthreshold',
        'downstateflush',
        'tcpprofilename',
        'httpprofilename',
        'hashid',
        'comment',
        'appflowlog',
        'netprofile',
        'processlocal',
        'dnsprofilename',
        'ipaddress',
        'graceful',
    ]

    readonly_attrs = [
        'numofconnections',
        'policyname',
        'serviceconftype',
        'serviceconftype2',
        'value',
        'gslb',
        'dup_state',
        'publicip',
        'publicport',
        'svrstate',
        'monitor_state',
        'monstatcode',
        'lastresponse',
        'responsetime',
        'riseapbrstatsmsgcode2',
        'monstatparam1',
        'monstatparam2',
        'monstatparam3',
        'statechangetimesec',
        'statechangetimemsec',
        'tickssincelaststatechange',
        'stateupdatereason',
        'clmonowner',
        'clmonview',
        'serviceipstr',
        'oracleserverversion',
    ]

    immutable_attrs = [
        'name',
        'ip',
        'servername',
        'servicetype',
        'port',
        'cleartextport',
        'cachetype',
        'cipheader',
        'serverid',
        'state',
        'td',
        'monitor_name_svc',
        'riseapbrstatsmsgcode',
        'graceful',
        'all',
        'Internal',
        'newname',
    ]

    transforms = {
        'pathmonitorindv': ['bool_yes_no'],
        'cacheable': ['bool_yes_no'],
        'cka': ['bool_yes_no'],
        'pathmonitor': ['bool_yes_no'],
        'tcpb': ['bool_yes_no'],
        'sp': ['bool_on_off'],
        'graceful': ['bool_yes_no'],
        'usip': ['bool_yes_no'],
        'healthmonitor': ['bool_yes_no'],
        'useproxyport': ['bool_yes_no'],
        'rtspsessionidremap': ['bool_on_off'],
        'accessdown': ['bool_yes_no'],
        'cmp': ['bool_yes_no'],
        'cip': [lambda v: v.upper()],
        'downstateflush': [lambda v: v.upper()],
        'appflowlog': [lambda v: v.upper()],
        'processlocal': [lambda v: v.upper()],
    }

    monitor_bindings_rw_attrs = [
        'servicename',
        'servicegroupname',
        'dup_state',
        'dup_weight',
        'monitorname',
        'weight',
    ]

    # Translate module arguments to correspondign config oject attributes
    if module.params['ip'] is None:
        module.params['ip'] = module.params['ipaddress']

    service_proxy = ConfigProxy(
        actual=service(),
        client=client,
        attribute_values_dict=module.params,
        readwrite_attrs=readwrite_attrs,
        readonly_attrs=readonly_attrs,
        immutable_attrs=immutable_attrs,
        transforms=transforms,
    )

    try:

        # Apply appropriate state
        if module.params['state'] == 'present':
            log('Applying actions for state present')
            if not service_exists(client, module):
                if not module.check_mode:
                    service_proxy.add()
                    sync_monitor_bindings(client, module, monitor_bindings_rw_attrs)
                    if module.params['save_config']:
                        client.save_config()
                module_result['changed'] = True
            elif not all_identical(client, module, service_proxy, monitor_bindings_rw_attrs):

                # Check if we try to change value of immutable attributes
                diff_dict = diff(client, module, service_proxy)
                immutables_changed = get_immutables_intersection(service_proxy, diff_dict.keys())
                if immutables_changed != []:
                    msg = 'Cannot update immutable attributes %s. Must delete and recreate entity.' % (immutables_changed,)
                    module.fail_json(msg=msg, diff=diff_dict, **module_result)

                # Service sync
                if not service_identical(client, module, service_proxy):
                    if not module.check_mode:
                        service_proxy.update()

                # Monitor bindings sync
                if not monitor_bindings_identical(client, module, monitor_bindings_rw_attrs):
                    if not module.check_mode:
                        sync_monitor_bindings(client, module, monitor_bindings_rw_attrs)

                module_result['changed'] = True
                if not module.check_mode:
                    if module.params['save_config']:
                        client.save_config()
            else:
                module_result['changed'] = False

            if not module.check_mode:
                res = do_state_change(client, module, service_proxy)
                if res.errorcode != 0:
                    msg = 'Error when setting disabled state. errorcode: %s message: %s' % (res.errorcode, res.message)
                    module.fail_json(msg=msg, **module_result)

            # Sanity check for state
            if not module.check_mode:
                log('Sanity checks for state present')
                if not service_exists(client, module):
                    module.fail_json(msg='Service does not exist', **module_result)

                if not service_identical(client, module, service_proxy):
                    module.fail_json(msg='Service differs from configured', diff=diff(client, module, service_proxy), **module_result)

                if not monitor_bindings_identical(client, module, monitor_bindings_rw_attrs):
                    module.fail_json(msg='Monitor bindings are not identical', **module_result)

        elif module.params['state'] == 'absent':
            log('Applying actions for state absent')
            if service_exists(client, module):
                if not module.check_mode:
                    service_proxy.delete()
                    if module.params['save_config']:
                        client.save_config()
                module_result['changed'] = True
            else:
                module_result['changed'] = False

            # Sanity check for state
            if not module.check_mode:
                log('Sanity checks for state absent')
                if service_exists(client, module):
                    module.fail_json(msg='Service still exists', **module_result)

    except nitro_exception as e:
        msg = "nitro exception errorcode=%s, message=%s" % (str(e.errorcode), e.message)
        module.fail_json(msg=msg, **module_result)

    client.logout()
    module.exit_json(**module_result)
Example #55
0
def main():

    module_specific_arguments = dict(

        monitorname=dict(type='str'),

        type=dict(
            type='str',
            choices=[
                'PING',
                'TCP',
                'HTTP',
                'TCP-ECV',
                'HTTP-ECV',
                'UDP-ECV',
                'DNS',
                'FTP',
                'LDNS-PING',
                'LDNS-TCP',
                'LDNS-DNS',
                'RADIUS',
                'USER',
                'HTTP-INLINE',
                'SIP-UDP',
                'SIP-TCP',
                'LOAD',
                'FTP-EXTENDED',
                'SMTP',
                'SNMP',
                'NNTP',
                'MYSQL',
                'MYSQL-ECV',
                'MSSQL-ECV',
                'ORACLE-ECV',
                'LDAP',
                'POP3',
                'CITRIX-XML-SERVICE',
                'CITRIX-WEB-INTERFACE',
                'DNS-TCP',
                'RTSP',
                'ARP',
                'CITRIX-AG',
                'CITRIX-AAC-LOGINPAGE',
                'CITRIX-AAC-LAS',
                'CITRIX-XD-DDC',
                'ND6',
                'CITRIX-WI-EXTENDED',
                'DIAMETER',
                'RADIUS_ACCOUNTING',
                'STOREFRONT',
                'APPC',
                'SMPP',
                'CITRIX-XNC-ECV',
                'CITRIX-XDM',
                'CITRIX-STA-SERVICE',
                'CITRIX-STA-SERVICE-NHOP',
            ]
        ),

        action=dict(
            type='str',
            choices=[
                'NONE',
                'LOG',
                'DOWN',
            ]
        ),
        respcode=dict(type='list'),
        httprequest=dict(type='str'),
        rtsprequest=dict(type='str'),
        customheaders=dict(type='str'),
        maxforwards=dict(type='float'),
        sipmethod=dict(
            type='str',
            choices=[
                'OPTIONS',
                'INVITE',
                'REGISTER',
            ]
        ),
        sipuri=dict(type='str'),
        sipreguri=dict(type='str'),
        send=dict(type='str'),
        recv=dict(type='str'),
        query=dict(type='str'),
        querytype=dict(
            type='str',
            choices=[
                'Address',
                'Zone',
                'AAAA',
            ]
        ),
        scriptname=dict(type='str'),
        scriptargs=dict(type='str'),
        dispatcherip=dict(type='str'),
        dispatcherport=dict(type='int'),
        username=dict(type='str'),
        password=dict(type='str'),
        secondarypassword=dict(type='str'),
        logonpointname=dict(type='str'),
        lasversion=dict(type='str'),
        radkey=dict(type='str'),
        radnasid=dict(type='str'),
        radnasip=dict(type='str'),
        radaccounttype=dict(type='float'),
        radframedip=dict(type='str'),
        radapn=dict(type='str'),
        radmsisdn=dict(type='str'),
        radaccountsession=dict(type='str'),
        lrtm=dict(
            type='str',
            choices=[
                'enabled',
                'disabled',
            ]
        ),
        deviation=dict(type='float'),
        units1=dict(
            type='str',
            choices=[
                'SEC',
                'MSEC',
                'MIN',
            ]
        ),
        interval=dict(type='int'),
        units3=dict(
            type='str',
            choices=[
                'SEC',
                'MSEC',
                'MIN',
            ]
        ),
        resptimeout=dict(type='int'),
        units4=dict(
            type='str',
            choices=[
                'SEC',
                'MSEC',
                'MIN',
            ]
        ),
        resptimeoutthresh=dict(type='float'),
        retries=dict(type='int'),
        failureretries=dict(type='int'),
        alertretries=dict(type='int'),
        successretries=dict(type='int'),
        downtime=dict(type='int'),
        units2=dict(
            type='str',
            choices=[
                'SEC',
                'MSEC',
                'MIN',
            ]
        ),
        destip=dict(type='str'),
        destport=dict(type='int'),
        reverse=dict(type='bool'),
        transparent=dict(type='bool'),
        iptunnel=dict(type='bool'),
        tos=dict(type='bool'),
        tosid=dict(type='float'),
        secure=dict(type='bool'),
        validatecred=dict(type='bool'),
        domain=dict(type='str'),
        ipaddress=dict(type='list'),
        group=dict(type='str'),
        filename=dict(type='str'),
        basedn=dict(type='str'),
        binddn=dict(type='str'),
        filter=dict(type='str'),
        attribute=dict(type='str'),
        database=dict(type='str'),
        oraclesid=dict(type='str'),
        sqlquery=dict(type='str'),
        evalrule=dict(type='str'),
        mssqlprotocolversion=dict(
            type='str',
            choices=[
                '70',
                '2000',
                '2000SP1',
                '2005',
                '2008',
                '2008R2',
                '2012',
                '2014',
            ]
        ),
        Snmpoid=dict(type='str'),
        snmpcommunity=dict(type='str'),
        snmpthreshold=dict(type='str'),
        snmpversion=dict(
            type='str',
            choices=[
                'V1',
                'V2',
            ]
        ),
        application=dict(type='str'),
        sitepath=dict(type='str'),
        storename=dict(type='str'),
        storefrontacctservice=dict(type='bool'),
        hostname=dict(type='str'),
        netprofile=dict(type='str'),
        originhost=dict(type='str'),
        originrealm=dict(type='str'),
        hostipaddress=dict(type='str'),
        vendorid=dict(type='float'),
        productname=dict(type='str'),
        firmwarerevision=dict(type='float'),
        authapplicationid=dict(type='list'),
        acctapplicationid=dict(type='list'),
        inbandsecurityid=dict(
            type='str',
            choices=[
                'NO_INBAND_SECURITY',
                'TLS',
            ]
        ),
        supportedvendorids=dict(type='list'),
        vendorspecificvendorid=dict(type='float'),
        vendorspecificauthapplicationids=dict(type='list'),
        vendorspecificacctapplicationids=dict(type='list'),
        storedb=dict(
            type='str',
            choices=[
                'enabled',
                'disabled',
            ]
        ),
        storefrontcheckbackendservices=dict(type='bool'),
        trofscode=dict(type='float'),
        trofsstring=dict(type='str'),
    )

    hand_inserted_arguments = dict()

    argument_spec = dict()
    argument_spec.update(module_specific_arguments)
    argument_spec.update(netscaler_common_arguments)
    argument_spec.update(hand_inserted_arguments)

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

    module_result = dict(
        changed=False,
        failed=False,
        loglines=loglines,
    )

    # Fail the module if imports failed
    if not PYTHON_SDK_IMPORTED:
        module.fail_json(msg='Could not load nitro python sdk', **module_result)

    # Fallthrough to rest of execution
    client = get_nitro_client(module)

    try:
        client.login()
    except nitro_exception as e:
        msg = "nitro exception during login. errorcode=%s, message=%s" % (str(e.errorcode), e.message)
        module.fail_json(msg=msg)
    except Exception as e:
        if str(type(e)) == "<class 'requests.exceptions.ConnectionError'>":
            module.fail_json(msg='Connection error %s' % str(e))
        elif str(type(e)) == "<class 'requests.exceptions.SSLError'>":
            module.fail_json(msg='SSL Error %s' % str(e))
        else:
            module.fail_json(msg='Unexpected error during login %s' % str(e))

    # Instantiate lb monitor object
    readwrite_attrs = [
        'monitorname',
        'type',
        'action',
        'respcode',
        'httprequest',
        'rtsprequest',
        'customheaders',
        'maxforwards',
        'sipmethod',
        'sipuri',
        'sipreguri',
        'send',
        'recv',
        'query',
        'querytype',
        'scriptname',
        'scriptargs',
        'dispatcherip',
        'dispatcherport',
        'username',
        'password',
        'secondarypassword',
        'logonpointname',
        'lasversion',
        'radkey',
        'radnasid',
        'radnasip',
        'radaccounttype',
        'radframedip',
        'radapn',
        'radmsisdn',
        'radaccountsession',
        'lrtm',
        'deviation',
        'units1',
        'interval',
        'units3',
        'resptimeout',
        'units4',
        'resptimeoutthresh',
        'retries',
        'failureretries',
        'alertretries',
        'successretries',
        'downtime',
        'units2',
        'destip',
        'destport',
        'reverse',
        'transparent',
        'iptunnel',
        'tos',
        'tosid',
        'secure',
        'validatecred',
        'domain',
        'ipaddress',
        'group',
        'filename',
        'basedn',
        'binddn',
        'filter',
        'attribute',
        'database',
        'oraclesid',
        'sqlquery',
        'evalrule',
        'mssqlprotocolversion',
        'Snmpoid',
        'snmpcommunity',
        'snmpthreshold',
        'snmpversion',
        'application',
        'sitepath',
        'storename',
        'storefrontacctservice',
        'netprofile',
        'originhost',
        'originrealm',
        'hostipaddress',
        'vendorid',
        'productname',
        'firmwarerevision',
        'authapplicationid',
        'acctapplicationid',
        'inbandsecurityid',
        'supportedvendorids',
        'vendorspecificvendorid',
        'vendorspecificauthapplicationids',
        'vendorspecificacctapplicationids',
        'storedb',
        'storefrontcheckbackendservices',
        'trofscode',
        'trofsstring',
    ]

    readonly_attrs = [
        'lrtmconf',
        'lrtmconfstr',
        'dynamicresponsetimeout',
        'dynamicinterval',
        'multimetrictable',
        'dup_state',
        'dup_weight',
        'weight',
    ]

    immutable_attrs = [
        'monitorname',
        'type',
        'units1',
        'units3',
        'units4',
        'units2',
        'Snmpoid',
        'hostname',
        'servicename',
        'servicegroupname',
    ]

    transforms = {
        'storefrontcheckbackendservices': ['bool_yes_no'],
        'secure': ['bool_yes_no'],
        'tos': ['bool_yes_no'],
        'validatecred': ['bool_yes_no'],
        'storefrontacctservice': ['bool_yes_no'],
        'iptunnel': ['bool_yes_no'],
        'transparent': ['bool_yes_no'],
        'reverse': ['bool_yes_no'],
        'lrtm': [lambda v: v.upper()],
        'storedb': [lambda v: v.upper()],
    }

    lbmonitor_proxy = ConfigProxy(
        actual=lbmonitor(),
        client=client,
        attribute_values_dict=module.params,
        readwrite_attrs=readwrite_attrs,
        readonly_attrs=readonly_attrs,
        immutable_attrs=immutable_attrs,
        transforms=transforms,
    )

    try:
        ensure_feature_is_enabled(client, 'LB')

        if module.params['state'] == 'present':
            log('Applying actions for state present')
            if not lbmonitor_exists(client, module):
                if not module.check_mode:
                    log('Adding monitor')
                    lbmonitor_proxy.add()
                    if module.params['save_config']:
                        client.save_config()
                module_result['changed'] = True
            elif not lbmonitor_identical(client, module, lbmonitor_proxy):

                # Check if we try to change value of immutable attributes
                immutables_changed = get_immutables_intersection(lbmonitor_proxy, diff_list(client, module, lbmonitor_proxy).keys())
                if immutables_changed != []:
                    diff = diff_list(client, module, lbmonitor_proxy)
                    msg = 'Cannot update immutable attributes %s' % (immutables_changed,)
                    module.fail_json(msg=msg, diff=diff, **module_result)

                if not module.check_mode:
                    log('Updating monitor')
                    lbmonitor_proxy.update()
                    if module.params['save_config']:
                        client.save_config()
                module_result['changed'] = True
            else:
                log('Doing nothing for monitor')
                module_result['changed'] = False

            # Sanity check for result
            log('Sanity checks for state present')
            if not module.check_mode:
                if not lbmonitor_exists(client, module):
                    module.fail_json(msg='lb monitor does not exist', **module_result)
                if not lbmonitor_identical(client, module, lbmonitor_proxy):
                    module.fail_json(
                        msg='lb monitor is not configured correctly',
                        diff=diff_list(client, module, lbmonitor_proxy),
                        **module_result
                    )

        elif module.params['state'] == 'absent':
            log('Applying actions for state absent')
            if lbmonitor_exists(client, module):
                if not module.check_mode:
                    lbmonitor_proxy.delete()
                    if module.params['save_config']:
                        client.save_config()
                module_result['changed'] = True
            else:
                module_result['changed'] = False

            # Sanity check for result
            log('Sanity checks for state absent')
            if not module.check_mode:
                if lbmonitor_exists(client, module):
                    module.fail_json(msg='lb monitor still exists', **module_result)

        module_result['actual_attributes'] = lbmonitor_proxy.get_actual_rw_attributes(filter='monitorname')
    except nitro_exception as e:
        msg = "nitro exception errorcode=%s, message=%s" % (str(e.errorcode), e.message)
        module.fail_json(msg=msg, **module_result)

    client.logout()

    module.exit_json(**module_result)
Example #56
0
def server_exists(client, module):
    log('Checking if server exists')
    if server.count_filtered(client, 'name:%s' % module.params['name']) > 0:
        return True
    else:
        return False
Example #57
0
def sync_monitor_bindings(client, module):
    log('sync_monitor_bindings')

    actual_monitor_bindings = get_actual_monitor_bindings(client, module)
    configured_monitor_proxys = get_configured_monitor_bindings(client, module)

    # Delete actual bindings not in configured bindings
    for monitor_name, actual_binding in actual_monitor_bindings.items():
        if monitor_name not in configured_monitor_proxys.keys():
            log('Deleting absent binding for monitor %s' % monitor_name)
            log('dir is %s' % dir(actual_binding))
            gslbservice_lbmonitor_binding.delete(client, actual_binding)

    # Delete and re-add actual bindings that differ from configured
    for proxy_key, binding_proxy in configured_monitor_proxys.items():
        if proxy_key in actual_monitor_bindings:
            actual_binding = actual_monitor_bindings[proxy_key]
            if not binding_proxy.has_equal_attributes(actual_binding):
                log('Deleting differing binding for monitor %s' % actual_binding.monitor_name)
                log('dir %s' % dir(actual_binding))
                log('attribute monitor_name %s' % getattr(actual_binding, 'monitor_name'))
                log('attribute monitorname %s' % getattr(actual_binding, 'monitorname', None))
                gslbservice_lbmonitor_binding.delete(client, actual_binding)
                log('Adding anew binding for monitor %s' % binding_proxy.monitor_name)
                binding_proxy.add()

    # Add configured monitors that are missing from actual
    for proxy_key, binding_proxy in configured_monitor_proxys.items():
        if proxy_key not in actual_monitor_bindings.keys():
            log('Adding monitor binding for monitor %s' % binding_proxy.monitor_name)
            binding_proxy.add()
Example #58
0
def main():

    module_specific_arguments = dict(
        policyname=dict(type='str'),
        url=dict(type='str'),
        rule=dict(type='str'),
        domain=dict(type='str'),
        action=dict(type='str'),
    )

    hand_inserted_arguments = dict(
    )

    argument_spec = dict()

    argument_spec.update(netscaler_common_arguments)
    argument_spec.update(module_specific_arguments)
    argument_spec.update(hand_inserted_arguments)

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    module_result = dict(
        changed=False,
        failed=False,
        loglines=loglines,
    )

    # Fail the module if imports failed
    if not PYTHON_SDK_IMPORTED:
        module.fail_json(msg='Could not load nitro python sdk')

    # Fallthrough to rest of execution
    client = get_nitro_client(module)

    try:
        client.login()
    except nitro_exception as e:
        msg = "nitro exception during login. errorcode=%s, message=%s" % (str(e.errorcode), e.message)
        module.fail_json(msg=msg)
    except Exception as e:
        if str(type(e)) == "<class 'requests.exceptions.ConnectionError'>":
            module.fail_json(msg='Connection error %s' % str(e))
        elif str(type(e)) == "<class 'requests.exceptions.SSLError'>":
            module.fail_json(msg='SSL Error %s' % str(e))
        else:
            module.fail_json(msg='Unexpected error during login %s' % str(e))

    readwrite_attrs = [
        'policyname',
        'url',
        'rule',
        'domain',
        'action',
    ]
    readonly_attrs = [
        'vstype',
        'hits',
        'bindhits',
        'labelname',
        'labeltype',
        'priority',
        'activepolicy',
        'cspolicytype',
    ]

    transforms = {
    }

    # Instantiate config proxy
    cspolicy_proxy = ConfigProxy(
        actual=cspolicy(),
        client=client,
        attribute_values_dict=module.params,
        readwrite_attrs=readwrite_attrs,
        readonly_attrs=readonly_attrs,
        transforms=transforms,
    )

    try:
        ensure_feature_is_enabled(client, 'CS')

        # Apply appropriate state
        if module.params['state'] == 'present':
            log('Sanity checks for state present')
            if not policy_exists(client, module):
                if not module.check_mode:
                    cspolicy_proxy.add()
                    if module.params['save_config']:
                        client.save_config()
                module_result['changed'] = True
            elif not policy_identical(client, module, cspolicy_proxy):
                if not module.check_mode:
                    cspolicy_proxy.update()
                    if module.params['save_config']:
                        client.save_config()
                module_result['changed'] = True
            else:
                module_result['changed'] = False

            # Sanity check for state
            if not module.check_mode:
                log('Sanity checks for state present')
                if not policy_exists(client, module):
                    module.fail_json(msg='Policy does not exist', **module_result)
                if not policy_identical(client, module, cspolicy_proxy):
                    module.fail_json(msg='Policy differs from configured', diff=diff_list(client, module, cspolicy_proxy), **module_result)

        elif module.params['state'] == 'absent':
            log('Applying actions for state absent')
            if policy_exists(client, module):
                if not module.check_mode:
                    cspolicy_proxy.delete()
                    if module.params['save_config']:
                        client.save_config()
                module_result['changed'] = True
            else:
                module_result['changed'] = False

            # Sanity check for state
            if not module.check_mode:
                log('Sanity checks for state absent')
                if policy_exists(client, module):
                    module.fail_json(msg='Policy still exists', **module_result)

    except nitro_exception as e:
        msg = "nitro exception errorcode=%s, message=%s" % (str(e.errorcode), e.message)
        module.fail_json(msg=msg, **module_result)

    client.logout()
    module.exit_json(**module_result)
Example #59
0
def lbmonitor_exists(client, module):
    log('Checking if monitor exists')
    if lbmonitor.count_filtered(client, 'monitorname:%s' % module.params['monitorname']) > 0:
        return True
    else:
        return False
Example #60
0
def main():

    module_specific_arguments = dict(
        name=dict(type='str'),
        ipaddress=dict(type='str'),
        domain=dict(type='str'),
        translationip=dict(type='str'),
        translationmask=dict(type='str'),
        domainresolveretry=dict(type='int'),
        ipv6address=dict(
            type='bool',
            default=False
        ),
        comment=dict(type='str'),
        td=dict(type='float'),
    )

    hand_inserted_arguments = dict(
        disabled=dict(
            type='bool',
            default=False,
        ),
    )

    argument_spec = dict()

    argument_spec.update(netscaler_common_arguments)
    argument_spec.update(module_specific_arguments)
    argument_spec.update(hand_inserted_arguments)

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    module_result = dict(
        changed=False,
        failed=False,
        loglines=loglines,
    )

    # Fail the module if imports failed
    if not PYTHON_SDK_IMPORTED:
        module.fail_json(msg='Could not load nitro python sdk')

    # Fallthrough to rest of execution

    client = get_nitro_client(module)
    try:
        client.login()
    except nitro_exception as e:
        msg = "nitro exception during login. errorcode=%s, message=%s" % (str(e.errorcode), e.message)
        module.fail_json(msg=msg)
    except Exception as e:
        if str(type(e)) == "<class 'requests.exceptions.ConnectionError'>":
            module.fail_json(msg='Connection error %s' % str(e))
        elif str(type(e)) == "<class 'requests.exceptions.SSLError'>":
            module.fail_json(msg='SSL Error %s' % str(e))
        else:
            module.fail_json(msg='Unexpected error during login %s' % str(e))

    # Instantiate Server Config object
    readwrite_attrs = [
        'name',
        'ipaddress',
        'domain',
        'translationip',
        'translationmask',
        'domainresolveretry',
        'ipv6address',
        'comment',
        'td',
    ]

    readonly_attrs = [
        'statechangetimesec',
        'tickssincelaststatechange',
        'autoscale',
        'customserverid',
        'monthreshold',
        'maxclient',
        'maxreq',
        'maxbandwidth',
        'usip',
        'cka',
        'tcpb',
        'cmp',
        'clttimeout',
        'svrtimeout',
        'cipheader',
        'cip',
        'cacheable',
        'sc',
        'sp',
        'downstateflush',
        'appflowlog',
        'boundtd',
        '__count',
    ]

    immutable_attrs = [
        'name',
        'domain',
        'ipv6address',
        'td',
    ]

    transforms = {
        'ipv6address': ['bool_yes_no'],
    }

    server_proxy = ConfigProxy(
        actual=server(),
        client=client,
        attribute_values_dict=module.params,
        readwrite_attrs=readwrite_attrs,
        readonly_attrs=readonly_attrs,
        immutable_attrs=immutable_attrs,
        transforms=transforms,
    )

    try:

        # Apply appropriate state
        if module.params['state'] == 'present':
            log('Applying actions for state present')
            if not server_exists(client, module):
                if not module.check_mode:
                    server_proxy.add()
                    if module.params['save_config']:
                        client.save_config()
                module_result['changed'] = True
            elif not server_identical(client, module, server_proxy):

                # Check if we try to change value of immutable attributes
                immutables_changed = get_immutables_intersection(server_proxy, diff_list(client, module, server_proxy).keys())
                if immutables_changed != []:
                    msg = 'Cannot update immutable attributes %s' % (immutables_changed,)
                    module.fail_json(msg=msg, diff=diff_list(client, module, server_proxy), **module_result)
                if not module.check_mode:
                    server_proxy.update()
                    if module.params['save_config']:
                        client.save_config()
                module_result['changed'] = True
            else:
                module_result['changed'] = False

            if not module.check_mode:
                res = do_state_change(client, module, server_proxy)
                if res.errorcode != 0:
                    msg = 'Error when setting disabled state. errorcode: %s message: %s' % (res.errorcode, res.message)
                    module.fail_json(msg=msg, **module_result)

            # Sanity check for result
            log('Sanity checks for state present')
            if not module.check_mode:
                if not server_exists(client, module):
                    module.fail_json(msg='Server does not seem to exist', **module_result)
                if not server_identical(client, module, server_proxy):
                    module.fail_json(
                        msg='Server is not configured according to parameters given',
                        diff=diff_list(client, module, server_proxy),
                        **module_result
                    )

        elif module.params['state'] == 'absent':
            log('Applying actions for state absent')
            if server_exists(client, module):
                if not module.check_mode:
                    server_proxy.delete()
                    if module.params['save_config']:
                        client.save_config()
                module_result['changed'] = True
            else:
                module_result['changed'] = False

            # Sanity check for result
            log('Sanity checks for state absent')
            if not module.check_mode:
                if server_exists(client, module):
                    module.fail_json(msg='Server seems to be present', **module_result)

    except nitro_exception as e:
        msg = "nitro exception errorcode=%s, message=%s" % (str(e.errorcode), e.message)
        module.fail_json(msg=msg, **module_result)

    client.logout()
    module.exit_json(**module_result)