Interview Prep/Ansible/Variables, Facts and Precedence Problems

`'ansible.vars.hostvars.HostVarsVars object' has no attribute 'ansible_default_ipv4'` when templating `hostvars['db01']`

IntermediateTroubleshootingVariables, Facts and Precedence Problems
Answer

Likely causes → Facts for db01 were never gathered in this run. Either db01 is not in the current play, or --limit web* excluded it, so only inventory variables exist for it.

Diagnose →

- ansible.builtin.debug:
    msg: "{{ hostvars['db01'].keys() | list }}"

Fix → Gather facts for the database hosts first:

- hosts: dbservers
  gather_facts: true
  tasks: []
- hosts: webservers
  tasks: ...

Alternatively, use ansible.builtin.setup with delegate_to: "{{ item }}" and delegate_facts: true over groups['dbservers'], or turn on a fact cache.

Prevent → Put stable addresses in inventory variables (db_private_ip) instead of relying on another host's facts.

All Ansible questions Roadmap: Ansible

More on Variables, Facts and Precedence Problems