Пример #1
0
    def test_task_result_no_log(self):
        mock_host = MagicMock()
        mock_task = MagicMock()

        # no_log should remove secrets
        tr = TaskResult(mock_host, mock_task, dict(_ansible_no_log=True, secret='DONTSHOWME'))
        clean = tr.clean_copy()
        self.assertTrue('secret' not in clean._result)
    def test_v2_runner_on_unreachable(self):
        """
        Verify UNREACHABLE results uses the logger.
        """
        result = TaskResult('127.0.0.1', Task(), {})
        result._host = Host('127.0.0.1')

        self.logforward.v2_runner_on_unreachable(result)
        self.assertEqual(1, self.logforward.log.warn.call_count)
    def test_v2_runner_on_skipped(self):
        """
        Verify SKIPPED results uses the logger.
        """
        result = TaskResult('127.0.0.1', Task(), {})
        result._host = Host('127.0.0.1')

        self.logforward.v2_runner_on_skipped(result)
        self.assertEqual(1, self.logforward.log.warn.call_count)
    def test_v2_runner_on_ok(self):
        """
        Verify OK results uses the logger.
        """
        result = TaskResult('127.0.0.1', Task(), {})
        result._host = Host('127.0.0.1')

        self.logforward.v2_runner_on_ok(result)
        self.assertEqual(1, self.logforward.log.info.call_count)
    def test_v2_runner_on_failed(self):
        """
        Verify failed results uses the logger.
        """
        result = TaskResult('127.0.0.1', Task(), {'exception': 'error'})
        result._host = MagicMock()
        result._host.get_name.return_value = '127.0.0.1'

        self.logforward.v2_runner_on_failed(result)
        self.assertEqual(1, self.logforward.log.warn.call_count)
Пример #6
0
    def test_task_result_no_log_preserve(self):
        mock_host = MagicMock()
        mock_task = MagicMock()

        # no_log should not remove presrved keys
        tr = TaskResult(
            mock_host,
            mock_task,
            dict(
                _ansible_no_log=True,
                retries=5,
                attempts=5,
                changed=False,
                foo='bar',
            )
        )
        clean = tr.clean_copy()
        self.assertTrue('retries' in clean._result)
        self.assertTrue('attempts' in clean._result)
        self.assertTrue('changed' in clean._result)
        self.assertTrue('foo' not in clean._result)
Пример #7
0
    def test_task_result_is_failed(self):
        mock_host = MagicMock()
        mock_task = MagicMock()

        # test with no failed in result
        tr = TaskResult(mock_host, mock_task, dict())
        self.assertFalse(tr.is_failed())

        # test failed result with rc values (should not matter)
        tr = TaskResult(mock_host, mock_task, dict(rc=0))
        self.assertFalse(tr.is_failed())
        tr = TaskResult(mock_host, mock_task, dict(rc=1))
        self.assertFalse(tr.is_failed())

        # test with failed in result
        tr = TaskResult(mock_host, mock_task, dict(failed=True))
        self.assertTrue(tr.is_failed())

        # test with failed_when in result
        tr = TaskResult(mock_host, mock_task, dict(failed_when_result=True))
        self.assertTrue(tr.is_failed())
Пример #8
0
    def test_task_result_is_unreachable(self):
        mock_host = MagicMock()
        mock_task = MagicMock()

        # test with no unreachable in result
        tr = TaskResult(mock_host, mock_task, dict())
        self.assertFalse(tr.is_unreachable())

        # test with unreachable in the result
        tr = TaskResult(mock_host, mock_task, dict(unreachable=True))
        self.assertTrue(tr.is_unreachable())

        # test with multiple results but none unreachable
        mock_task.loop = 'foo'
        tr = TaskResult(mock_host, mock_task, dict(results=[dict(foo='bar'), dict(bam='baz'), True]))
        self.assertFalse(tr.is_unreachable())

        # test with multiple results and one unreachable
        mock_task.loop = 'foo'
        tr = TaskResult(mock_host, mock_task, dict(results=[dict(unreachable=False), dict(unreachable=True), dict(some_key=False)]))
        self.assertTrue(tr.is_unreachable())
Пример #9
0
    def test_task_result_is_changed(self):
        mock_host = MagicMock()
        mock_task = MagicMock()

        # test with no changed in result
        tr = TaskResult(mock_host, mock_task, dict())
        self.assertFalse(tr.is_changed())

        # test with changed in the result
        tr = TaskResult(mock_host, mock_task, dict(changed=True))
        self.assertTrue(tr.is_changed())

        # test with multiple results but none changed
        mock_task.loop = 'foo'
        tr = TaskResult(mock_host, mock_task, dict(results=[dict(foo='bar'), dict(bam='baz'), True]))
        self.assertFalse(tr.is_changed())

        # test with multiple results and one changed
        mock_task.loop = 'foo'
        tr = TaskResult(mock_host, mock_task, dict(results=[dict(changed=False), dict(changed=True), dict(some_key=False)]))
        self.assertTrue(tr.is_changed())
Пример #10
0
    def test_task_result_is_skipped(self):
        mock_host = MagicMock()
        mock_task = MagicMock()

        # test with no skipped in result
        tr = TaskResult(mock_host, mock_task, dict())
        self.assertFalse(tr.is_skipped())

        # test with skipped in the result
        tr = TaskResult(mock_host, mock_task, dict(skipped=True))
        self.assertTrue(tr.is_skipped())

        # test with multiple results but none skipped
        mock_task.loop = 'foo'
        tr = TaskResult(mock_host, mock_task, dict(results=[dict(foo='bar'), dict(bam='baz'), True]))
        self.assertFalse(tr.is_skipped())

        # test with multiple results and one skipped
        mock_task.loop = 'foo'
        tr = TaskResult(mock_host, mock_task, dict(results=[dict(skipped=False), dict(skipped=True), dict(some_key=False)]))
        self.assertFalse(tr.is_skipped())

        # test with multiple results and all skipped
        mock_task.loop = 'foo'
        tr = TaskResult(mock_host, mock_task, dict(results=[dict(skipped=True), dict(skipped=True), dict(skipped=True)]))
        self.assertTrue(tr.is_skipped())

        # test with multiple squashed results (list of strings)
        # first with the main result having skipped=False
        mock_task.loop = 'foo'
        tr = TaskResult(mock_host, mock_task, dict(results=["a", "b", "c"], skipped=False))
        self.assertFalse(tr.is_skipped())
        # then with the main result having skipped=True
        tr = TaskResult(mock_host, mock_task, dict(results=["a", "b", "c"], skipped=True))
        self.assertTrue(tr.is_skipped())
Пример #11
0
    def _execute(self, variables=None):
        '''
        The primary workhorse of the executor system, this runs the task
        on the specified host (which may be the delegated_to host) and handles
        the retry/until and block rescue/always execution
        '''

        if variables is None:
            variables = self._job_vars

        templar = Templar(loader=self._loader,
                          shared_loader_obj=self._shared_loader_obj,
                          variables=variables)

        context_validation_error = None
        try:
            # apply the given task's information to the connection info,
            # which may override some fields already set by the play or
            # the options specified on the command line
            self._play_context = self._play_context.set_task_and_variable_override(
                task=self._task, variables=variables, templar=templar)

            # fields set from the play/task may be based on variables, so we have to
            # do the same kind of post validation step on it here before we use it.
            self._play_context.post_validate(templar=templar)

            # now that the play context is finalized, if the remote_addr is not set
            # default to using the host's address field as the remote address
            if not self._play_context.remote_addr:
                self._play_context.remote_addr = self._host.address

            # We also add "magic" variables back into the variables dict to make sure
            # a certain subset of variables exist.
            self._play_context.update_vars(variables)

            # FIXME: update connection/shell plugin options
        except AnsibleError as e:
            # save the error, which we'll raise later if we don't end up
            # skipping this task during the conditional evaluation step
            context_validation_error = e

        # Evaluate the conditional (if any) for this task, which we do before running
        # the final task post-validation. We do this before the post validation due to
        # the fact that the conditional may specify that the task be skipped due to a
        # variable not being present which would otherwise cause validation to fail
        try:
            if not self._task.evaluate_conditional(templar, variables):
                display.debug("when evaluation is False, skipping this task")
                return dict(changed=False,
                            skipped=True,
                            skip_reason='Conditional result was False',
                            _ansible_no_log=self._play_context.no_log)
        except AnsibleError:
            # loop error takes precedence
            if self._loop_eval_error is not None:
                raise self._loop_eval_error  # pylint: disable=raising-bad-type
            # skip conditional exception in the case of includes as the vars needed might not be available except in the included tasks or due to tags
            if self._task.action not in [
                    'include', 'include_tasks', 'include_role'
            ]:
                raise

        # Not skipping, if we had loop error raised earlier we need to raise it now to halt the execution of this task
        if self._loop_eval_error is not None:
            raise self._loop_eval_error  # pylint: disable=raising-bad-type

        # if we ran into an error while setting up the PlayContext, raise it now
        if context_validation_error is not None:
            raise context_validation_error  # pylint: disable=raising-bad-type

        # if this task is a TaskInclude, we just return now with a success code so the
        # main thread can expand the task list for the given host
        if self._task.action in ('include', 'include_tasks'):
            include_variables = self._task.args.copy()
            include_file = include_variables.pop('_raw_params', None)
            if not include_file:
                return dict(failed=True,
                            msg="No include file was specified to the include")

            include_file = templar.template(include_file)
            return dict(include=include_file,
                        include_variables=include_variables)

        # if this task is a IncludeRole, we just return now with a success code so the main thread can expand the task list for the given host
        elif self._task.action == 'include_role':
            include_variables = self._task.args.copy()
            return dict(include_role=self._task,
                        include_variables=include_variables)

        # Now we do final validation on the task, which sets all fields to their final values.
        self._task.post_validate(templar=templar)
        if '_variable_params' in self._task.args:
            variable_params = self._task.args.pop('_variable_params')
            if isinstance(variable_params, dict):
                display.deprecated(
                    "Using variables for task params is unsafe, especially if the variables come from an external source like facts",
                    version="2.6")
                variable_params.update(self._task.args)
                self._task.args = variable_params

        # get the connection and the handler for this execution
        if (not self._connection
                or not getattr(self._connection, 'connected', False)
                or self._play_context.remote_addr !=
                self._connection._play_context.remote_addr):
            self._connection = self._get_connection(variables=variables,
                                                    templar=templar)
        else:
            # if connection is reused, its _play_context is no longer valid and needs
            # to be replaced with the one templated above, in case other data changed
            self._connection._play_context = self._play_context

        self._set_connection_options(variables, templar)

        # get handler
        self._handler = self._get_action_handler(connection=self._connection,
                                                 templar=templar)

        # And filter out any fields which were set to default(omit), and got the omit token value
        omit_token = variables.get('omit')
        if omit_token is not None:
            self._task.args = dict((i[0], i[1])
                                   for i in iteritems(self._task.args)
                                   if i[1] != omit_token)

        # Read some values from the task, so that we can modify them if need be
        if self._task.until:
            retries = self._task.retries
            if retries is None:
                retries = 3
            elif retries <= 0:
                retries = 1
            else:
                retries += 1
        else:
            retries = 1

        delay = self._task.delay
        if delay < 0:
            delay = 1

        # make a copy of the job vars here, in case we need to update them
        # with the registered variable value later on when testing conditions
        vars_copy = variables.copy()

        display.debug("starting attempt loop")
        result = None
        for attempt in range(1, retries + 1):
            display.debug("running the handler")
            try:
                result = self._handler.run(task_vars=variables)
            except AnsibleActionSkip as e:
                return dict(skipped=True, msg=to_text(e))
            except AnsibleActionFail as e:
                return dict(failed=True, msg=to_text(e))
            except AnsibleConnectionFailure as e:
                return dict(unreachable=True, msg=to_text(e))
            display.debug("handler run complete")

            # preserve no log
            result["_ansible_no_log"] = self._play_context.no_log

            # update the local copy of vars with the registered value, if specified,
            # or any facts which may have been generated by the module execution
            if self._task.register:
                vars_copy[self._task.register] = wrap_var(result.copy())

            if self._task.async_val > 0:
                if self._task.poll > 0 and not result.get(
                        'skipped') and not result.get('failed'):
                    result = self._poll_async_result(result=result,
                                                     templar=templar,
                                                     task_vars=vars_copy)
                    # FIXME callback 'v2_runner_on_async_poll' here

                # ensure no log is preserved
                result["_ansible_no_log"] = self._play_context.no_log

            # helper methods for use below in evaluating changed/failed_when
            def _evaluate_changed_when_result(result):
                if self._task.changed_when is not None and self._task.changed_when:
                    cond = Conditional(loader=self._loader)
                    cond.when = self._task.changed_when
                    result['changed'] = cond.evaluate_conditional(
                        templar, vars_copy)

            def _evaluate_failed_when_result(result):
                if self._task.failed_when:
                    cond = Conditional(loader=self._loader)
                    cond.when = self._task.failed_when
                    failed_when_result = cond.evaluate_conditional(
                        templar, vars_copy)
                    result['failed_when_result'] = result[
                        'failed'] = failed_when_result
                else:
                    failed_when_result = False
                return failed_when_result

            if 'ansible_facts' in result:
                vars_copy.update(namespace_facts(result['ansible_facts']))
                if C.INJECT_FACTS_AS_VARS:
                    vars_copy.update(clean_facts(result['ansible_facts']))

            # set the failed property if it was missing.
            if 'failed' not in result:
                # rc is here for backwards compatibility and modules that use it instead of 'failed'
                if 'rc' in result and result['rc'] not in [0, "0"]:
                    result['failed'] = True
                else:
                    result['failed'] = False

            # set the changed property if it was missing.
            if 'changed' not in result:
                result['changed'] = False

            # if we didn't skip this task, use the helpers to evaluate the changed/
            # failed_when properties
            if 'skipped' not in result:
                _evaluate_changed_when_result(result)
                _evaluate_failed_when_result(result)

            if retries > 1:
                cond = Conditional(loader=self._loader)
                cond.when = self._task.until
                result['attempts'] = attempt
                if cond.evaluate_conditional(templar, vars_copy):
                    break
                else:
                    # no conditional check, or it failed, so sleep for the specified time
                    if attempt < retries:
                        result['_ansible_retry'] = True
                        result['retries'] = retries
                        display.debug('Retrying task, attempt %d of %d' %
                                      (attempt, retries))
                        self._rslt_q.put(TaskResult(
                            self._host.name,
                            self._task._uuid,
                            result,
                            task_fields=self._task.dump_attrs()),
                                         block=False)
                        time.sleep(delay)
        else:
            if retries > 1:
                # we ran out of attempts, so mark the result as failed
                result['attempts'] = retries - 1
                result['failed'] = True

        # do the final update of the local variables here, for both registered
        # values and any facts which may have been created
        if self._task.register:
            variables[self._task.register] = wrap_var(result)

        if 'ansible_facts' in result:
            variables.update(namespace_facts(result['ansible_facts']))
            if C.INJECT_FACTS_AS_VARS:
                variables.update(clean_facts(result['ansible_facts']))

        # save the notification target in the result, if it was specified, as
        # this task may be running in a loop in which case the notification
        # may be item-specific, ie. "notify: service {{item}}"
        if self._task.notify is not None:
            result['_ansible_notify'] = self._task.notify

        # add the delegated vars to the result, so we can reference them
        # on the results side without having to do any further templating
        # FIXME: we only want a limited set of variables here, so this is currently
        #        hardcoded but should be possibly fixed if we want more or if
        #        there is another source of truth we can use
        delegated_vars = variables.get('ansible_delegated_vars',
                                       dict()).get(self._task.delegate_to,
                                                   dict()).copy()
        if len(delegated_vars) > 0:
            result["_ansible_delegated_vars"] = {
                'ansible_delegated_host': self._task.delegate_to
            }
            for k in ('ansible_host', ):
                result["_ansible_delegated_vars"][k] = delegated_vars.get(k)

        # and return
        display.debug("attempt loop complete, returning result")
        return result
Пример #12
0
    def _run_loop(self, items):
        '''
        Runs the task with the loop items specified and collates the result
        into an array named 'results' which is inserted into the final result
        along with the item for which the loop ran.
        '''

        results = []

        # make copies of the job vars and task so we can add the item to
        # the variables and re-validate the task with the item variable
        # task_vars = self._job_vars.copy()
        task_vars = self._job_vars

        loop_var = 'item'
        label = None
        loop_pause = 0
        if self._task.loop_control:
            loop_var = self._task.loop_control.loop_var
            loop_pause = self._task.loop_control.pause
            # the these may be 'None', so we still need to default to something useful
            label = self._task.loop_control.label or ('{{' + loop_var + '}}')

        if loop_var in task_vars:
            display.warning(
                u"The loop variable '%s' is already in use. "
                u"You should set the `loop_var` value in the `loop_control` option for the task"
                u" to something else to avoid variable collisions and unexpected behavior."
                % loop_var)

        ran_once = False
        if self._task.loop_with:
            # Only squash with 'with_:' not with the 'loop:', 'magic' squashing can be removed once with_ loops are
            items = self._squash_items(items, loop_var, task_vars)

        for item in items:
            task_vars[loop_var] = item

            # pause between loop iterations
            if loop_pause and ran_once:
                time.sleep(loop_pause)
            else:
                ran_once = True

            try:
                tmp_task = self._task.copy(exclude_parent=True,
                                           exclude_tasks=True)
                tmp_task._parent = self._task._parent
                tmp_play_context = self._play_context.copy()
            except AnsibleParserError as e:
                results.append(dict(failed=True, msg=to_text(e)))
                continue

            # now we swap the internal task and play context with their copies,
            # execute, and swap them back so we can do the next iteration cleanly
            (self._task, tmp_task) = (tmp_task, self._task)
            (self._play_context, tmp_play_context) = (tmp_play_context,
                                                      self._play_context)
            res = self._execute(variables=task_vars)
            task_fields = self._task.dump_attrs()
            (self._task, tmp_task) = (tmp_task, self._task)
            (self._play_context, tmp_play_context) = (tmp_play_context,
                                                      self._play_context)

            # now update the result with the item info, and append the result
            # to the list of results
            res[loop_var] = item
            res['_ansible_item_result'] = True
            res['_ansible_ignore_errors'] = task_fields.get('ignore_errors')

            if label is not None:
                templar = Templar(loader=self._loader,
                                  shared_loader_obj=self._shared_loader_obj,
                                  variables=self._job_vars)
                res['_ansible_item_label'] = templar.template(label)

            self._rslt_q.put(
                TaskResult(
                    self._host.name,
                    self._task._uuid,
                    res,
                    task_fields=task_fields,
                ),
                block=False,
            )
            results.append(res)
            del task_vars[loop_var]

        return results