Example #1
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 delete(self):
        log('ModuleExecutor.delete()')

        if self.signatures_exists():
            self.module_result['changed'] = True
            if not self.module.check_mode:
                self.delete_signatures()
Example #3
0
    def delete(self):
        log('ModuleExecutor.delete()')

        if self.binding_exists():
            self.module_result['changed'] = True
            if not self.module.check_mode:
                self.delete_binding()
Example #4
0
    def binding_delete(self):
        log('ModuleExecutor.binding_delete()')

        args = {}
        for key in self.module.params['workflow']['delete_id_attributes']:
            if key in self.configured_object:
                # Bool args values need to be lower case otherwise NITRO errors
                if isinstance(self.configured_object[key], bool):
                    if self.configured_object[key]:
                        args_value = 'true'
                    else:
                        args_value = 'false'
                else:
                    args_value = self.configured_object[key]
                args[key] = args_value

        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 delete(self):
        log('ModuleExecutor.delete()')

        if self.nspartition_exists():
            self.module_result['changed'] = True
            if not self.module.check_mode:
                self.delete_nspartition()
Example #6
0
    def systemfile_identical(self):
        log('ModuleExecutor.systemfile_identical()')

        diff_list = []

        # Only the filecontents is considered for equality
        # systemfile_exists has already tested filelocation and filename for equality to be true
        bytes_received = codecs.encode(self.retrieved_systemfile['filecontent'])
        retrieved_filecontent = codecs.decode(base64.b64decode(bytes_received))
        configured_filecontent = self.configured_systemfile['filecontent']

        if retrieved_filecontent != configured_filecontent:
            str_tuple = (
                'filecontent',
                type(configured_filecontent),
                configured_filecontent,
                type(retrieved_filecontent),
                retrieved_filecontent,
            )
            diff_list.append('Attribute "%s" differs. Playbook parameter: (%s) %s. Retrieved NITRO object: (%s) %s' % str_tuple)
            log('Attribute "%s" differs. Playbook parameter: (%s) %s. Retrieved NITRO object: (%s) %s' % str_tuple)
            self.module_result['diff_list'] = diff_list

        if diff_list != []:
            return False
        else:
            return True
Example #7
0
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
Example #8
0
    def ssl_certkey_identical(self):
        log('ModuleExecutor.ssl_certkey_identical()')
        result = self.fetcher.get('sslcertkey', self.configured_ssl_certkey['certkey'])
        self.retrieved_ssl_certkey = result['data']['sslcertkey'][0]

        # Keep track of what keys are different for update and change operations
        self.differing_keys = []

        diff_list = []
        for attribute in self._get_configured_for_identical_comparison():
            retrieved_value = self.retrieved_ssl_certkey.get(attribute)
            configured_value = self.configured_ssl_certkey.get(attribute)

            if retrieved_value != configured_value:
                str_tuple = (
                    attribute,
                    type(configured_value),
                    configured_value,
                    type(retrieved_value),
                    retrieved_value,
                )
                self.differing_keys.append(attribute)
                diff_list.append('Attribute "%s" differs. Playbook parameter: (%s) %s. Retrieved NITRO object: (%s) %s' % str_tuple)
                log('Attribute "%s" differs. Playbook parameter: (%s) %s. Retrieved NITRO object: (%s) %s' % str_tuple)

            self.module_result['diff_list'] = diff_list

        if diff_list != []:
            return False
        else:
            return True
Example #9
0
    def delete_monitor_binding(self, configured_dict):
        log('ModuleExecutor.delete_monitor_binding()')

        monitor_binding = copy.deepcopy(configured_dict)

        args = {}
        for attribute in self.attribute_config['monitor_bindings']['delete_id_attributes']:
            value = monitor_binding.get(attribute)
            if value is not None:
                args[attribute] = value

        result = self.fetcher.delete(
            resource='service_lbmonitor_binding',
            id=self.configured_service['name'],
            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'),
            )
Example #10
0
    def delete(self):
        log('ModuleExecutor.delete()')

        if self.ssl_certkey_exists():
            self.module_result['changed'] = True
            if not self.module.check_mode:
                self.delete_ssl_certkey()
Example #11
0
    def delete_ssl_certkey(self):
        log('ModuleExecutor.delete_ssl_certkey()')

        args = {}

        # Add delete flag if defined
        if 'deletefromdevice' in self.configured_ssl_certkey:
            if self.configured_ssl_certkey['deletefromdevice']:
                args['deletefromdevice'] = 'true'
            else:
                args['deletefromdevice'] = 'false'

        result = self.fetcher.delete(
            resource='sslcertkey',
            id=self.configured_ssl_certkey['certkey'],
            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'),
            )
Example #12
0
def policy_exists(client, module):
    log('Checking if policy exists')
    try:
        cspolicy.get(client, module.params['policyname'])
        return True
    except Exception:
        return False
Example #13
0
def get_nitro_api_info(module):
    log('In get_nitro_api_info')

    fetcher = NitroAPIFetcher(module=module)

    endpoint = module.params.get('endpoint')
    args = module.params.get('args', None)
    attrs = module.params.get('attrs', None)
    filter = module.params.get('filter', None)

    nitro_info_key = module.params.get('nitro_info_key', None)
    if nitro_info_key is None:
        nitro_info_key = endpoint

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

    get_result = fetcher.get(resource=endpoint,
                             args=args,
                             attrs=attrs,
                             filter=filter)
    log("get_result: %s" % get_result)
    data = get_result.get('data')

    # data key is always expected from a NITRO request
    if data is None:
        module_result['failed'] = True
        module.fail_json(msg='There is no data key in get result',
                         **module_result)

    nitro_empty_errorcodes = module.params.get('nitro_empty_errorcodes')
    if nitro_empty_errorcodes is None:
        nitro_empty_errorcodes = []

    # Resource does not exist and appropriate errorcode returned
    errorcode = data.get('errorcode', 0)
    if errorcode in nitro_empty_errorcodes:
        module.exit_json(nitro_info=[], **module_result)

    acceptable_errorcodes = [0]
    acceptable_errorcodes.extend(nitro_empty_errorcodes)

    # Errorcode that signifies actual error
    if errorcode not in acceptable_errorcodes:
        msg = 'NITRO error %s. message: %s' % (errorcode, data.get('message'))
        module.fail_json(msg=msg, **module_result)

    nitro_info = data.get(nitro_info_key)

    # Fail if the data do not contain expected key
    if nitro_info is None:
        module_result['failed'] = True
        module.fail_json(msg='There is no nitro_info_key "%s"' %
                         nitro_info_key,
                         **module_result)

    module.exit_json(nitro_info=nitro_info, **module_result)
Example #14
0
    def parameter_object_exists(self):
        log('ModuleExecutor.parameter_object_exists()')

        result = self.fetcher.get(self.endpoint)

        log('get result %s' % result)
        if result['nitro_errorcode'] == 0:
            if self.endpoint not in result['data']:
                msg = 'Parameter object does not exist'
                self.fail_json(msg=msg, **self.module_result)
            else:
                self.retrieved_object = result['data'][self.endpoint]

                if not isinstance(self.retrieved_object, dict):
                    msg = 'Expected dict. Got instead %s' % type(
                        self.retrieved_object)
                    self.fail_json(msg=msg, **self.module_result)
                # Fallthrough

                return True
        else:
            raise NitroException(
                errorcode=result['nitro_errorcode'],
                message=result.get('nitro_message'),
                severity=result.get('nitro_severity'),
            )

        # Parameter object always exists
        # We just adjust some values through the update method
        return True
Example #15
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)
                entry = 'Attribute "%s" differs. Playbook parameter: "%s". Retrieved NITRO object: "%s"' % (
                    attribute, configured_value, retrieved_value)
                self.prepared_list.append(entry)

        return ret_val
    def _do_update_action(self, post_data):
        log('ModuleExecutor._do_update_action()')

        post_data = {'appfwsignatures': post_data}

        result = self.fetcher.post(
            resource='appfwsignatures',
            post_data=post_data,
            action='update',
        )
        if result['http_response_data']['status'] == 200:
            if result.get('nitro_errorcode') is not None:
                if result['nitro_errorcode'] != 0:
                    raise NitroException(
                        errorcode=result['nitro_errorcode'],
                        message=result.get('nitro_message'),
                        severity=result.get('nitro_severity'),
                    )
        elif 400 <= result['http_response_data']['status'] <= 599:
            raise NitroException(
                errorcode=result.get('nitro_errorcode'),
                message=result.get('nitro_message'),
                severity=result.get('nitro_severity'),
            )
        else:
            raise Exception(
                'Did not get nitro errorcode and http status was not 200 or 4xx (%s)'
                % result['http_response_data']['status'])
Example #17
0
    def delete(self):
        log('ModuleExecutor.delete()')

        if self.dnsnsrec_exists():
            self.module_result['changed'] = True
            if not self.module.check_mode:
                self.delete_dnsnsrec()
    def nspartition_identical(self):
        log('ModuleExecutor.nspartition_identical()')

        diff_list = []
        non_updateable_list = []
        for attribute in self.configured_nspartition.keys():
            retrieved_value = self.retrieved_nspartition.get(attribute)
            configured_value = self.configured_nspartition.get(attribute)
            if retrieved_value != configured_value:
                str_tuple = (
                    attribute,
                    type(configured_value),
                    configured_value,
                    type(retrieved_value),
                    retrieved_value,
                )
                diff_list.append('Attribute "%s" differs. Playbook parameter: (%s) %s. Retrieved NITRO object: (%s) %s' % str_tuple)
                log('Attribute "%s" differs. Playbook parameter: (%s) %s. Retrieved NITRO object: (%s) %s' % str_tuple)
                entry = 'Attribute "%s" differs. Playbook parameter: "%s". Retrieved NITRO object: "%s"' % (attribute, configured_value, retrieved_value)
                # Also append changed values to the non updateable list
                if attribute in self.attribute_config['nspartition']['non_updateable_attributes']:
                    non_updateable_list.append(attribute)

        self.module_result['diff_list'] = diff_list
        if non_updateable_list != []:
            msg = 'Cannot change value for the following non updateable attributes %s' % non_updateable_list
            self.module.fail_json(msg=msg, **self.module_result)

        if diff_list != []:
            return False
        else:
            return True
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']
    del argument_spec['bearer_token']
    del argument_spec['is_cloud']
    del argument_spec['instance_id']
    del argument_spec['instance_name']
    del argument_spec['api_path']

    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 update_signatures(self):
        log('ModuleExecutor.update_signatures()')

        self.download_native_singatures_file()

        self.process_native_signatures_file()

        self.upload_and_update_native_signatures_file()
Example #21
0
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
Example #22
0
    def delete(self):
        log('ModuleExecutor.delete()')

        if self.service_exists():
            self.module_result['changed'] = True
            self.prepared_list.append('Delete service')
            if not self.module.check_mode:
                self.delete_service()
 def process_enabled(self, rule):
     log('ModuleExecutor.process_enabled()')
     want_enabled = self._rule_want_enabled(rule)
     if want_enabled:
         rule.attrib['enabled'] = 'ON'
     else:
         if 'enabled' in rule.attrib:
             del rule.attrib['enabled']
    def create_signatures(self):
        log('ModuleExecutor.create_signatures()')

        if self.use_builtin_xslt:
            self.copy_builtin_xslt_to_vartmp()

        self.initial_create_signatures()

        self.update_signatures()
Example #25
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 download_native_singatures_file(self):
        log('ModuleExecutor.download_native_singatures_file()')
        remote_path = os.path.join('/var/download/custom',
                                   self.configured_signatures['name'])
        local_path = self.local_native_signatures
        if os.path.exists(local_path):
            return

        # Fallthrough to download

        self._download_file(remote_path=remote_path, local_path=local_path)
Example #27
0
    def delete_service(self):

        result = self.fetcher.delete(resource='service', id=self.module.params['name'])
        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 update_or_create(self):
        log('ModuleExecutor.update_or_create()')

        # sslcipher only valid attribute is its ciphergroupname
        # It either exists or not. ugdate is not sensible
        if not self.cipher_exists():
            self.module_result['changed'] = True
            if not self.module.check_mode:
                log('cipher does not exist. Will create.')
                self.create_cipher()
        else:
            self.module_result['changed'] = False
Example #29
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 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