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