Automating the process of updating the IP address and netmask values in the network configuration file of multiple remote hosts can be a time-consuming and tedious task. However, with Ansible, it's possible to automate this process and save time and effort.
Ansible is an open-source automation tool that allows users to automate IT infrastructure tasks, including configuration management, application deployment, and orchestration. One of the key features of Ansible is its ability to manage multiple remote hosts simultaneously, making it an ideal choice for managing large-scale IT infrastructure.
In this article, we will explore how to use Ansible to automate the process of updating the IP address and netmask values in the network configuration file of remote hosts.
Ansible module lineinfile
Today we're talking about the Ansible module lineinfile.
The full name is ansible.builtin.lineinfile, which means that is part of the collection of modules "builtin" with ansible and shipped with it.
It's a module pretty stable and out for years and it supports a large variety of operating systems.
You are able to insert, update and remove a single line of text in a file.
Main Parameters
- path _string_ - file path
- line _string_ - text
- insertafter/insertbefore _string_ - EOF/regular expression
- validate _string_ - validation command
- create _boolean_ - create if not exist
- state _string_ - present/absent
- owner/group/mode - permission
- setype/seuser/selevel - SELinux
This module has some parameters to perform any tasks.
The only required is "path", where you specify the filesystem path of the file you're going to edit.
"line" is the line of text we would like to insert in the file, easy!
By default, the text is going to be inserted at the end of the file, but we could personalize it in a specific position with "insertafter" or "insertbefore".
If there is any tool to validate the file we could specify it in the validate parameter, very useful for configuration files.
If the file does not exist we could also "create" it!
Usually, we would like to insert a text line but we could also remove using state in conjunction with parameter absent.
Let me also highlight that we could also specify some permissions or SELinux property.
Links
- [ansible.builtin.lineinfile](https://docs.ansible.com/ansible/latest/collections/ansible/builtin/lineinfile_module.html)
Code
This Ansible playbook changes the IP address and netmask of a remote host by updating the network configuration file.
The hosts field specifies that this playbook should run on all hosts. The become field is set to true, which means that the playbook will run with elevated privileges (i.e. as a superuser).
The vars field sets two variables, new_ip_address and netmask, to the desired IP address and netmask values.
The tasks field contains two tasks. The first task uses the ansible.builtin.lineinfile module to update the network configuration file (`/etc/ne