如何运行一个任务时,变量是未定义在可视?

我正在寻找一种方法来执行任务时,Ansible 变量不是寄存器或未定义。

例如:

- name: some task
command:  sed -n '5p' "{{app.dirs.includes}}/BUILD.info" | awk '{print  $2}'
when: (! deployed_revision) AND ( !deployed_revision.stdout )
register: deployed_revision
293639 次浏览

来自 可靠的文件:

如果没有设置所需的变量,可以使用 Jinja2定义的测试跳过或失败。例如:

tasks:
- name: Run the command if "foo" is defined
ansible.builtin.shell: echo "I've got '\{\{ foo }}' and am not afraid to use it!"
when: foo is defined


- name: Fail if "bar" is undefined
ansible.builtin.fail: msg="Bailing out. This play requires 'bar'"
when: bar is undefined

因此,在您的情况下,when: deployed_revision is not defined应该工作。

根据最新的 AnsibleVersion 2.5,要检查是否定义了变量,如果要运行任何任务,则根据这一点使用 undefined关键字。

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 undefined

可移植文件

严格说明,您必须检查以下所有内容: 定义,而不是空和没有。

对于“正常”变量,定义、设置或不设置都会产生影响。请参见下面示例中的 foobar。两者都已定义,但只设置了 foo

在另一端,已注册的变量被设置为运行命令的结果,并且在不同的模块之间有所不同。大部分都是 Json 建筑。您可能必须检查您感兴趣的子元素。见下面例子中的 xyzxyz.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

您可以使用此代码检查可变变量是否为空。

tasks:


- fail: msg="The variable 'bar' is empty"
when: bar|length == 0


- shell: echo "The variable 'foo' is not empty: '\{\{ foo }}'"
when: foo|length > 0

我希望这对你有帮助。