Day 18: Ansible playbook adding a line to a file


ansible logo

Ansible, the name of resounding legend.

Problem ?

There are many use cases like this where you would need to add a line to a file.

It could be as simple as adding a new host in the /etc/hosts of multiple servers to allow for DNS resolution using a particular IP.

It could also be about whitelisting an IP address (adding it to the whitelisting plain text file).

Adding a line to /etc/hosts

In this scenario, we want to add a line to the /etc/hosts file

Skip this part if you know the use of /etc/hosts

The /etc/hosts file is a plaintext-file on standard GNU/Linux OS.

Its purpose is to allow for DNS resolution of the host.

It has priority over DNS servers.

[email protected]:~$ ping
PING ( 56(84) bytes of data.
64 bytes from ( icmp_seq=1 ttl=117 time=44.5 ms

Now, as we see, google is resolving with IP address

Say, I’m living in france and I want to resolve it to

  1. Then I need to check the IP of, just to see if it’s a different IP
     [email protected]:~$ ping
     PING ( 56(84) bytes of data.
     64 bytes from ( icmp_seq=1 ttl=117 time=42.2 ms
  2. I would add the following line in /etc/hosts in the format: IP[Space or tab]FQDN
     [email protected]:~$ vim /etc/hosts
     [email protected]:~$ tail -n3 /etc/hosts
     ff02::2 ip6-allrouters

    What i’m doing is forcing to resolve to

  3. Now when i type in:, I’m redirected to transparently. googlecom.png

Changed on 1 server

OK, easy.

On multiple servers, we’ll use ansible.

# Playbook name: add_googlefr.yaml
hosts: MyFrontend
- name: Add to /etc/hosts
    path: /etc/hosts
    line: ''
    state: present
    backup: yes

Why use this method?

  • It adds a line at the end of the text file

  • It doesn’t create duplicates if line is present.

  • Rollback: Remove the line by replacing the state: present with ‘absent’


Ansible logo


Written on January 18, 2021