Ansible variables wildcard selection
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.