Ansible:模拟一个"passed when"模块

Ansible: simulating a "passed when" module

Ansible 提供了一个 failed_when 模块,允许用户在他们的任务中指定特定的失败条件,例如在 stdout 或 stderr 中找到某个字符串。

我正在尝试做相反的事情:如果在 stdout 或 stderr 中找到任何一组字符串,我希望我的任务 而不是 失败。换句话说,我想要一些接近 passed_when 模块功能的东西。

我的推理是这样的:

There are many reasons why the task could fail - but some of these, depending on the output, I do not consider as a failure in the current context.

有人知道如何实现吗?

您的原始问题是这样表述的(使用布尔逻辑使其更容易):

Succeed a command if a set of strings is found in stdout or stderr

重述你的逻辑:

如果在 stdout 或 stderr 中找不到一组字符串,则失败。使用此逻辑,failed_when 很容易做到。这是一个片段:

---
- name: Test failed_when as succeed_if
  hosts: localhost
  connection: local
  gather_facts: no

  tasks:
    - name: "'succeed_if' set of strings in stdout"
      command: /bin/echo succeed1
      register: command_result
      failed_when: "command_result.stdout not in ['succeed1',]"

    - name: "'succeed_if' set of strings in stdout (multiple values)"
      command: /bin/echo succeed2
      register: command_result
      failed_when: "command_result.stdout not in ['succeed1', 'succeed2']"

    - name: "'succeed_if' set of strings in stderr (multiple values)"
      shell: ">&2 /bin/echo succeed2 "
      register: command_result
      failed_when: "command_result.stderr not in ['succeed1', 'succeed2']"

    - name: "'succeed_if' set of strings in stderr (multiple values) or rc != 0"
      shell: ">&2 /bin/echo succeed2; /bin/false"
      register: command_result
      failed_when: "command_result.stderr not in ['succeed1', 'succeed2'] and command_result.rc != 0"

# vim: set ts=2 sts=2 fenc=utf-8 expandtab list:

另外,您可能正在寻找的文档是 Jinja2 Expressions

看这里:

- name: ping pong redis
  command: redis-cli ping
  register: command_result
  failed_when: 
    - "'PONG' not in command_result.stderr"
    - "command_result.rc != 0"
  • 如果 return code 为 0 且 stderr 中没有 'PONG' 则不会失败。
  • 如果 stderr 中有 "PONG" 则不会失败。

因此,如果列表中的任何一个为 False,它就会通过