如何仅根据条件通知 Ansible 中的处理程序? [英] How do you notify a handler in Ansible based solely on a conditional?
问题描述
我想通过执行以下操作来通知我角色中的处理程序:
I would like to notify a handler in my role by doing something like this:
- name: Notify handler
notify: my_handler
when: this_thing_is_true|bool
但 Ansible 只是抱怨:
But Ansible just whines:
错误!在任务中未检测到模块/操作.
ERROR! no module/action detected in task.
我尝试了各种楔子,例如:
I have tried various wedges, such as:
- name: Notify handler
meta: noop
notify: my_handler
when: this_thing_is_true|bool
但同样的抱怨:
[警告]:有条件时不支持 noop 任务有什么建议吗?
[WARNING]: noop task does not support when conditional Any suggestions?
推荐答案
请注意,运行任务不足以通知处理程序,您还需要一个创建更改结果的任务.
Please mind that running a task is not enough for an handler to be notified, you also need a task that creates a changed result.
在changed_when
Ansible 中的选项.
然后,做一个简单的 debug
可以成为一种选择.
You can achieve a change result on any task with the help of the changed_when
option in Ansible.
Then, doing a simple debug
could be an option.
我的其他想法,但最终没有真正意义:
The other ideas I had, but that did not really made sense in the end:
pause
:但你不能暂停少于一秒assert
:但是断言同样的条件感觉很愚蠢,你还需要放入changed_that
以通知处理程序.您仍然可以assert: that: true
,但感觉同样愚蠢.- 也许我能想到的最愚蠢的想法是带有
failed_when: false
的fail
任务. command: 'true'
与上面的相比可能不那么愚蠢,但我仍然不完全相信
pause
: but you cannot pause for less than a secondassert
: but it feels silly to assert the same condition that you also need to put in thechanged_that
to notify the handler. You can stillassert: that: true
but it feels equally silly.- Maybe the most silliest of the ideas I could came with was a
fail
task with afailed_when: false
. command: 'true'
is maybe less silly, compared to the above, but I am not totally convinced, still
给定剧本:
- hosts: local
gather_facts: no
vars:
this_thing_is_true: true
tasks:
- debug:
msg: 'Notifying handlers'
# var: this_thing_is_true
# ^-- might be an alternative option to msg:
changed_when: this_thing_is_true
notify:
- me
handlers:
- name: me
debug:
msg: 'I have been notified'
回顾一下:
PLAY [local] *******************************************************************
TASK [debug] *******************************************************************
changed: [local] => {
"msg": "Notifying handlers"
}
RUNNING HANDLER [me] ***********************************************************
ok: [local] => {
"msg": "I have been notified"
}
PLAY RECAP *********************************************************************
local : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
这篇关于如何仅根据条件通知 Ansible 中的处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!