在 ansible 中打印从 till 循环的自定义消息



我正在尝试多次运行命令并检查输出中是否包含一些字符串("hi"(。我有目的地模拟故障并期望until循环失败。到目前为止,一切都很好。

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

所以问题是,如果循环无法通过重试,我如何从 till 循环打印自定义消息。

剧本:

-->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

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

  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"

看看可用于此目的的块错误处理。

基本概述:

- 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 }}"

最新更新