Ansibleundefinedvariable: 'Ansible. Vars. Hostvars. Hostvarsvars Object' Has No Attribute
I'm Using Ansible and I'm Getting This Error After Running My Playbook. This Is My Playbook: --- - Name: Set 192.168.122.4 Hostname Hosts: 192.168.122.4...
I'm using Ansible and I'm getting this error after running my playbook.
This is my playbook:
---
- name: Set 192.168.122.4 Hostname
hosts: 192.168.122.4
gather_facts: false
become: true
tasks:
- name : Name 4
hostname:
name: ansible1.example.com
- name: Set 192.168.122.5 Hostname
hosts: 192.168.122.5
gather_facts: false
become: true
tasks:
- name : Name 5
hostname:
name: ansible2.example.com
- name: Manage Hosts File
hosts: all
gather_facts: true
become: true
tasks:
- name: Deploy Hosts Template
template:
src: hosts.j2
dest: /etc/hosts
This is my Template
# Managed by Ansible
127.0.0.1 localhost
{% for host in groups['all'] %}
{{ hostvars[host]['ansible_default_ipv4']['address'] }} {{ hostvars[host]['ansible_fqdn'] }} {{ hostvars[host]['ansible_hostname'] }}
{% endfor %}
I get this error:
AnsibleUndefinedVariable: 'ansible.vars.hostvars.HostVarsVars object' has no attribute 'ansible_default_ipv4
I have tried using the debug module to see if I get back a response from ansible_default_ipv4, and I get a list there including the address, which is what I want. So its not the case that the remote servers don't have that setup, they do, the info is there, but just how do I retrieve it so I can populate this /etc/hosts file.
BUT I've found out that it's not about the ansible_default_ipv4 per se, because it will give the same error for another object.
So I'm guessing that its something to do with these magic variables from the Template.
My references are:
RHCE 8 - Ansible RHCE - Using Jinja Templates to Populate Host Files by theurbanpenguin on YouTube, look it up
2 Answers
Thanks @Jack @Zeitounator, the issue was on my inventory. So apparently if you leave a server on your inventory that you are not using, for example, my inventory was
10.0.2.[4:7]
but I left my [7] machine off, once I removed and made my inventory like
10.0.2.[4:6] it started working.
So Im guessing that if you have a machine listed in your inventory that you are not using anymore it can cause issues with magic variables.
My lesson here is to keep inventory file clean.
Thanks
you must specify hosts:all
gathering: This only affects the gathering done by a play's gather_facts directive,