Ansible 和基于 `stdout` 值的 `changed_when` [英] Ansible and `changed_when` based on `stdout` value
问题描述
我正在运行一个自定义命令,因为我还没有找到一个可以做我需要的工作模块,我想调整 changed
标志以反映实际行为:
I am running a custom command because I haven't found a working module doing what I need, and I want to adjust the changed
flag to reflect the actual behaviour:
- name: Remove unused images
shell: '[ -n "$(docker images -q -f dangling=true)" ] && docker rmi $(docker images -q -f dangling=true) || echo Ignoring failure...'
register: command_result
changed_when: "command_result.stdout == 'Ignoring failure...'"
- debug: var="1 {{ command_result.stdout }}"
when: "command_result.stdout != 'Ignoring failure...'"
- debug: var="2 {{ command_result.stdout }}"
when: "command_result.stdout == 'Ignoring failure...'"
(我知道 shell 命令很难看,可以通过更复杂的脚本进行改进,但我现在不想这样做)
(I know the shell command is ugly and could be improved by a more complex script but I don't want to for now)
在无法删除 Docker 映像的主机上运行此任务会产生以下输出:
Running this task on an host where no Docker image can be removed gives the following output:
TASK: [utils.dockercleaner | Remove unused images] ****************************
changed: [cloud-host] => {"changed": true, "cmd": "[ -n \"$(docker images -q -f dangling=true)\" ] && docker rmi $(docker images -q -f dangling=true) || echo Ignoring failure...", "delta": "0:00:00.064451", "end": "2015-07-30 18:37:25.620135", "rc": 0, "start": "2015-07-30 18:37:25.555684", "stderr": "", "stdout": "Ignoring failure...", "stdout_lines": ["Ignoring failure..."], "warnings": []}
TASK: [utils.dockercleaner | debug var="DIFFERENT {{ command_result.stdout }}"] ***
skipping: [cloud-host]
TASK: [utils.dockercleaner | debug var="EQUAL {{ command_result.stdout }}"] ***
ok: [cloud-host] => {
"var": {
"EQUAL Ignoring failure...": "EQUAL Ignoring failure..."
}
}
所以,我有这个 stdout 返回值 "stdout": "Ignoring failure..."
,并且调试任务显示字符串相等,所以 为什么任务仍然显示如改变"?
So, I have this stdout return value "stdout": "Ignoring failure..."
, and the debug task shows the strings are equal, so why is the task still displayed as "changed"?
我使用的是 ansible 1.9.1
.
我指的文档是这个:http://docs.ansible.com/ansible/playbooks_error_handling.html#overriding-the-changed-result
推荐答案
我想你可能误解了 changed_when
的作用.
I think you may have misinterpreted what changed_when
does.
changed_when
根据条件语句的评估将任务标记为已更改,在您的情况下为:
changed_when
marks the task as changed based on the evaluation of the conditional statement which in your case is:
"command_result.stdout == '忽略失败...'"
"command_result.stdout == 'Ignoring failure...'"
所以只要这个条件为真,任务就会被标记为已更改.
So whenever this condition is true, the task will be marked as changed.
这篇关于Ansible 和基于 `stdout` 值的 `changed_when`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!