The only way I've found to select variables by a wildcard is to loop all variables and test match. For example
tasks:
- debug:
var: item
loop: "{{ query('dict', hostvars[inventory_hostname]) }}"
when: item.key is match("^.*_python_.*$")
shell> ansible-playbook test.yml | grep key:
key: ansible_python_interpreter
key: ansible_python_version
key: ansible_selinux_python_present
Neither json_query([?key=='name']), nor lookup('vars', 'name') work with wildcards.
Note: regex_search is discussed in What is the syntax within the regex_search() to match against a variable?
You can select/reject with Jinja tests:
- debug:
msg: "{{ lookup('vars', item) }}"
loop: "{{ hostvars[inventory_hostname].keys() | select('match', '^.*_python_.*$') | list }}"
gives:
ok: [localhost] => (item=ansible_selinux_python_present) => {
"msg": false
}
ok: [localhost] => (item=ansible_python_version) => {
"msg": "2.7.10"
}
Update for Ansible 2.8 and higher versions.
There is the lookup plugin varnames added in Ansible 2.8. to "List of Python regex patterns to search for in variable names"
. See details
shell> ansible-doc -t lookup varnames
For example, to list the variables .*_python_.*
the task below
- debug:
msg: "{{ item }}: {{ lookup('vars', item) }}"
loop: "{{ query('varnames', '^.*_python_.*$') }}"
gives
TASK [debug] ***************************************************************
ok: [localhost] => (item=ansible_python_interpreter) =>
msg: 'ansible_python_interpreter: /usr/bin/python3'
ok: [localhost] => (item=ansible_python_version) =>
msg: 'ansible_python_version: 3.8.5'
ok: [localhost] => (item=ansible_selinux_python_present) =>
msg: 'ansible_selinux_python_present: True
Moreover, the lookup plugin varnames will find also variables not 'instantiated' yet and therefore not included in the hostvars.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With