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


115

我正在寻找一种方法来执行任务,当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

Answers:


213

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


4
感谢这对我when: deployed_revision is not defined or deployed_revision.stdout is not defined or deployed_revision.stdout == ''
有用

5
您还可以将其与不同的条件结合使用:when: item.sudo is defined and item.sudo == true
czerasz

5
不要做我做的事,并在foo中加上大括号when: foo is defined(例如,这不起作用:when: {{ foo }} is defined
David

2
@David我和你一样面临同样的问题。打破条件时放大括号。要使此工作正常运行,您需要在条件周围加上括号。例如 when: ({{ foo }} in undefined)
Tarun

7
不赞成在Ansible中使用花括号作为条件词。另外,Ansible语句不能以变量扩展名开头(例如{{ foo }})。这不是因为Ansible,而是Yaml会将其解释为对象。如果您需要从变量扩展开始,只需将整个内容用双引号引起来(例如"{{ foo }}"),以强制Yaml将其视为字符串并将其原样传递给Ansible。
维克多·施罗德

11

根据最新的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文档


5

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

对于“普通”变量,无论是否定义和设置,都会有所不同。见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
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.