打印自定义消息,直到循环循环

时间:2019-12-03 16:10:27

标签: ansible

我试图多次运行命令,并检查输出中是否包含某些字符串(“ hi”)。我故意模拟失败并期望until循环失败。到目前为止,一切都很好。

现在,我需要有一些自定义消息,说明为什么until循环或task失败。例如:"Your command failed to print hi"

所以问题是,如果在重试过程中循环无法通过,如何打印直到循环的自定义消息。

剧本:

-->cat until.yml
---

- hosts: localhost
  gather_facts: no
  tasks:

    - name: "check command"
      shell: echo hello
      register: var
      until: var.stdout.find('hi') != -1
      retries: 5
      delay: 1

剧本输出:

 -->ansible-playbook until.yml
PLAY [localhost] *************************************************************************************************************************************************************************************************************************

TASK [check command] ********************************************************************************************************************************************************************************************************
FAILED - RETRYING: who triggered the playbook (5 retries left).
FAILED - RETRYING: who triggered the playbook (4 retries left).
FAILED - RETRYING: who triggered the playbook (3 retries left).
FAILED - RETRYING: who triggered the playbook (2 retries left).
FAILED - RETRYING: who triggered the playbook (1 retries left).
fatal: [localhost]: FAILED! => {
    "attempts": 5,
    "changed": true,
    "cmd": "echo hello",
    "delta": "0:00:00.003004",
    "end": "2019-12-03 10:04:14.731488",
    "rc": 0,
    "start": "2019-12-03 10:04:14.728484"
}

STDOUT:

hello


PLAY RECAP *******************************************************************************************************************************************************************************************************************************
localhost                  : ok=0    changed=0    unreachable=0    failed=1

2 个答案:

答案 0 :(得分:0)

看看block error handling,可以将其用于此目的。

基本概述:

- block:
    - name: A task that may fail.
      debug:
        msg: "I may fail"
      failed_when: true
      register: might_fail_exec

  rescue:
    - name: fail nicely with a msg
      fail:
        msg: "The task that might fail has failed. Here is some info from the task: {{ might_fail_exec }}"

答案 1 :(得分:0)

您可以将任务分为两个任务:

  1. 第一个任务将使用until循环轮询所需的输出。但是我们使用了ignore_errors: True,所以until循环不会使剧本失败。我们将只捕获结果。

  2. 在第二项任务中,使用assert打印success_msg作为成功案例,fail_msg作为失败案例。

调整以下最小工作示例:

---

- hosts: localhost
  gather_facts: no
  tasks:

    - name: "check command"
      shell: echo hello
      register: var
      until: var.stdout.find('hi') != -1
      retries: 5
      delay: 1
      ignore_errors: true

    - name: "Print result"
      assert:
        that: var.stdout|regex_search('hi')
        fail_msg: "COuld not find HI in command output"
        success_msg: "Hi is present in Command output"