有条件的情况下如何避免重复?

时间:2019-06-04 21:44:10

标签: ansible

我有这本剧本:

---
- name: Test
  hosts: localhost

  tasks:
    - name: Ansible grep pattern with ignore_errors example
      shell: "grep 'authorization' /tmp/junk.test"
      register: grep_output
      ignore_errors: true

    - name: Output debug grep_output
      debug:
        var: grep_output
        verbosity: 0
      shell: "echo 'Hello!'"
      when: grep_output.failed

当我运行它时,出现此错误:

ERROR! conflicting action statements: debug, shell

所以我必须将剧本改写成这样:

---
- name: Test
  hosts: localhost

  tasks:
    - name: Ansible grep pattern with ignore_errors example
      shell: "grep 'authorization' /tmp/junk.test"
      register: grep_output
      ignore_errors: true

    - name: Output debug grep_output
      debug:
        var: grep_output
        verbosity: 0
      when: grep_output.failed

    - name: Echo hello
      shell: "echo 'Hello!'"
      when: grep_output.failed

所以我要重复when: grep_output.failed。有没有更好的方式编写上述剧本?

谢谢

1 个答案:

答案 0 :(得分:2)

您可以使用block statement。它允许您对模块进行分组,并对整个块使用单个when语句。 这应该起作用:

---
- name: Test
  hosts: localhost

  tasks:
    - name: Ansible grep pattern with ignore_errors example
      shell: "grep 'authorization' /tmp/junk.test"
      register: grep_output
      ignore_errors: true

    - block:
      - name: Output debug grep_output
        debug:
          var: grep_output
          verbosity: 0

      - name: Echo hello
        shell: "echo 'Hello!'"
      when: grep_output.failed