def get_configured_service_members(client, module):
    log('get_configured_service_members')
    readwrite_attrs = [
        'servicegroupname', 'ip', 'port', 'state', 'hashid', 'serverid',
        'servername', 'customserverid', 'weight'
    ]
    readonly_attrs = [
        'delay',
        'statechangetimesec',
        'svrstate',
        'tickssincelaststatechange',
        'graceful',
    ]

    members = []
    if module.params['servicemembers'] is None:
        return 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
def default_lb_vserver_identical(client, module):
    d = get_default_lb_vserver(client, module)
    configured = ConfigProxy(actual=csvserver_lbvserver_binding(),
                             client=client,
                             readwrite_attrs=[
                                 'name',
                                 'lbvserver',
                             ],
                             attribute_values_dict={
                                 'name': module.params['name'],
                                 'lbvserver': module.params['lbvserver'],
                             })
    log('default lb vserver %s' % ((d.name, d.lbvserver), ))
    if d.name is None and module.params['lbvserver'] is None:
        log('Default lb vserver identical missing')
        return True
    elif d.name is not None and module.params['lbvserver'] is None:
        log('Default lb vserver needs removing')
        return False
    elif configured.has_equal_attributes(d):
        log('Default lb vserver identical')
        return True
    else:
        log('Default lb vserver not identical')
        return False
def get_configured_monitor_bindings(client, module):
    log('Entering get_configured_monitor_bindings')
    bindings = {}
    if 'monitorbindings' in module.params and module.params[
            'monitorbindings'] is not None:
        for binding in module.params['monitorbindings']:
            readwrite_attrs = [
                'monitorname',
                'servicegroupname',
                'weight',
            ]
            readonly_attrs = []
            attribute_values_dict = copy.deepcopy(binding)
            attribute_values_dict['servicegroupname'] = module.params[
                'servicegroupname']
            binding_proxy = ConfigProxy(
                actual=lbmonitor_servicegroup_binding(),
                client=client,
                attribute_values_dict=attribute_values_dict,
                readwrite_attrs=readwrite_attrs,
                readonly_attrs=readonly_attrs,
            )
            key = attribute_values_dict['monitorname']
            bindings[key] = binding_proxy
    return bindings
Exemplo n.º 4
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
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
Exemplo n.º 6
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 sync_monitor_bindings(client, module):
    log('Entering sync_monitor_bindings')

    actual_bindings = get_actual_monitor_bindings(client, module)

    # Exclude default monitors from deletion
    for monitorname in ('tcp-default', 'ping-default'):
        if monitorname in actual_bindings:
            del actual_bindings[monitorname]

    configured_bindings = get_configured_monitor_bindings(client, module)

    to_remove = list(
        set(actual_bindings.keys()) - set(configured_bindings.keys()))
    to_add = list(
        set(configured_bindings.keys()) - set(actual_bindings.keys()))
    to_modify = list(
        set(configured_bindings.keys()) & set(actual_bindings.keys()))

    # Delete existing and modifiable bindings
    for key in to_remove + to_modify:
        binding = actual_bindings[key]
        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)

    # Add new and modified bindings
    for key in to_add + to_modify:
        binding = configured_bindings[key]
        log('Adding %s' % binding.monitorname)
        binding.add()
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()
Exemplo n.º 9
0
def policy_exists(client, module):
    log('Checking if policy exists')
    if cspolicy.count_filtered(
            client, 'policyname:%s' % module.params['policyname']) > 0:
        return True
    else:
        return False
def servicegroup_identical(client, module, servicegroup_proxy):
    log('Checking if service group is identical')
    servicegroups = servicegroup.get_filtered(
        client, 'servicegroupname:%s' % module.params['servicegroupname'])
    if servicegroup_proxy.has_equal_attributes(servicegroups[0]):
        return True
    else:
        return False
def do_state_change(client, module, servicegroup_proxy):
    if module.params['disabled']:
        log('Disabling service')
        result = servicegroup.disable(client, servicegroup_proxy.actual)
    else:
        log('Enabling service')
        result = servicegroup.enable(client, servicegroup_proxy.actual)
    return result
def do_state_change(client, module, csvserver_proxy):
    if module.params['disabled']:
        log('Disabling cs vserver')
        result = csvserver.disable(client, csvserver_proxy.actual)
    else:
        log('Enabling cs vserver')
        result = csvserver.enable(client, csvserver_proxy.actual)
    return result
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 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
 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')
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 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
Exemplo n.º 18
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)
def monitor_bindings_identical(client, module):
    log('Entering monitor_bindings_identical')
    configured_bindings = get_configured_monitor_bindings(client, module)
    actual_bindings = get_actual_monitor_bindings(client, module)

    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]

        # Follow nscli convention for missing weight value
        if not hasattr(configured_proxy, 'weight'):
            configured_proxy.weight = 1
        log('configured_proxy %s' % [
            configured_proxy.monitorname, configured_proxy.servicegroupname,
            configured_proxy.weight
        ])
        log('actual_bindings %s' % [
            actual_bindings[key].monitor_name,
            actual_bindings[key].servicegroupname, actual_bindings[key].weight
        ])
        if not monitor_binding_equal(configured_proxy, actual_bindings[key]):
            return False

    # Fallthrought to success
    return True
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()
Exemplo n.º 21
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 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
    diff = diff_list(client, module, server_proxy)

    # Remove options that are not present in nitro server object
    # These are special options relevant to the disabled action
    for option in ['graceful', 'delay']:
        if option in diff:
            del diff[option]

    if diff == {}:
        return True
    else:
        return False
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_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
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 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 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 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()
def sync_default_lb_vserver(client, module):
    d = get_default_lb_vserver(client, module)

    if module.params['lbvserver'] is not None:
        configured = ConfigProxy(actual=csvserver_lbvserver_binding(),
                                 client=client,
                                 readwrite_attrs=[
                                     'name',
                                     'lbvserver',
                                 ],
                                 attribute_values_dict={
                                     'name': module.params['name'],
                                     'lbvserver': module.params['lbvserver'],
                                 })

        if not configured.has_equal_attributes(d):
            if d.name is not None:
                log('Deleting default lb vserver %s' % d.lbvserver)
                csvserver_lbvserver_binding.delete(client, d)
            log('Adding default lb vserver %s' % configured.lbvserver)
            configured.add()
    else:
        if d.name is not None:
            log('Deleting default lb vserver %s' % d.lbvserver)
            csvserver_lbvserver_binding.delete(client, d)
Exemplo n.º 30
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()