Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible variables wildcard selection

Tags:

ansible

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
  • Is there a more efficient way to do it?

Neither json_query([?key=='name']), nor lookup('vars', 'name') work with wildcards.

  • Is there any other "wildcard-enabled" test, filter ...?

Note: regex_search is discussed in What is the syntax within the regex_search() to match against a variable?

like image 379
Vladimir Botka Avatar asked Jan 29 '19 13:01

Vladimir Botka


2 Answers

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"
}
like image 145
Konstantin Suvorov Avatar answered Nov 15 '22 08:11

Konstantin Suvorov


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.

like image 34
Vladimir Botka Avatar answered Nov 15 '22 08:11

Vladimir Botka