RAM88
RAM88

Reputation: 23

Check if a value is part of a list, the name of the list being in a variable

I try to find if a variable has a valid value which is stored in a list.
The name of the list is also stored in a variable. If the variable is not valid the test should fail.
This works if I use the name of the list:

- fail: msg="unsupported version requested"
  when: requestedversion not in windowsversionlist

But the name of the versionlist is also a variable because there are more lists like linux and windows.

This does not work:

- fail: msg="unsupported version requested"
  when: requesterversion not in versionlist 

The value of the variable versionlist is windowsversionlist

I try {{ versionlist }}, etc. but this does not work.

Upvotes: 2

Views: 6701

Answers (1)

β.εηοιτ.βε
β.εηοιτ.βε

Reputation: 39129

You should use the vars lookup:

- fail: 
    msg: "unsupported version requested"
  when: "requestedversion not in lookup('vars', versionlist)"

Given the playbook:

- hosts: localhost
  gather_facts: no
      
  tasks:
    - fail: 
        msg: "unsupported version requested"
      when: "requestedversion not in lookup('vars', versionlist)"
      vars:
        requestedversion: a.a.a
        versionlist: windowsversionlist
        windowsversionlist: 
          - x.x.x
          - y.y.y
          - z.z.z

This gives:

TASK [fail] *******************************************************
fatal: [localhost]: FAILED! => changed=false 
  msg: unsupported version requested

Upvotes: 7

Related Questions