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

前端 未结 3 1086
生来不讨喜
生来不讨喜 2020-12-21 11:08

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:
    - n         


        
相关标签:
3条回答
  • 2020-12-21 11:53

    Try using below

      with_items:
        - v1
        - v2
    
    0 讨论(0)
  • 2020-12-21 12:04

    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.

    0 讨论(0)
  • 2020-12-21 12:11

    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
    
    0 讨论(0)
提交回复
热议问题