ansible:检查变量列表的正确方法是否已设置?

ansible: correct way to check a list of variables has been set?

我正在尝试使用 Ansible 2.5 中的 when: item is undefined 来检查是否已设置变量列表,如下所示:

- hosts: all
  tasks:
    - name: validate some variables
      fail:
        msg: "Required variable {{item}} has not been provided"
      when: item is undefined
      loop:
        - v1
        - v2

但是,无论是否提供 v1v2,这都不会失败。

切换 when 以使用 jinja2 模板有效:

when: "{{item}} is undefined"

但是 ansible 抱怨这个:

[WARNING]: when statements should not include jinja2 templating delimiters such as {{ }} or {% %}. Found: {{item}} is undefined

遍历变量名称列表并检查它们是否已设置的正确方法是什么?

尝试使用下面的

  with_items:
    - v1
    - v2

使用vars结构:

- name: validate some variables
  fail:
    msg: "Required variable {{item}} has not been provided"
  when: vars[item] is undefined
  loop:
    - v1
    - v2

或者,在 Ansible 2.5 中,使用新的 vars 查找插件:

- name: validate some variables
  debug:
  when: lookup('vars', item) is undefined
  loop:
    - v1
    - v2

虽然不是您指定的错误消息,但是查找插件的默认错误消息。

模块甚至不会被执行,所以你可以使用我在上面的例子中用 debug 替换 fail 的任何东西。

内部循环,你可以使用{{ variable | mandatory }}(参见Forcing variables to be defined

我认为将其添加为第一个任务看起来更好,它会检查 v1 和 v2 是否存在:

- name: 'Check mandatory variables are defined'
  assert:
    that:
      - v1 is defined
      - v2 is defined