Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...