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

时间:2015-05-08 09:08:48

标签: ansible ansible-playbook

我正在寻找一种在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

3 个答案:

答案 0 :(得分:173)

来自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应该正常工作

答案 1 :(得分:10)

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

答案 2 :(得分:4)

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

对于“普通”变量,无论是否定义和设置,都会有所不同。请参见以下示例中的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