ansible: correct way to check a list of variables

2019-02-26 03:16发布

问题:

I'm trying to use when: item is undefined in Ansible 2.5 to check if a list of variables have been set, as below:

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

However, this never fails regardless of whether v1 or v2 are provided.

Switching the when to use jinja2 templating works:

when: "{{item}} is undefined"

But ansible complains about this:

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

What is the correct way loop through a list of variable names and checked they have been set?

回答1:

Using the vars structure:

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

Or, in Ansible 2.5, with the new vars lookup plugin:

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

Although not with the error message you specified, but a default error message for a lookup plugin.

The module won't even be executed, so you can use whatever ー I replaced fail with debug in the example above.



回答2:

Inside loop, you can use {{ variable | mandatory }} (see Forcing variables to be defined)

I think it looks nicer to add this as first task, it checks is v1 and v2 exist:

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


回答3:

Try using below

  with_items:
    - v1
    - v2