Skip to content

vars

Collection Note

This module is part of the ansible.builtin collection. To install the collection, use:

ansible-galaxy collection install ansible.builtin
Added in version 2.5.

Synopsis

  • Retrieves the value of an Ansible variable. Note: Only returns top level variable names.

Parameters

Parameter Defaults / Choices Comments
_terms
required
The variable names to look up.
default What to return if a variable is undefined.
If no default is set, it will result in an error if any of the variables is undefined.

Examples

- name: Show value of 'variablename'
  ansible.builtin.debug: msg="{{ lookup('ansible.builtin.vars', 'variabl' + myvar) }}"
  vars:
    variablename: hello
    myvar: ename

- name: Show default empty since i dont have 'variablnotename'
  ansible.builtin.debug: msg="{{ lookup('ansible.builtin.vars', 'variabl' + myvar, default='') }}"
  vars:
    variablename: hello
    myvar: notename

- name: Produce an error since i dont have 'variablnotename'
  ansible.builtin.debug: msg="{{ q('vars', 'variabl' + myvar) }}"
  ignore_errors: True
  vars:
    variablename: hello
    myvar: notename

- name: find several related variables
  ansible.builtin.debug: msg="{{ query('ansible.builtin.vars', 'ansible_play_hosts', 'ansible_play_batch', 'ansible_play_hosts_all') }}"

- name: show values from variables found via varnames (note "*" is used to dereference the list to a 'list of arguments')
  debug: msg="{{ q('vars', *q('varnames', 'ansible_play_.+')) }}"

- name: Access nested variables
  ansible.builtin.debug: msg="{{ lookup('ansible.builtin.vars', 'variabl' + myvar).sub_var }}"
  ignore_errors: True
  vars:
    variablename:
        sub_var: 12
    myvar: ename

- name: alternate way to find some 'prefixed vars' in loop
  ansible.builtin.debug: msg="{{ lookup('ansible.builtin.vars', 'ansible_play_' + item) }}"
  loop:
    - hosts
    - batch
    - hosts_all

Return Values

Key Data Type Description Returned
_value list value of the variables requested.

Authors

  • Ansible Core Team