Exemplo n.º 1
0
    def delete_resource(self):
        log('ModuleExecutor.delete_resource()')

        if self.resource_exists():
            self.module_result['changed'] = True
            if not self.module.check_mode:
                self.resource_delete()
def policy_exists(client, module):
    log('Checking if policy exists')
    try:
        cspolicy.get(client, module.params['policyname'])
        return True
    except Exception:
        return False
def lbmonitor_get(client, module):
    log('Getting lb monitor')
    try:
        lbmonitor_inst = lbmonitor.get(client, module.params['monitorname'])
        return True, lbmonitor_inst
    except nitro_exception:
        return False, None
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.º 5
0
    def non_updateable_object_identical(self):
        log('ModuleExecutor.non_updateable_object_identical()')

        ret_val = True

        if self.retrieved_object is None:
            raise Exception('Should have a retrieved object by now.')

        for attribute in self.module.params['resource'].keys():
            configured_value = self.module.params['resource'][attribute]
            retrieved_value = self.retrieved_object.get(attribute)
            if configured_value != retrieved_value:
                ret_val = False
                str_tuple = (
                    attribute,
                    type(configured_value),
                    configured_value,
                    type(retrieved_value),
                    retrieved_value,
                )
                self.differing_attributes.append(attribute)
                log('Attribute "%s" differs. Playbook parameter: (%s) %s. Retrieved NITRO object: (%s) %s'
                    % str_tuple)

        return ret_val
def server_exists(client, module):
    log('Checking if server exists')
    try:
        server.get(client, module.params['name'])
        return True
    except nitro_exception:
        return False
Exemplo n.º 7
0
def do_state_change(client, module, service_proxy):
    if module.params['disabled']:
        log('Disabling service')
        result = service.disable(client, service_proxy.actual)
    else:
        log('Enabling service')
        result = service.enable(client, service_proxy.actual)
    return result
def do_state_change(client, module, gslb_vserver_proxy):
    if module.params['disabled']:
        log('Disabling glsb_vserver')
        result = gslbvserver.disable(client, gslb_vserver_proxy.actual)
    else:
        log('Enabling gslbvserver')
        result = gslbvserver.enable(client, gslb_vserver_proxy.actual)
    return result
def main():

    argument_spec = dict()

    module_specific_arguments = dict(
        username=dict(
            type='str',
            required=True,
        ),
        password=dict(
            type='str',
            required=True,
            no_log=True,
        ),
        new_password=dict(
            type='str',
            required=True,
            no_log=True,
        ),
        nsip=dict(type='str'),
        nitro_protocol=dict(
            required=True,
            type='str',
            choices=['https', 'http'],
        ),
        validate_certs=dict(required=True, type='bool'),
    )

    argument_spec.update(module_specific_arguments)

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=False,
    )
    post_data = {
        'login': {
            'username': module.params['username'],
            'password': module.params['password'],
            'new_password': module.params['new_password'],
        }
    }

    fetcher = NitroAPIFetcher(module)
    result = fetcher.post(post_data=post_data, resource='login')

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

    log('{0}'.format(result))
    if result['nitro_errorcode'] == 0:
        module_result['changed'] = True
        module.exit_json(**module_result)
    else:
        msg = 'Non zero nitro errorcode {0}'.format(result['nitro_errorcode'])
        module.fail_json(msg=msg, **module_result)
Exemplo n.º 10
0
 def _get_binding_key_tuple(self, binding_dict):
     log('ModuleExecutor._get_binding_key_tuple()')
     ret_val = []
     # Order of attribute values is determined by ordering of self.key_attributes_present
     for attribute in self.key_attributes_present:
         if attribute in binding_dict:
             attribute_value = binding_dict[attribute]
             ret_val.append(attribute_value)
     return tuple(ret_val)
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
Exemplo n.º 12
0
 def resource_delete(self):
     log('ModuleExecutor.resource_delete()')
     if self.lifecycle == 'object':
         self.object_delete()
     elif self.lifecycle == 'binding':
         self.binding_delete()
     elif self.lifecycle == 'bindings_list':
         self.bindings_list_delete()
     elif self.lifecycle == 'non_updateable_object':
         return self.non_updateable_object_delete()
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)

    if not module.params['mas_proxy_call']:
        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)

    if not module.params['mas_proxy_call']:
        client.logout()

    module.exit_json(**module_result)
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 sync_binding_with_data(self, data):

        binding_key = data['binding_key']
        binding_object = data['binding_object']

        if self.module.params.get(binding_key) is None:
            return

        log('ModuleExecutor syncing binding %s' % binding_key)

        mode = self.module.params[binding_key]['mode']

        # Make a list of config objects for configured bindings
        configured_bindings = []
        for bind_values in self.module.params[binding_key]['attributes']:
            all_bind_values = copy.deepcopy(bind_values)
            configured_binding = NitroResourceConfig(
                module=self.module,
                resource=binding_object,
                attribute_values_dict=all_bind_values,
                attributes_list=self.attribute_config[binding_key]
                ['attributes_list'],
                transforms=self.attribute_config[binding_key]['transforms'],
            )

            configured_bindings.append(configured_binding)

        if mode == 'bind':
            for configured_binding in configured_bindings:
                self.module_result['changed'] = True
                try:
                    configured_binding.create()
                except NitroException as e:
                    if e.errorcode != 273:
                        raise

        elif mode == 'unbind':
            for configured_binding in configured_bindings:
                self.module_result['changed'] = True
                try:
                    configured_binding.delete(
                        delete_id_attributes=self.attribute_config[binding_key]
                        ['delete_id_attributes'])
                except NitroException as e:
                    # Handle exceptions when trying to unbind objects that are not bound
                    # Every binding has its own errorcode
                    if binding_object == 'appfwglobal_appfwpolicy_binding':
                        if e.errorcode == 3093:
                            log('Ignoring nitro_errocode 3093 for appfwglobal_appfwpolicy_binding'
                                )
                        else:
                            raise
Exemplo n.º 16
0
 def resource_exists(self):
     log('ModuleExecutor.resource_exists()')
     if self.lifecycle == 'object':
         return self.object_exists()
     elif self.lifecycle == 'binding':
         return self.binding_exists()
     elif self.lifecycle == 'bindings_list':
         return self.bindings_list_exists()
     elif self.lifecycle == 'non_updateable_object':
         return self.non_updateable_object_exists()
     else:
         msg = 'Unrecognized lifecycle value "%s"' % self.lifecycle
         self.module.fail_json(msg=msg, **self.module_result)
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
def policy_identical(client, module, cspolicy_proxy):
    log('Checking if defined policy is identical to configured')
    try:
        policy_list = cspolicy.get(client, module.params['policyname'])
    except Exception:
        return False

    diff_dict = cspolicy_proxy.diff_object(policy_list)
    if 'ip' in diff_dict:
        del diff_dict['ip']
    if len(diff_dict) == 0:
        return True
    else:
        return False
Exemplo n.º 19
0
    def bindings_list_update(self):
        log('ModuleExecutor.bindings_list_update()')

        for key in self.to_delete_keys:
            self._binding_list_item_delete(self.existing_bindings_dict[key])

        for key in self.to_update_keys:
            self._binding_list_item_delete(self.existing_bindings_dict[key])

        for key in self.to_update_keys:
            self._binding_list_item_create(self.configured_bindings_dict[key])

        for key in self.to_create_keys:
            self._binding_list_item_create(self.configured_bindings_dict[key])
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
Exemplo n.º 21
0
    def update_or_create_resource(self):
        log('ModuleExecutor.update_or_create_resource()')

        # Create or update main object
        if not self.resource_exists():
            self.module_result['changed'] = True
            if not self.module.check_mode:
                self.resource_create()
        else:
            if not self.resource_identical():
                self.module_result['changed'] = True
                if not self.module.check_mode:
                    self.resource_update()
            else:
                log('Existing resource has identical values to configured.')
    def update(self):
        log('ModuleExecutor.update()')
        # Check if main object exists
        config = NitroResourceConfig(
            module=self.module,
            resource=self.main_nitro_class,
            attribute_values_dict=self.module.params,
            attributes_list=self.attribute_config[
                self.main_nitro_class]['attributes_list'],
            transforms=self.attribute_config[self.main_nitro_class]
            ['transforms'],
        )

        self.module_result['changed'] = True
        if not self.module.check_mode:
            config.update()
Exemplo n.º 23
0
    def binding_matches_id_attributes(self, binding):
        log('ModuleExecutor.binding_matches_id_attributes()')
        retval = True
        id_keys = []
        id_keys.append(self.module.params['workflow']['primary_id_attribute'])
        id_keys.extend(self.module.params['workflow']['delete_id_attributes'])

        for attribute in self.module.params['resource'].keys():
            if attribute in id_keys:
                configured_value = self.module.params['resource'][attribute]
                retrieved_value = binding.get(attribute)
                if configured_value != retrieved_value:
                    log('Non matching id attribute %s' % attribute)
                    retval = False

        return retval
    def main(self):
        try:

            if self.module.params['state'] == 'present':
                self.update()
            elif self.module.params['state'] == 'absent':
                log('Nothing to do for state absent')

            self.module.exit_json(**self.module_result)

        except NitroException as e:
            msg = "Nitro exception: errorcode=%s, message=%s, severity=%s" % (
                str(e.errorcode), e.message, e.severity)
            self.module.fail_json(msg=msg, **self.module_result)
        except Exception as e:
            msg = 'Exception %s: %s' % (type(e), str(e))
            self.module.fail_json(msg=msg, **self.module_result)
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 main(self):
        try:

            if self.module.params['state'] == 'present':
                self.sync_bindings()
            elif self.module.params['state'] == 'absent':
                log('state "absent" is a noop for this module')

            self.module.exit_json(**self.module_result)

        except NitroException as e:
            msg = "nitro exception errorcode=%s, message=%s, severity=%s" % (
                str(e.errorcode), e.message, e.severity)
            self.module.fail_json(msg=msg, **self.module_result)
        except Exception as e:
            msg = 'Exception %s: %s' % (type(e), str(e))
            self.module.fail_json(msg=msg, **self.module_result)
def server_identical(client, module, server_proxy):
    log('Checking if configured server is identical')
    try:
        server.get(client, module.params['name'])
    except nitro_exception:
        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
Exemplo n.º 28
0
    def non_updateable_object_delete(self):
        log('ModuleExecutor.non_updateable_object_delete()')

        args = {}
        for key in self.module.params['workflow']['delete_id_attributes']:
            if key in self.configured_object:
                args[key] = self.configured_object[key]

        result = self.fetcher.delete(resource=self.endpoint,
                                     id=self.id,
                                     args=args)
        log('delete result %s' % result)

        if result['nitro_errorcode'] != 0:
            raise NitroException(
                errorcode=result['nitro_errorcode'],
                message=result.get('nitro_message'),
                severity=result.get('nitro_severity'),
            )
def lbmonitor_identical(lbmonitor_inst, lbmonitor_proxy):
    log('Checking if monitor is identical')

    diff_dict = lbmonitor_proxy.diff_object(lbmonitor_inst)

    # 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
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()