Day 18: Ansible playbook adding a line to a file
Ansible, the name of resounding legend.
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 www.google.com PING www.google.com (22.214.171.124) 56(84) bytes of data. 64 bytes from mba01s08-in-f4.1e100.net (126.96.36.199): icmp_seq=1 ttl=117 time=44.5 ms
Now, as we see, google is resolving with IP address 188.8.131.52
Say, I’m living in france and I want to resolve it to google.fr.
- Then I need to check the IP of google.fr, just to see if it’s a different IP
[email protected]:~$ ping www.google.fr PING www.google.fr (184.108.40.206) 56(84) bytes of data. 64 bytes from mba01s08-in-f3.1e100.net (220.127.116.11): icmp_seq=1 ttl=117 time=42.2 ms
- I would add the following line in /etc/hosts in the format: IP[Space or tab]FQDN
What i’m doing is forcing google.com to resolve to google.fr
- Now when i type in: www.google.com, I’m redirected to google.fr transparently.
Changed on 1 server
On multiple servers, we’ll use ansible.
# Playbook name: add_googlefr.yaml hosts: MyFrontend - name: Add google.fr to /etc/hosts lineinfile: path: /etc/hosts line: '18.104.22.168 www.google.fr' 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’