2

I am learning Ansible and I am observe that the variable (fact) naming seems to be inconsistent.

For example, my Jinja2 template can run successfully.

{% for host in groups['node'] %}
{{ hostvars[host]['ansible_facts']['default_ipv4']['address'] }}
{% endfor %}

But if I run ad-hoc command setup to show all variables, the variable name will be ansible_default_ipv4. If I input the prefix ansible_ in playbooks, it then not run.

I ran then setup module to look for the variable name I need and I am so confuse about it now.

Am I doing it wrong, or have another proper way to look for variable name?

I tried looking for answer anywhere.

Thank you.

U880D
  • 8,601
  • 6
  • 24
  • 40
Dennis
  • 21
  • 2
  • Yes, you're right. It might be considered inconsistent. Ad hoc setup, e.g. `ansible localhost -m setup | grep default_ipv4` will give you `ansible_default_ipv4` while the *setup* module in a task will give you both `ansible_facts.default_ipv4` and `ansible_default_ipv4` in the *hostvars*. – Vladimir Botka Dec 12 '22 at 06:25
  • Does the thread [Why should I remove the`ansible_` prefix when refering to an Ansible fact?](https://stackoverflow.com/questions/73859125/) answer your question? – U880D Dec 12 '22 at 06:27
  • 1
    @U880D thanks!! it does help me to understand the reason behind that. – Dennis Dec 12 '22 at 07:03

1 Answers1

2

Q: "I run ad-hoc command setup to show all variables."

A: Use lookup plugins vars and varnames instead. See

shell> ansible-doc -t lookup varnames
shell> ansible-doc -t lookup vars

For example,

- hosts: localhost
  gather_facts: false
  vars:
    my_vars: "{{ query('varnames', 'ipv4') }}"
  tasks:
    - setup:
        gather_subset: default_ipv4
    - debug:
        var: my_vars
    - debug:
        msg: "{{ lookup('vars', item) }}"
      loop: "{{ my_vars }}"

gives

PLAY [localhost] *****************************************************************************

TASK [setup] *********************************************************************************
ok: [localhost]

TASK [debug] *********************************************************************************
ok: [localhost] => 
  my_vars:
  - ansible_default_ipv4
  - ansible_all_ipv4_addresses

TASK [debug] *********************************************************************************
ok: [localhost] => (item=ansible_default_ipv4) => 
  msg:
    address: 10.1.0.184
    alias: eth1
    broadcast: 10.1.0.255
    gateway: 10.1.0.10
    interface: eth1
    macaddress: <sanitized>
    mtu: 1500
    netmask: 255.255.255.0
    network: 10.1.0.0
    type: ether
ok: [localhost] => (item=ansible_all_ipv4_addresses) => 
  msg:
  - 172.17.0.1
  - 10.1.0.184

PLAY RECAP ***********************************************************************************
localhost: ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63