Skip to content

Instantly share code, notes, and snippets.

@glennswest
Created April 7, 2017 04:57
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save glennswest/6e43aa88f3de0a0cf4ecf00749a91fa1 to your computer and use it in GitHub Desktop.
Save glennswest/6e43aa88f3de0a0cf4ecf00749a91fa1 to your computer and use it in GitHub Desktop.
Ansible automatically create /etc/hosts file for all host - to give nice short names using dnsmasq
---
- hosts: all
tasks: []
- hosts: all
gather_facts: True
tasks:
- name: check connection
ping:
- name: setup
setup:
- name: "Build hosts file"
lineinfile: dest=/etc/hosts
state=present
dest=/etc/hosts
regexp='.*{{ item }}$' line="{{ hostvars[item].ansible_default_ipv4.address }} {{item}}"
when: hostvars[item].ansible_default_ipv4.address is defined
with_items: "{{ groups['all'] }}"
- hosts: localhost
gather_facts: True
tasks:
- name: check connection
ping:
- name: setup
setup:
- name: "Build hosts file"
lineinfile: dest=/etc/hosts
state=present
dest=/etc/hosts
regexp='.*{{ item }}$' line="{{ hostvars[item].ansible_default_ipv4.address }} {{item}}"
when: hostvars[item].ansible_default_ipv4.address is defined
with_items: "{{ groups['all'] }}"
@falkolab
Copy link

falkolab commented Jun 1, 2019

What if you remove one host from inventory? How are you going to cleanup removed hosts?

@glennswest
Copy link
Author

glennswest commented Jun 1, 2019 via email

@Tecquilka
Copy link

Tecquilka commented Sep 20, 2019

Little-bit nasty solution, but it works... (but slow as hell, version: Ansible 2.5.1)

- when: hostvars[item].ansible_default_ipv4.address is defined
+ when: (hostvars[item] is defined) and (hostvars[item]['ansible_default_ipv4'] is defined) and (hostvars[item]['ansible_default_ipv4']['address'] is defined)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment