Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
379 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...