Ansible: print only user defined variables

Viewed 1915

How can I print variables declared only at group_vars, host_vars without ansible facts?

such code is good:

- name: "Ansible | List all known variables and facts"
  debug:
    var: hostvars[inventory_hostname]

But I don't need host IPs,disks, etc.

I mean to check all my variables one more time before continue to execute Play.

1 Answers

There are 3 categories of variables: ansible facts, special variables, and user's variables. Remove both ansible facts and special variables from hostvars and what is left are user's variables. The list of the ansible facts is available in the variables ansible_facts. The list of the special variables must be created (I think).

Create a list of special variables

If you run the playbook below you'll see the list of the special variables and user's variables

- hosts: localhost
  tasks:
    - debug:
        msg: "{{ hostvars[inventory_hostname]|
                 difference(ansible_facts) }}"

Eliminate the user's vars and put the list of the special variables into a file. For example

shell> cat special_vars.yml
special_vars:
  - ansible_python_interpreter
  - ansible_connection
  - inventory_hostname
    ...

This list of special variables might be not complete and will serve the purpose of this host only.

Remove ansible facts and special variables from hostvars

- hosts: localhost
  vars_files:
    - special_vars.yml
  tasks:
    - set_fact:
        user_var1: AAA
    - debug:
        msg: "{{ hostvars[inventory_hostname]|
                 difference(ansible_facts)
                 difference(special_vars) }}"

gives the list of user's variables only

  msg:
  - user_var1

The user's variables will include also the configuration variables set by the user (e.g. connection variables: ansible_user or priviledge escalation: ansible_become).


Name-space

A better practice is to "name-space" variables. For example

- hosts: localhost
  vars:
    prj51_var1: AAA
    prj51_var2: BBB
  tasks:
    - debug:
        msg: "{{ item }}: {{ query('vars', item)|first }}"
      loop: "{{ query('varnames', 'prj51_.+$') }}"

gives

  msg: 'prj51_var1: AAA'
  msg: 'prj51_var2: BBB'
Related