I've started learning and using ansible for configuring my staging and production servers. One thing I'd like to do is configure /etc/hosts through the inventory file.

It seems that this is possible. Here is one such usage: https://gist.github.com/rothgar/8793800

However, I'm a little green to Ansible and I don't get it. Can someone please explain in plain english how I make it work in practice?

For example, if my inventory file contains.





I'd like to say with consistency that my hosts file after running the playbook contained db1 db2 db3 compute1 compute2

Is this possible?

  • Would you be open to give your hosts explicit hostnames in the inventory? Because everything else might be prone to errors.
    – udondan
    Feb 29, 2016 at 4:15

2 Answers 2


You could generate your hosts entries from a template. Loop over the list of groups, discard groups like all and ungrouped, and then loop over the list of hosts in each group:

{# this loops over the list of groups.  inside the loop #}
{# "group" will be the group name and "hosts" will be the #}
{# list of hosts in that group. #}
{% for group,hosts in groups.items() %}

{# skip the "all" and "ungrouped" groups, which presumably #}
{# you don't want in your hosts file #}
{% if group not in ["ungrouped", "all"] %}

{# generate a hosts entry for each host, using the "loop.index" #}
{# variable and the group name to generate a unique hostname. #}
{% for host in hosts %}
{{host}} {{group}}{{loop.index}}
{% endfor %}

{% endif %}
{% endfor %}

The above is using {{host}} for the ip address, because this lets me tested it out on my system, but you would probably prefer {{hostvars[host]['ansible_default_ipv4']['address']}} in a real environment, unless you are positive you are always using ip addresses in your inventory.


In the inventory file:

  [myhosts] host_name=host1 host_name=host2

In the playbook.yaml

    - name: Update /etc/hosts from inventory
  lineinfile: dest=/etc/hosts regexp='.*{{item}}$' line='{{hostvars[item]['ansible_eth1']['ipv4']['address'] }}   {{hostvars[item]['host_name']}} ' state=present
  with_items: '{{groups.myhosts}}'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.