Dynamic hosts file with Ansible

ansible with vagrant

Hosts file

hosts file consist a map of some hostname to IP Addresses before DNS can be referenced, plain text, leftmost column is the IP address. The next column is the host’s name.  Some people only using DNS to manage their hosts, others using both (DNS and hosts file), you can choose your own flavor. DNS is run but it could fail at any time, best practice, it’s always good to rely on /etc/hosts.

If i can recall, before deploying with ansible or any other orchestration engine, we do lot of stuff using manual bash scripting, ssh passwordless and ‘for loop’ to repeat the script for updating the host files. Now dynamic updating the host file for hundred or thousand machine much easier with ansible.

Inventory file

[controller]
controller-01

[compute]
compute-01

Template file

# {{ ansible_managed }}

127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 {{ ansible_hostname }}
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 {{ ansible_hostname }}

# Openstack Environment
{% for item in groups['all'] %}
 {{ hostvars[item]['ansible_enp0s10']['ipv4']['address'] }} {{ hostvars[item]['ansible_hostname'] }}
{% endfor %}

Yaml file

---
- hosts: all
  become: true
  become_user: root

tasks:

- name: Build hosts file
  template:
  src=/home/vagrant/openstack/files/hosts.j2
  dest=/etc/hosts
  mode=0644
  owner=root
  group=root
  backup=yes

Fire the command

$ ansible --version
ansible 2.3.1.0
 
$ ansible-playbook hosts-files-generate.yml

Result on target hosts

$ cat /etc/hosts
# Ansible managed

127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 compute-01
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 compute-01

# Openstack Environment
 192.168.100.203 compute-01
 192.168.100.200 controller-01

Note:

– You can get the information about hostvars[item], using ansible <hostname> -m setup, choose your own flavor, following is the output

[ ... ]
 "ansible_enp0s10": {
            "active": true,
            "device": "enp0s10",
            "features": {
                "busy_poll": "off [fixed]",
                "fcoe_mtu": "off [fixed]",
                "generic_receive_offload": "on",
                "generic_segmentation_offload": "on",
[ ... ]
 },
            "ipv4": {
                "address": "192.168.100.200",
                "broadcast": "192.168.100.255",
                "netmask": "255.255.255.0",
                "network": "192.168.100.0"
            },
[ ... ]
 "ansible_hostname": "controller-01",
 "ansible_interfaces": [
 "lo",
 "enp0s10",
 "enp0s3",
 "enp0s8",
 "enp0s9"
 ],
 [ ... ]