
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
- 5,234 Views
Hello All,
I have seen a post or two about this already, but there hasn't been any real solution proposed.
The following is given as a template to generate /etc/hosts:
{% for host in groups['all'] %} {{ hostvars[host]['ansible_facts']['default_ipv4']['address'] }} {{ hostvars[host]['ansible_facts']['fqdn'] }} {{ hostvars[host]['ansible_facts']['hostname'] }} {% endfor %}
However, after running this is seems that I receive "AnsibleUndefinedVariable: 'dict object' has no attribute 'default_ipv4'".
What is the confusion here? How else would one be able to easily generate an /etc/hosts file using a template?
Thanks
Accepted Solutions

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
- 5,221 Views
It looks like I was specifying a specific group of hosts to move this template to... This can't be done since we haven't gathered facts for all of the hosts, only the ones in which we run our play against.. oops

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
- 5,222 Views
It looks like I was specifying a specific group of hosts to move this template to... This can't be done since we haven't gathered facts for all of the hosts, only the ones in which we run our play against.. oops

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
- 3,670 Views
This code is working fine:
$ cat hosts.yml
---
- name: use template
hosts: all
tasks:
- template:
src: hosts.j2
dest: myhosts
$ cat hosts.j2
{% for host in groups['all'] %}
{{ hostvars[host]['ansible_facts']['default_ipv4']['address'] }} {{ hostvars[host]['ansible_facts']['fqdn'] }} {{ hostvars[host]['ansible_facts']['hostname'] }}
{% endfor %}
To debug just let {{ hostvars[host] }} in the j2 file and watch the output