如何在 ansible 中未定义变量时 运行 任务?

How to run a task when variable is undefined in ansible?

我正在寻找一种方法来在 ansible 变量未注册/未定义时执行任务,例如

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

来自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 应该有效

根据最新的 Ansible 版本 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

Ansible Documentation

严格来说,您必须检查以下所有内容:已定义、不为空且不 None。

对于 "normal" 变量,定义和设置或未设置都会有所不同。请参阅下面示例中的 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

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

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

希望对你有所帮助