# Build /etc/hosts with template

**URL:** <https://forum.ansible.com/t/build-etc-hosts-with-template/19453>\
**Category:** Ansible Project\
**Created:** [October 7, 2015, 9:08am UTC](https://forum.ansible.com/t/build-etc-hosts-with-template/19453 "2015-10-07T09:08:48Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![jepper](https://avatars.discourse-cdn.com/v4/letter/j/49beb7/32.png) [@jepper](https://forum.ansible.com/u/jepper)\
**Post date:** [October 7, 2015, 9:08am UTC](https://forum.ansible.com/t/build-etc-hosts-with-template/19453/1 "2015-10-07T09:08:48Z")

</div>

I have a template to build /etc/hosts by taking stuff from the inventory file. It’s fragile to be sure, and I’m looking for suggestions. Here what I have so far:

$ cat hosts.j2

127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4  
{% for host in groups[‘all’] %}

{{ hostvars[host][‘ansible\_eth0’][‘ipv4’][‘address’] }} {{ host }} {{ host }}.{{ clientspecific\_dns\_domain }}  
{% endfor %}

This generates

$ cat /etc/hosts  
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4  
10.124.44.2 box1 [box1.domain.com](http://box1.domain.com)

10.124.44.3 box2 [box2.domain.com](http://box2.domain.com)

The problem with this is if I change the scope of targets, e.g.  
ansible-playbook site.yml -l box1

I end with just box1 in the hosts file on box1. Is there a better way?
