Пример #1
0
    def run(self, terms, variables, **kwargs):

        ret = list()

        self.ds = variables.copy()
        self.template = template_loader.get('json_template', self._templar)

        display.debug("File lookup term: %s" % terms[0])

        lookupfile = self.find_file_in_search_path(variables, 'files',
                                                   terms[0])
        display.vvvv("File lookup using %s as file" % lookupfile)
        try:
            if lookupfile:
                with open(to_bytes(lookupfile, errors='surrogate_or_strict'),
                          'rb') as f:
                    json_data = list()
                    json_data.append(json.load(f))
                    ret.append(self.template.run(json_data, self.ds))
            else:
                raise AnsibleParserError()
        except AnsibleParserError:
            raise AnsibleError("could not locate file in lookup: %s" %
                               terms[0])

        return ret
Пример #2
0
    def run(self, tmp=None, task_vars=None):
        if task_vars is None:
            task_vars = dict()

        result = super(ActionModule, self).run(tmp, task_vars)

        try:
            source_dir = self._task.args.get('dir')
            source_file = self._task.args.get('file')
            content = self._task.args['content']
        except KeyError as exc:
            return {
                'failed': True,
                'msg': 'missing required argument: %s' % exc
            }

        if source_dir and source_file:
            return {
                'failed': True,
                'msg': '`dir` and `file` are mutually exclusive arguments'
            }

        if source_dir:
            sources = self.get_files(to_list(source_dir))
        else:
            if source_file:
                sources = to_list(source_file)
            else:
                searchpath = []
                searchpath = task_vars.get('ansible_search_path', [])
                if not searchpath:
                    searchpath.append(self._loader._basedir)

                if 'parser_templates' in os.listdir(searchpath[0]):
                    subdir_searchpath = os.path.join(searchpath[0],
                                                     'parser_templates')

                    # parser in {{ playbook_dir }}/parser_templates/{{ ansible_network_os }}
                    if task_vars['ansible_network_os'] in os.listdir(
                            subdir_searchpath):
                        newsearchpath = os.path.join(
                            subdir_searchpath, task_vars['ansible_network_os'])
                        sources = self.get_parser(path=newsearchpath)

                    # parser in {{ playbook_dir }}/parser_templates
                    else:
                        sources = self.get_parser(path=subdir_searchpath)

                # parser in {{ playbook_dir }}
                else:
                    sources = self.get_parser(path=searchpath[0])

        facts = {}

        self.template = template_loader.get('json_template', self._templar)

        for src in sources:
            src_path = os.path.expanduser(src)
            if not os.path.exists(src_path) and not os.path.isfile(src_path):
                raise AnsibleError("src [%s] is either missing or invalid" %
                                   src_path)

            tasks = self._loader.load_from_file(src)

            self.ds = {'content': content}
            self.ds.update(task_vars)

            for task in tasks:
                name = task.pop('name', None)
                display.vvvv('processing directive: %s' % name)

                register = task.pop('register', None)
                extend = task.pop('extend', None)

                export = task.pop('export', False)
                export_as = task.pop('export_as', 'list')
                export_as = self.template(export_as, self.ds)
                if export_as not in self.VALID_EXPORT_AS:
                    raise AnsibleError('invalid value for export_as, got %s' %
                                       export_as)

                if 'export_facts' in task:
                    task['set_vars'] = task.pop('export_facts')
                    export = True
                elif 'set_vars' not in task:
                    if export and not register:
                        warning(
                            'entry will not be exported due to missing register option'
                        )

                when = task.pop('when', None)
                if when is not None:
                    if not self._check_conditional(when, self.ds):
                        display.vvv(
                            'command_parser: skipping task [%s] due to conditional check'
                            % name)
                        continue

                loop = task.pop('loop', None)
                loop_var = task.pop('loop_control',
                                    {}).get('loop_var') or 'item'

                if loop is not None:
                    loop = self.template(loop, self.ds)
                    if not loop:
                        display.vvv(
                            'command_parser: loop option was defined but no loop data found'
                        )
                    res = list()

                    if loop:
                        # loop is a hash so break out key and value
                        if isinstance(loop, collections.Mapping):
                            for loop_key, loop_value in iteritems(loop):
                                self.ds[loop_var] = {
                                    'key': loop_key,
                                    'value': loop_value
                                }
                                resp = self._process_directive(task)
                                res.append(resp)

                        # loop is either a list or a string
                        else:
                            for loop_item in loop:
                                self.ds[loop_var] = loop_item
                                resp = self._process_directive(task)
                                res.append(resp)

                        if 'set_vars' in task:
                            if register:
                                self.ds[register] = res
                                if export:
                                    if extend:
                                        facts.update(
                                            self.merge_facts(
                                                task_vars, extend, register,
                                                res))
                                    else:
                                        facts[register] = res
                            else:
                                self.ds.update(res)
                                if export:
                                    facts.update(res)
                        elif register:
                            self.ds[register] = res
                            if export:
                                if export_as in ('dict', 'hash', 'object'):
                                    if extend:
                                        facts.update(
                                            self.merge_facts(task_vars,
                                                             extend,
                                                             register,
                                                             res,
                                                             expand=True))
                                    else:
                                        if register not in facts:
                                            facts[register] = {}
                                        for item in res:
                                            facts[register] = self.rec_update(
                                                facts[register], item)
                                else:
                                    if extend:
                                        facts.update(
                                            self.merge_facts(
                                                task_vars, extend, register,
                                                res))
                                    else:
                                        facts[register] = res
                else:
                    res = self._process_directive(task)
                    if 'set_vars' in task:
                        if register:
                            self.ds[register] = res
                            if export:
                                if extend:
                                    facts.update(
                                        self.merge_facts(
                                            task_vars, extend, register, res))
                                else:
                                    facts[register] = res
                        else:
                            self.ds.update(res)
                            if export:
                                facts.update(res)
                    elif res and register:
                        self.ds[register] = res
                        if export:
                            if register:
                                if extend:
                                    facts.update(
                                        self.merge_facts(
                                            task_vars, extend, register, res))
                                else:
                                    facts[register] = res
                            else:
                                for r in to_list(res):
                                    for k, v in iteritems(r):
                                        facts.update({to_text(k): v})

        result.update({'ansible_facts': facts, 'included': sources})

        return result
Пример #3
0
    def run(self, tmp=None, task_vars=None):
        if task_vars is None:
            task_vars = dict()

        result = super(ActionModule, self).run(tmp, task_vars)

        try:
            source_dir = self._task.args.get('dir')
            source_file = self._task.args.get('file')
            content = self._task.args['content']
        except KeyError as exc:
            return {'failed': True, 'msg': 'missing required argument: %s' % exc}

        if not source_dir and not source_file:
            return {'failed': True, 'msg': 'one of `dir` or `file` must be specified'}
        elif source_dir and source_file:
            return {'failed': True, 'msg': '`dir` and `file` are mutually exclusive arguments'}

        if not isinstance(content, string_types):
            return {'failed': True, 'msg': '`content` must be of type str, got %s' % type(content)}

        if source_dir:
            sources = self.get_files(to_list(source_dir))
        else:
            sources = to_list(source_file)

        facts = {}

        self.template = template_loader.get('json_template', self._templar)

        for src in sources:
            src_path = os.path.expanduser(src)
            if not os.path.exists(src_path) and not os.path.isfile(src_path):
                raise AnsibleError("src [%s] is either missing or invalid" % src_path)

            tasks = self._loader.load_from_file(src)

            self.ds = {'content': content}
            self.ds.update(task_vars)

            for task in tasks:
                name = task.pop('name', None)
                display.vvvv('processing directive: %s' % name)

                register = task.pop('register', None)

                export = task.pop('export', False)
                export_as = task.pop('export_as', 'list')
                if export_as not in self.VALID_EXPORT_AS:
                    raise AnsibleError('invalid value for export_as, got %s' % export_as)

                if 'export_facts' in task:
                    task['set_vars'] = task.pop('export_facts')
                    export = True
                elif 'set_vars' not in task:
                    if export and not register:
                        warning('entry will not be exported due to missing register option')

                when = task.pop('when', None)
                if when is not None:
                    if not self._check_conditional(when, self.ds):
                        display.vvv('command_parser: skipping task [%s] due to conditional check' % name)
                        continue

                loop = task.pop('loop', None)
                loop_var = task.pop('loop_control', {}).get('loop_var') or 'item'

                if loop is not None:
                    loop = self.template(loop, self.ds)
                    if not loop:
                        display.vvv('command_parser: loop option was defined but no loop data found')
                    res = list()

                    if loop:
                        # loop is a hash so break out key and value
                        if isinstance(loop, collections.Mapping):
                            for loop_key, loop_value in iteritems(loop):
                                self.ds[loop_var] = {'key': loop_key, 'value': loop_value}
                                resp = self._process_directive(task)
                                res.append(resp)

                        # loop is either a list or a string
                        else:
                            for loop_item in loop:
                                self.ds[loop_var] = loop_item
                                resp = self._process_directive(task)
                                res.append(resp)

                        if 'set_vars' in task:
                            if register:
                                self.ds[register] = res
                                if export:
                                    facts[register] = res
                            else:
                                self.ds.update(res)
                                if export:
                                    facts.update(res)
                        elif register:
                            self.ds[register] = res
                            if export:
                                if export_as in ('dict', 'hash', 'object'):
                                    if register not in facts:
                                        facts[register] = {}
                                    for item in res:
                                        facts[register] = self.rec_update(facts[register], item)
                                else:
                                    facts[register] = res
                else:
                    res = self._process_directive(task)
                    if 'set_vars' in task:
                        if register:
                            self.ds[register] = res
                            if export:
                                facts[register] = res
                        else:
                            self.ds.update(res)
                            if export:
                                facts.update(res)
                    elif res and register:
                        self.ds[register] = res
                        if export:
                            if register:
                                facts[register] = res
                            else:
                                for r in to_list(res):
                                    for k, v in iteritems(r):
                                        facts.update({to_text(k): v})

        result.update({
            'ansible_facts': facts,
            'included': sources
        })

        return result