Python ansible.module_utils._text.to_native() Examples

The following are 30 code examples of ansible.module_utils._text.to_native(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ansible.module_utils._text , or try the search function .
Example #1
Source File: openshift_facts.py    From origin-ci-tool with Apache License 2.0 6 votes vote down vote up
def query_metadata(metadata_url, headers=None, expect_json=False):
    """ Return metadata from the provided metadata_url

        Args:
            metadata_url (str): metadata url
            headers (dict): headers to set for metadata request
            expect_json (bool): does the metadata_url return json
        Returns:
            dict or list: metadata request result
    """
    result, info = fetch_url(module, metadata_url, headers=headers)
    if info['status'] != 200:
        raise OpenShiftFactsMetadataUnavailableError("Metadata unavailable")
    if expect_json:
        return module.from_json(to_native(result.read()))
    else:
        return [to_native(line.strip()) for line in result.readlines()] 
Example #2
Source File: podman_container.py    From baremetal-deploy with Apache License 2.0 6 votes vote down vote up
def _perform_action(self, action):
        """Perform action with container

        Arguments:
            action {str} -- action to perform - start, create, stop, run, delete
        """
        b_command = construct_command_from_params(action, self.module.params)
        self.module.log(
            "PODMAN-DEBUG: %s" % " ".join([to_native(i) for i in b_command])
        )
        rc, out, err = run_podman_command(
            module=self.module, args=[b"container"] + b_command, ignore_errors=True
        )
        if rc != 0:
            self.module.fail_json(
                msg="Can't %s container %s" % (action, self.name),
                stdout=out,
                stderr=err,
            ) 
Example #3
Source File: nsxt_vcenter_moids.py    From ansible-module-chaperone with Apache License 2.0 6 votes vote down vote up
def find_object_by_name(module,content, object_name):
    try:
    	if(object_name == module.params['datacenter']):
    	    vmware_objects = get_all_objs(module,content,[vim.Datacenter])
    	elif (object_name == module.params['cluster']):
    	    vmware_objects = get_all_objs(module,content,[vim.ComputeResource])
    	elif (object_name == module.params['datastore']):
            vmware_objects = get_all_objs(module,content,[vim.Datastore])
    	elif (object_name == module.params['portgroup1'] or module.params['portgroup2'] or module.params['portgroup3'] ):
            vmware_objects = get_all_objs(module,content,[vim.dvs.DistributedVirtualPortgroup, vim.Network])
 
    	for object in vmware_objects:
            if object.name == object_name:
            	logger.info('object: %s',object.name)
            	return object
    	return None
    except Exception as err:
       module.fail_json(changed=False, msg= "Error Occured while Finding the Object by name. Error is %s" %(to_native(err))) 
Example #4
Source File: grafana_dashboard.py    From community.grafana with GNU General Public License v3.0 6 votes vote down vote up
def grafana_list_dashboards(self):
        # define http headers
        headers = self.grafana_headers()

        dashboard_list = []
        try:
            if self.search:
                r = open_url('%s/api/search?query=%s' % (self.grafana_url, self.search), headers=headers, method='GET')
            else:
                r = open_url('%s/api/search/' % self.grafana_url, headers=headers, method='GET')
        except HTTPError as e:
            raise GrafanaAPIException('Unable to search dashboards : %s' % to_native(e))
        if r.getcode() == 200:
            try:
                dashboard_list = json.loads(r.read())
            except Exception as e:
                raise GrafanaAPIException('Unable to parse json list %s' % to_native(e))
        else:
            raise GrafanaAPIException('Unable to list grafana dashboards : %s' % str(r.getcode()))

        return dashboard_list 
Example #5
Source File: oneview.py    From oneview-ansible with Apache License 2.0 6 votes vote down vote up
def transform_list_to_dict(list_):
    """
    Transforms a list into a dictionary, putting values as keys.

    :arg list list_: List of values
    :return: dict: dictionary built
    """

    ret = {}

    if not list_:
        return ret

    for value in list_:
        if isinstance(value, collections.Mapping):
            ret.update(value)
        else:
            ret[to_native(value)] = True

    return ret


# Makes a deep merge of 2 dictionaries and returns the merged dictionary 
Example #6
Source File: foreman_helper.py    From foreman-ansible-modules with GNU General Public License v3.0 6 votes vote down vote up
def parse_template(template_content, module):
    if not HAS_PYYAML:
        module.fail_json(msg=missing_required_lib("PyYAML"), exception=PYYAML_IMP_ERR)

    try:
        template_dict = {}
        data = re.search(
            r'<%#([^%]*([^%]*%*[^>%])*%*)%>', template_content)
        if data:
            datalist = data.group(1)
            if datalist[-1] == '-':
                datalist = datalist[:-1]
            template_dict = yaml.safe_load(datalist)
        # No metadata, import template anyway
        template_dict['template'] = template_content
    except Exception as e:
        module.fail_json(msg='Error while parsing template: ' + to_native(e))
    return template_dict 
Example #7
Source File: foreman_helper.py    From foreman-ansible-modules with GNU General Public License v3.0 6 votes vote down vote up
def resource_action(self, resource, action, params, options=None, data=None, files=None,
                        ignore_check_mode=False, record_change=True, ignore_task_errors=False):
        resource_payload = self._resource_prepare_params(resource, action, params)
        if options is None:
            options = {}
        try:
            result = None
            if ignore_check_mode or not self.check_mode:
                result = self._resource_call(resource, action, resource_payload, options=options, data=data, files=files)
                is_foreman_task = isinstance(result, dict) and 'action' in result and 'state' in result and 'started_at' in result
                if is_foreman_task:
                    result = self.wait_for_task(result, ignore_errors=ignore_task_errors)
        except Exception as e:
            msg = 'Error while performing {0} on {1}: {2}'.format(
                action, resource, to_native(e))
            self.fail_from_exception(e, msg)
        if record_change and not ignore_check_mode:
            # If we were supposed to ignore check_mode we can assume this action was not a changing one.
            self.set_changed()
        return result 
Example #8
Source File: fortios_api.py    From ansible_fortios_api with GNU General Public License v3.0 6 votes vote down vote up
def _connect(self):
        if self.module.params['file_mode']:
            self.forti_device = FortiOS('')
        else:
            host = self.module.params['host']
            username = self.module.params['username']
            password = self.module.params['password']
            timeout = self.module.params['timeout']
            vdom = self.module.params['vdom']

            self.forti_device = FortiOS(host, username=username, password=password, timeout=timeout, vdom=vdom)

            try:
                self.forti_device.open()
            except Exception as e:
                self.module.fail_json(msg='Error connecting device. %s' % to_native(e),
                                      exception=traceback.format_exc()) 
Example #9
Source File: openshift_facts.py    From origin-ci-tool with Apache License 2.0 6 votes vote down vote up
def query_metadata(metadata_url, headers=None, expect_json=False):
    """ Return metadata from the provided metadata_url

        Args:
            metadata_url (str): metadata url
            headers (dict): headers to set for metadata request
            expect_json (bool): does the metadata_url return json
        Returns:
            dict or list: metadata request result
    """
    result, info = fetch_url(module, metadata_url, headers=headers)
    if info['status'] != 200:
        raise OpenShiftFactsMetadataUnavailableError("Metadata unavailable")
    if expect_json:
        return module.from_json(to_native(result.read()))
    else:
        return [to_native(line.strip()) for line in result.readlines()] 
Example #10
Source File: alicloud_ecs.py    From alibaba.alicloud with Apache License 2.0 6 votes vote down vote up
def _get_instances_by_region(self, regions, filters):
        '''
           :param regions: a list of regions in which to describe instances
           :param filters: a list of ECS filter dictionaries
           :return A list of instance dictionaries
        '''
        all_instances = []
        if not regions:
            try:
                regions = list(map(lambda x: x.id, self.connect_to_ecs(footmark.ecs, "cn-beijing").describe_regions()))
            except Exception as e:
                raise AnsibleError('Unable to get regions list from available methods, you must specify the "regions" option to continue.')

        for region in regions:
            try:
                conn = connect_to_acs(footmark.ecs, region, **self.credentials)
                insts = conn.describe_instances(**filters)
                all_instances.extend(map(lambda x: x.read(), insts))
            except Exception as e:
                raise AnsibleError("Failed to describe instances: %s" % to_native(e))
        return sorted(all_instances, key=lambda x: x['instance_id']) 
Example #11
Source File: openshift_facts.py    From origin-ci-tool with Apache License 2.0 6 votes vote down vote up
def query_metadata(metadata_url, headers=None, expect_json=False):
    """ Return metadata from the provided metadata_url

        Args:
            metadata_url (str): metadata url
            headers (dict): headers to set for metadata request
            expect_json (bool): does the metadata_url return json
        Returns:
            dict or list: metadata request result
    """
    result, info = fetch_url(module, metadata_url, headers=headers)
    if info['status'] != 200:
        raise OpenShiftFactsMetadataUnavailableError("Metadata unavailable")
    if expect_json:
        return module.from_json(to_native(result.read()))
    else:
        return [to_native(line.strip()) for line in result.readlines()] 
Example #12
Source File: openshift_facts.py    From origin-ci-tool with Apache License 2.0 6 votes vote down vote up
def query_metadata(metadata_url, headers=None, expect_json=False):
    """ Return metadata from the provided metadata_url

        Args:
            metadata_url (str): metadata url
            headers (dict): headers to set for metadata request
            expect_json (bool): does the metadata_url return json
        Returns:
            dict or list: metadata request result
    """
    result, info = fetch_url(module, metadata_url, headers=headers)
    if info['status'] != 200:
        raise OpenShiftFactsMetadataUnavailableError("Metadata unavailable")
    if expect_json:
        return module.from_json(to_native(result.read()))
    else:
        return [to_native(line.strip()) for line in result.readlines()] 
Example #13
Source File: fortios_api.py    From ansible_fortios_api with GNU General Public License v3.0 5 votes vote down vote up
def apply_changes(self):
        change_string = self.forti_device.compare_config()
        if change_string:
            self.result['change_string'] = change_string
            self.result['changed'] = True

        # Commit if not check mode
        if change_string and not self.module.check_mode:
            if self.module.params['file_mode']:
                try:
                    f = open(self.module.params['config_file'], 'w')
                    f.write(self.candidate_config.to_text())
                    f.close()
                except IOError as e:
                    self.module.fail_json(msg='Error writing configuration file. %s' %
                                          to_native(e), exception=traceback.format_exc())
            else:
                try:
                    self.forti_device.commit()
                except FailedCommit as e:
                    # Something's wrong (rollback is automatic)
                    self.forti_device.close()
                    error_list = self.get_error_infos(e)
                    self.module.fail_json(msg_error_list=error_list, msg="Unable to commit change, check your args, the error was %s" % e.message)

                self.forti_device.close()
        self.module.exit_json(**self.result) 
Example #14
Source File: jenkins_job.py    From ansible-role-jenkins with Apache License 2.0 5 votes vote down vote up
def get_jenkins_connection(self):
        try:
            if (self.user and self.password):
                return jenkins.Jenkins(self.jenkins_url, self.user, self.password)
            elif (self.user and self.token):
                return jenkins.Jenkins(self.jenkins_url, self.user, self.token)
            elif (self.user and not (self.password or self.token)):
                return jenkins.Jenkins(self.jenkins_url, self.user)
            else:
                return jenkins.Jenkins(self.jenkins_url)
        except Exception as e:
            self.module.fail_json(msg='Unable to connect to Jenkins server, %s' % to_native(e), exception=traceback.format_exc()) 
Example #15
Source File: jenkins_job.py    From ansible-role-jenkins with Apache License 2.0 5 votes vote down vote up
def get_job_status(self):
        try:
            response = self.server.get_job_info(self.name)
            if "color" not in response:
                return self.EXCL_STATE
            else:
                return to_native(response['color'])

        except Exception as e:
            self.module.fail_json(msg='Unable to fetch job information, %s' % to_native(e), exception=traceback.format_exc()) 
Example #16
Source File: jenkins_job.py    From ansible-role-jenkins with Apache License 2.0 5 votes vote down vote up
def job_exists(self):
        try:
            return bool(self.server.job_exists(self.name))
        except Exception as e:
            self.module.fail_json(msg='Unable to validate if job exists, %s for %s' % (to_native(e), self.jenkins_url),
                                  exception=traceback.format_exc()) 
Example #17
Source File: jenkins_job.py    From ansible-role-jenkins with Apache License 2.0 5 votes vote down vote up
def create_job(self):
        if self.config is None:
            self.module.fail_json(msg='missing required param: config')

        self.result['changed'] = True
        try:
            config_file = self.get_config()
            self.result['diff']['after'] = config_file
            if not self.module.check_mode:
                self.server.create_job(self.name, config_file)
        except Exception as e:
            self.module.fail_json(msg='Unable to create job, %s for %s' % (to_native(e), self.jenkins_url),
                                  exception=traceback.format_exc()) 
Example #18
Source File: urls.py    From ansible-role-jenkins with Apache License 2.0 5 votes vote down vote up
def fetch_file(module, url, data=None, headers=None, method=None,
               use_proxy=True, force=False, last_mod_time=None, timeout=10):
    '''Download and save a file via HTTP(S) or FTP (needs the module as parameter).
    This is basically a wrapper around fetch_url().
    :arg module: The AnsibleModule (used to get username, password etc. (s.b.).
    :arg url:             The url to use.
    :kwarg data:          The data to be sent (in case of POST/PUT).
    :kwarg headers:       A dict with the request headers.
    :kwarg method:        "POST", "PUT", etc.
    :kwarg boolean use_proxy:     Default: True
    :kwarg boolean force: If True: Do not get a cached copy (Default: False)
    :kwarg last_mod_time: Default: None
    :kwarg int timeout:   Default: 10
    :returns: A string, the path to the downloaded file.
    '''
    # download file
    bufsize = 65536
    file_name, file_ext = os.path.splitext(str(url.rsplit('/', 1)[1]))
    fetch_temp_file = tempfile.NamedTemporaryFile(dir=module.tmpdir, prefix=file_name, suffix=file_ext, delete=False)
    module.add_cleanup_file(fetch_temp_file.name)
    try:
        rsp, info = fetch_url(module, url, data, headers, method, use_proxy, force, last_mod_time, timeout)
        if not rsp:
            module.fail_json(msg="Failure downloading %s, %s" % (url, info['msg']))
        data = rsp.read(bufsize)
        while data:
            fetch_temp_file.write(data)
            data = rsp.read(bufsize)
        fetch_temp_file.close()
    except Exception as e:
        module.fail_json(msg="Failure downloading %s, %s" % (url, to_native(e)))
    return fetch_temp_file.name 
Example #19
Source File: jenkins_job.py    From ansible-role-jenkins with Apache License 2.0 5 votes vote down vote up
def absent_job(self):
        if self.job_exists():
            self.result['changed'] = True
            self.result['diff']['before'] = self.get_current_config()
            if not self.module.check_mode:
                try:
                    self.server.delete_job(self.name)
                except Exception as e:
                    self.module.fail_json(msg='Unable to delete job, %s for %s' % (to_native(e), self.jenkins_url),
                                          exception=traceback.format_exc()) 
Example #20
Source File: nsxt_selfsigned.py    From ansible-module-chaperone with Apache License 2.0 5 votes vote down vote up
def import_certificate(module,manager_url, NSX_USER, NSX_PASSWORD, validate_certs,request_data,cert_id):
    request_obj = json.dumps(request_data)
    if cert_id is None:
            try:
                if cert_id:
                    print("Certificate Already Exists with that name %s" %(cert_id))                    
                (rc, resp) = request(manager_url+ '/trust-management/certificates?action=import', data=request_obj, headers=headers, method='POST',
                                url_username=NSX_USER, url_password=NSX_PASSWORD, validate_certs=validate_certs, ignore_errors=True)
                logger.info("Successfully Imported the Certificate")
            except Exception as err:
                module.fail_json(changed=False,msg="Failed to Import the Certificate.Error:%s." % (to_native(err))) 
Example #21
Source File: citrix_adc.py    From citrix-adc-ansible-modules with GNU General Public License v3.0 5 votes vote down vote up
def monkey_patch_nitro_api():

    from nssrc.com.citrix.netscaler.nitro.resource.base.Json import Json

    def new_resource_to_string_convert(self, resrc):
        # Line below is the actual patch
        dict_valid_values = dict((k.replace('_', '', 1), v) for k, v in resrc.__dict__.items() if v)
        return json.dumps(dict_valid_values)
    Json.resource_to_string_convert = new_resource_to_string_convert

    from nssrc.com.citrix.netscaler.nitro.util.nitro_util import nitro_util

    @classmethod
    def object_to_string_new(cls, obj):
        output = []
        flds = obj.__dict__
        for k, v in ((k.replace('_', '', 1), v) for k, v in flds.items() if v):
            if isinstance(v, bool):
                output.append('"%s":%s' % (k, v))
            elif isinstance(v, (binary_type, text_type)):
                v = to_native(v, errors='surrogate_or_strict')
                output.append('"%s":"%s"' % (k, v))
            elif isinstance(v, int):
                output.append('"%s":"%s"' % (k, v))
        return ','.join(output)

    @classmethod
    def object_to_string_withoutquotes_new(cls, obj):
        output = []
        flds = obj.__dict__
        for k, v in ((k.replace('_', '', 1), v) for k, v in flds.items() if v):
            if isinstance(v, (int, bool)):
                output.append('%s:%s' % (k, v))
            elif isinstance(v, (binary_type, text_type)):
                v = to_native(v, errors='surrogate_or_strict')
                output.append('%s:%s' % (k, cls.encode(v)))
        return ','.join(output)

    nitro_util.object_to_string = object_to_string_new
    nitro_util.object_to_string_withoutquotes = object_to_string_withoutquotes_new 
Example #22
Source File: netscaler.py    From citrix-adc-ansible-modules with GNU General Public License v3.0 5 votes vote down vote up
def monkey_patch_nitro_api():

    from nssrc.com.citrix.netscaler.nitro.resource.base.Json import Json

    def new_resource_to_string_convert(self, resrc):
        # Line below is the actual patch
        dict_valid_values = dict((k.replace('_', '', 1), v) for k, v in resrc.__dict__.items() if v)
        return json.dumps(dict_valid_values)
    Json.resource_to_string_convert = new_resource_to_string_convert

    from nssrc.com.citrix.netscaler.nitro.util.nitro_util import nitro_util

    @classmethod
    def object_to_string_new(cls, obj):
        output = []
        flds = obj.__dict__
        for k, v in ((k.replace('_', '', 1), v) for k, v in flds.items() if v):
            if isinstance(v, bool):
                output.append('"%s":%s' % (k, v))
            elif isinstance(v, (binary_type, text_type)):
                v = to_native(v, errors='surrogate_or_strict')
                output.append('"%s":"%s"' % (k, v))
            elif isinstance(v, int):
                output.append('"%s":"%s"' % (k, v))
        return ','.join(output)

    @classmethod
    def object_to_string_withoutquotes_new(cls, obj):
        output = []
        flds = obj.__dict__
        for k, v in ((k.replace('_', '', 1), v) for k, v in flds.items() if v):
            if isinstance(v, (int, bool)):
                output.append('%s:%s' % (k, v))
            elif isinstance(v, (binary_type, text_type)):
                v = to_native(v, errors='surrogate_or_strict')
                output.append('%s:%s' % (k, cls.encode(v)))
        return ','.join(output)

    nitro_util.object_to_string = object_to_string_new
    nitro_util.object_to_string_withoutquotes = object_to_string_withoutquotes_new 
Example #23
Source File: gcp_iam_service_account_key.py    From google.cloud with GNU General Public License v3.0 5 votes vote down vote up
def create(module):
    auth = GcpSession(module, 'iam')
    json_content = return_if_object(module, auth.post(self_link(module), resource_to_request(module)))
    with open(module.params['path'], 'w') as f:
        private_key_contents = to_native(base64.b64decode(json_content['privateKeyData']))
        f.write(private_key_contents) 
Example #24
Source File: oneview.py    From oneview-ansible with Apache License 2.0 5 votes vote down vote up
def run(self):
        """
        Common implementation of the OneView run modules.

        It calls the inheritor 'execute_module' function and sends the return to the Ansible.

        It handles any OneViewModuleException in order to signal a failure to Ansible, with a descriptive error message.

        """
        try:
            if self.validate_etag_support:
                if not self.module.params.get('validate_etag'):
                    self.oneview_client.connection.disable_etag_validation()

            result = self.execute_module()

            if not result:
                result = {}

            if "changed" not in result:
                result['changed'] = False

            self.module.exit_json(**result)

        except OneViewModuleException as exception:
            error_msg = '; '.join(to_native(e) for e in exception.args)
            self.module.fail_json(msg=error_msg, exception=traceback.format_exc()) 
Example #25
Source File: oneview.py    From oneview-ansible with Apache License 2.0 5 votes vote down vote up
def run(self):
        """
        Common implementation of the OneView run modules.

        It calls the inheritor 'execute_module' function and sends the return to the Ansible.

        It handles any OneViewModuleException in order to signal a failure to Ansible, with a descriptive error message.

        """
        try:
            if self.validate_etag_support:
                if not self.module.params.get('validate_etag'):
                    self.oneview_client.connection.disable_etag_validation()

            result = self.execute_module()

            if not result:
                result = {}

            if "changed" not in result:
                result['changed'] = False

            self.module.exit_json(**result)

        except OneViewModuleException as exception:
            error_msg = '; '.join(to_native(e) for e in exception.args)
            self.module.fail_json(msg=error_msg, exception=traceback.format_exc()) 
Example #26
Source File: fortios_api.py    From ansible_fortios_api with GNU General Public License v3.0 5 votes vote down vote up
def load_config(self, path):
        self.path = path
        self._connect()
        # load in file_mode
        if self.module.params['file_mode']:
            try:
                f = open(self.module.params['config_file'], 'r')
                running = f.read()
                f.close()
            except IOError as e:
                self.module.fail_json(msg='Error reading configuration file. %s' % to_native(e),
                                      exception=traceback.format_exc())
            self.forti_device.load_config(config_text=running, path=path)

        else:
            # get  config
            try:
                self.forti_device.load_config(path=path)
            except Exception as e:
                self.forti_device.close()
                self.module.fail_json(msg='Error reading running config. %s' % to_native(e),
                                      exception=traceback.format_exc())

        # set configs in object
        self.result['running_config'] = self.forti_device.running_config.to_text()
        self.candidate_config = self.forti_device.candidate_config

        # backup if needed
        if self.module.params['backup']:
            backup(self.module, self.forti_device.running_config.to_text()) 
Example #27
Source File: redhat_manifest.py    From foreman-ansible-modules with GNU General Public License v3.0 5 votes vote down vote up
def export_manifest(module, manifest):
    path = "/subscription/consumers/%s/export" % (manifest['uuid'])
    try:
        resp, info = fetch_portal(module, path, 'GET', accept_header='application/zip')
        if not module.check_mode:
            with open(module.params['path'], 'wb') as f:
                while True:
                    data = resp.read(65536)  # 64K
                    if not data:
                        break
                    f.write(data)
    except Exception as e:
        module.fail_json(msg="Failure downloading manifest, {0}".format(to_native(e))) 
Example #28
Source File: podman_container.py    From tripleo-ansible with Apache License 2.0 5 votes vote down vote up
def _perform_action(self, action):
        """Perform action with container.

        Arguments:
            action {str} -- action to perform - start, create, stop, run,
                            delete
        """

        def clean_stderr(err):
            # Inspect STDERR for logs to avoid modules failures in case of
            # increased log level verbosity
            return "\n".join(
                [line for line in err.splitlines() if 'level=' not in line]).strip()

        b_command = PodmanModuleParams(action,
                                       self.module.params,
                                       self.version,
                                       self.module,
                                       ).construct_command_from_params()
        full_cmd = " ".join([self.module.params['executable']]
                            + [to_native(i) for i in b_command])
        self.actions.append(full_cmd)
        if self.module.check_mode:
            self.module.log("PODMAN-CONTAINER-DEBUG (check_mode): %s" % full_cmd)
        else:
            rc, out, err = self.module.run_command(
                [self.module.params['executable'], b'container'] + b_command,
                expand_user_and_vars=False)
            self.module.log("PODMAN-CONTAINER-DEBUG: %s" % full_cmd)
            if self.module.params['debug']:
                self.module.log("PODMAN-CONTAINER-DEBUG STDOUT: %s" % out)
                self.module.log("PODMAN-CONTAINER-DEBUG STDERR: %s" % err)
                self.module.log("PODMAN-CONTAINER-DEBUG RC: %s" % rc)
            self.stdout = out
            self.stderr = err
            if rc != 0 or clean_stderr(err) != '':
                self.module.fail_json(
                    msg="Failed %s container %s" % (action, self.name),
                    stdout=out, stderr=err) 
Example #29
Source File: foreman_helper.py    From foreman-ansible-modules with GNU General Public License v3.0 5 votes vote down vote up
def _exception2fail_json(msg='Generic failure: {0}'):
    def decor(f):
        @wraps(f)
        def inner(self, *args, **kwargs):
            try:
                return f(self, *args, **kwargs)
            except Exception as e:
                self.fail_from_exception(e, msg.format(to_native(e)))
        return inner
    return decor 
Example #30
Source File: foreman_helper.py    From foreman-ansible-modules with GNU General Public License v3.0 5 votes vote down vote up
def _update_entity(self, resource, desired_entity, current_entity, params, foreman_spec):
        """Update a given entity with given properties if any diverge

            Parameters:
                resource (string): Plural name of the api resource to manipulate
                desired_entity (dict): Desired properties of the entity
                current_entity (dict): Current properties of the entity
                params (dict): Lookup parameters (i.e. parent_id for nested entities) (optional)
                foreman_spec (dict): Description of the entity structure
            Return value:
                The new current state if the entity
        """
        payload = {}
        desired_entity = _flatten_entity(desired_entity, foreman_spec)
        current_entity = _flatten_entity(current_entity, foreman_spec)
        for key, value in desired_entity.items():
            # String comparison needs extra care in face of unicode
            if foreman_spec[key].get('type', 'str') == 'str':
                if to_native(current_entity.get(key)) != to_native(value):
                    payload[key] = value
            else:
                if current_entity.get(key) != value:
                    payload[key] = value
        if payload:
            payload['id'] = current_entity['id']
            if not self.check_mode:
                if params:
                    payload.update(params)
                return self.resource_action(resource, 'update', payload)
            else:
                # In check_mode we emulate the server updating the entity
                fake_entity = current_entity.copy()
                fake_entity.update(payload)
                self.set_changed()
                return fake_entity
        else:
            # Nothing needs changing
            return current_entity