gpt4 book ai didi

ansible - 在ansible中从until循环打印自定义消息

转载 作者:行者123 更新时间:2023-12-04 15:37:45 24 4
gpt4 key购买 nike

我试图多次运行一个命令并检查输出中是否包含一些字符串(“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

最佳答案

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

  • 第一个任务将使用 until 轮询所需的输出环形。但是我们用过ignore_errors: True ,所以 until循环不会使剧本失败。我们将只捕获结果。
  • 在第二个任务中,使用 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"

    关于ansible - 在ansible中从until循环打印自定义消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59161114/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com