Answers:
来自ansible docs:如果尚未设置必需的变量,则可以使用Jinja2定义的测试跳过或失败。例如:
tasks:
- shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
when: foo is defined
- fail: msg="Bailing out. this play requires 'bar'"
when: bar is not defined
所以在你的情况下,when: deployed_revision is not defined
应该工作
when: item.sudo is defined and item.sudo == true
when: foo is defined
(例如,这不起作用:when: {{ foo }} is defined
when: ({{ foo }} in undefined)
{{ foo }}
)。这不是因为Ansible,而是Yaml会将其解释为对象。如果您需要从变量扩展开始,只需将整个内容用双引号引起来(例如"{{ foo }}"
),以强制Yaml将其视为字符串并将其原样传递给Ansible。
严格说来,您必须检查以下所有内容:已定义,不为空且不为无。
对于“普通”变量,无论是否定义和设置,都会有所不同。见foo
并bar
在下面的例子。两者均已定义,但仅foo
已设置。
另一方面,已注册的变量设置为运行命令的结果,并且因模块而异。它们主要是json结构。您可能必须检查您感兴趣的子元素。请参见xyz
和xyz.msg
下面的示例中:
cat > test.yml <<EOF
- hosts: 127.0.0.1
vars:
foo: "" # foo is defined and foo == '' and foo != None
bar: # bar is defined and bar != '' and bar == None
tasks:
- debug:
msg : ""
register: xyz # xyz is defined and xyz != '' and xyz != None
# xyz.msg is defined and xyz.msg == '' and xyz.msg != None
- debug:
msg: "foo is defined and foo == '' and foo != None"
when: foo is defined and foo == '' and foo != None
- debug:
msg: "bar is defined and bar != '' and bar == None"
when: bar is defined and bar != '' and bar == None
- debug:
msg: "xyz is defined and xyz != '' and xyz != None"
when: xyz is defined and xyz != '' and xyz != None
- debug:
msg: "{{ xyz }}"
- debug:
msg: "xyz.msg is defined and xyz.msg == '' and xyz.msg != None"
when: xyz.msg is defined and xyz.msg == '' and xyz.msg != None
- debug:
msg: "{{ xyz.msg }}"
EOF
ansible-playbook -v test.yml
when: deployed_revision is not defined or deployed_revision.stdout is not defined or deployed_revision.stdout == ''