Ansible – How to use a variable in a variable name
Some times you have to construct the name of a variable to use it.
In previous versions of ansible there was a syntax like this one vars[ ansible_hostname + 'string' ]
Now, since the Ansible 2.5 you have another syntax very useful
- name: Show value of 'variablename' debug: msg="{{ lookup('vars', 'variabl' + myvar)}}" vars: variablename: hello myvar: ename - name: Show default empty since i dont have 'variablnotename' debug: msg="{{ lookup('vars', 'variabl' + myvar, default='')}}" vars: variablename: hello myvar: notename - name: Produce an error since i dont have 'variablnotename' debug: msg="{{ lookup('vars', 'variabl' + myvar)}}" ignore_errors: True vars: variablename: hello myvar: notename - name: find several related variables debug: msg="{{ lookup('vars', 'ansible_play_hosts', 'ansible_play_batch', 'ansible_play_hosts_all') }}" - name: alternate way to find some 'prefixed vars' in loop debug: msg="{{ lookup('vars', 'ansible_play_' + item) }}" loop: - hosts - batch - hosts_all
Find the documentaiton here
Please follow and like us: