Ansible – Updating Multiple Pis Hosts Files (Raspberry Pi)

Using Ansible to change the host file on multiple Pis

In my “test” environment I currently have 4 Raspberry Pis that all have an IP address reservation on the network but there is no local DNS. Without DNS the devices cannot find each other by device name, i.e. they cannot resolve the names to IP addresses. This could be resolved by making one of the Raspberry Pis into a DNS server, however there is also a quicker solution.

Each Pi has a hosts file that is stored under /etc/, this hosts file contains the local loop back address / host name and can also be used to store the IP addresses of other hosts (Raspberry Pis).

I’m going to use Ansible (running on my Raspberry Pi 3) to update the hosts file on each of the other Raspberry Pis. My current set up looks like this:

  • pi3 – runs Ansible, IP
  • pi4  – part of the “Pi_Collection”, IP
  • pizero1 – part of the “Pi_Collection”, IP
  • pizero2 – part of the “Pi_Colleciton”, IP

Using one line of Ansible I can add the IP address and hostname of a device into the hosts files of all the Pis in the Pi_Collection:

ansible COLLECTION_NAME -m shell “echo ‘IP_ADDRESS    HOSTNAME’>> /etc/hosts” -b

for me this is:

ansible Pi_Collection -m shell -a “echo ‘    pi3’>> /etc/hosts” -b

I’ve used 4 spaces in between the ip address and the hostname, as this is roughly the same as a tab (see: tabs vs spaces for a little background on that).  -m tells Ansible that I am going to use a module (in this case shell) and -a tells Ansible that what follows is an ad-hoc command. “echo starts the command saying that I want to echo back what I’m about to type. ‘IP_ADDRESS    HOSTNAME’ is what I want to echo back and >> /etc/hosts” says I want to echo the line back into the hosts file. -b tells Ansible to “become” and as I’ve not identified a user it uses the default which has privilege escalation.

ansible COLLECTION_NAME -m shell -a “cat /etc/hosts”

Can then be used to check what is in each devices hosts file.

Using Ansible to change the host file on multiple Pis
Using Ansible to change the host file on multiple Pis