如何在条件下无错误地退出 Ansible play [英] How do I exit Ansible play without error on a condition
问题描述
我想在没有错误的情况下退出(我知道 assert 和 fail modules) 当我满足某个条件时.以下代码退出但失败:
I want to exit without an error (I know about assert and fail modules) when I meet a certain condition. The following code exits but with a failure:
tasks:
- name: Check if there is something to upgrade
shell: if apt-get --dry-run upgrade | grep -q "0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded"; then echo "no"; else echo "yes"; fi
register: upgrading
- name: Exit if nothing to upgrade
fail: msg="Nothing to upgrade"
when: upgrading.stdout == "no"
推荐答案
从 Ansible 2.2 开始,您可以将 end_play
与 meta 模块:
Since Ansible 2.2, you can use end_play
with the meta module:
- meta: end_play
你也可以指定when
有条件地结束播放:
You can also specify when
for conditionally ending the play:
- meta: end_play
when: upgrading.stdout == "no"
但是请注意,无论该剧是否真正结束,该任务并未列在 ansible-playbook 的输出中.此外,任务不计入回顾.因此,您可以执行以下操作:
Note, though, that the task is not listed in the output of ansible-playbook, regardless of whether or not the play actually ends. Also, the task is not counted in the recap. So, you could do something like:
- block:
- name: "end play if nothing to upgrade"
debug:
msg: "nothing to upgrade, ending play"
- meta: end_play
when: upgrading.stdout == "no"
它将在结束之前宣布播放结束,仅当条件满足时.如果不满足条件,您将看到名为 end play if nothing to upgrade
的任务被适当跳过,这将为用户提供更多关于游戏结束或不结束的信息.
which will announce the end of the play right before ending it, only when the condition is met. If the condition is not met, you'll see the task named end play if nothing to upgrade
appropriately skipped, which would provide more info to the user as to why the play is, or is not, ending.
当然,这只会结束当前的播放,而不是所有剧本中剩余的播放.
Of course, this will only end the current play and not all remaining plays in the playbook.
2019 年 6 月 20 日更新:
UPDATE June 20 2019:
正如评论中提到的,end_play
结束所有主机的播放.在 Ansible 2.8 中,end_host
被添加到 元:
As reto mentions in comments, end_play
ends the play for all hosts. In Ansible 2.8, end_host
was added to meta:
end_host(在 Ansible 2.8 中添加)是 end_play 的每主机变体.使当前主机的播放结束而不会失败.
end_host (added in Ansible 2.8) is a per-host variation of end_play. Causes the play to end for the current host without failing it.
2021 年 2 月更新:修复了元模块的断开链接
UPDATE Feb 2021: fixed broken link to meta module
这篇关于如何在条件下无错误地退出 Ansible play的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!