# Add ansible\_host= to /etc/hosts

**URL:** <https://forum.ansible.com/t/add-ansible-host-to-etc-hosts/25000>\
**Category:** Ansible Project\
**Created:** [July 17, 2017, 2:02am UTC](https://forum.ansible.com/t/add-ansible-host-to-etc-hosts/25000 "2017-07-17T02:02:33Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![John\_Favorite](https://avatars.discourse-cdn.com/v4/letter/j/ba9def/32.png) [@John\_Favorite](https://forum.ansible.com/u/John_Favorite)\
**Post date:** [July 17, 2017, 2:02am UTC](https://forum.ansible.com/t/add-ansible-host-to-etc-hosts/25000/1 "2017-07-17T02:02:33Z")

</div>

Hi, I am having issues getting proper /etc/hosts entries when I specify ansible\_host= in my inventory file. I have two task; first behaves as expected; second chokes with no variable ansible\_host defined error. Any help or pointers would be much appreciated.

tasks:

> ```auto
> - name: Build hosts file
> lineinfile: dest=/etc/hosts regexp='.*{{ item }}$' line="{{ hostvars[item].ansible_default_ipv4.address }} {{ item }}" state=present
> when: hostvars[item].ansible_default_ipv4 is defined
> with_items: "{{ groups['all'] }}"
> 
> - name: Add aliases for hosts excluded in playbook to hosts file
> lineinfile: dest=/etc/hosts regexp='.*{{ item }}$' line="{{ hostvars[hostvars[item].ansible_host].ansible_default_ipv4.address }} {{ item }}" state=present
> when: hostvars[item].ansible_default_ipv4 is not defined
> with_items: "{{ groups['all'] }}"
> 
> ```

inventory:

> [jenkins]  
> jenkins  
> [logstash]  
> logstash1 ansible\_host=web1  
> logstash2 ansible\_host=web2  
> logstash3 ansible\_host=web3  
> [web]  
> web1  
> web2  
> web3

```auto

```
