Ansible Lineinfile Module Tutorial With Examples

When working with Ansible, you’ll sometimes be required to add, remove, or update a line within files stored in the hosts. Such a task requires one to search for a line in the file that matches a specified regular expression and then perform the specified action on that line. Ansible’s lineinfile module makes it possible to implement such tasks neatly and with ease.

In this blog, we use examples to demonstrate the different use case cases of the module.

Welcome to KodeKloud!

We are the #1 DevOps courses provider. Join us today to gain access to our free courses and labs and try sample lessons of all 65+ courses. No credit card required!

REGISTER

Ansible lineinfile Module

lineinfile is one of the most versatile modules in Ansible. You can use it to add, modify, remove, or replace a line or multiple lines in the host’s configuration files. You can also use it to create file backups or change file permissions and ownership.

It offers several parameters to customize its behavior:

  • path (required): Specifies the path to the file on the remote host where the modification needs to be made.
  • line (required): Defines the line to be added, replaced, or removed in the file.
  • state (optional): Determines the desired state of the line. Possible values are present (default), absent, before, or after.
  • regexp (optional): Specifies a regular expression pattern to search for in the file. The module performs actions on lines matching this pattern.
  • backrefs (optional): Enables the use of backreferences in regular expressions for replacement purposes.
  • insertafter/insertbefore (optional): Specifies a line before or after which the line should be inserted when the state is set to present.
  • insertafter_regex/insertbefore_regex (optional): Similar to insertafter/insertbefore, but using regular expressions to define the line.
  • create (optional): Determines whether to create the file if it doesn't exist. Set to yes or no (default).

The idempotent property of Ansible modules allows them to be used repeatedly without resulting in undesired side effects. In the case of the lineinfile module, it ensures that changes are only made when absolutely necessary, based on the parameters supplied and the file's present state.

Basic Usage of lineinfile

Let us see how to use the Ansible lineinfile module to add, delete and replace a line in a file.

Add a line

Using the lineinfile Module, you can add a new line to a file. You do this by providing the line argument and the file path. See the example below:

---
- hosts: all
  tasks:
  - name: create file and add line
    lineinfile:
      path: /home/ubuntu/demo.txt
      line: This is a new line
      state: present
      create: true

In the playbook above, the file "demo.txt" will be amended to include "This new line" in the example. The new line is added to the EOF, i.e., the end of the file. The line won't be concatenated if it already exists.

The create parameter has an optional setting. It tells the program that if the requested file is missing, a new one will be produced. The state's default value is present.

Remove a line

You can remove particular lines from a file using the lineinfile module. See the example below:

---
- hosts: all
  tasks:
    - name: Remove a line  
      lineinfile:  
        path: /home/ubuntu/demo.txt
        regexp: “Remove this line”
        state: absent  

Setting the "state" to absent and then giving the regexp parameter of a line will eliminate that specific line. This task will search for a line with the content “Remove this line” in the file and remove it if found.

Replace a Line in a File

The lineinfile module can also be used to replace specific lines in a file. To replace a line, you need to provide a regular expression pattern using the regexp parameter and the line parameter containing the new line.

---
- hosts: all  
  tasks: 
    - name: Replace a line  
      lineinfile:  
        path: /home/ubuntu/demo.conf
        regexp: ^AllowPassword
        line: AllowPasswords yes

In this example, lineinfile module will look for “AllowPassword” in the demo.conf file and replace it with “AllowPasswords yes” using the line parameter.

Change Multiple Lines

The lineinfile module also supports managing many lines at once. The tasks are guaranteed to be idempotent by Ansible, which means they will alter the file only when necessary depending on the current state of the file.

---
- hosts: all  
  tasks: 
    - name: Change multiple lines  
      lineinfile:  
        path: /home/ubuntu/demo.conf
        line: "{{ item.line }}"
        regexp: "{{ item.regexp }}"
      loop:
        - line: AllowPassword yes
          regexp: ^AllowPassword
        - line: PortForwarding yes
          regexp: ^PortForwarding

In this example, the lineinfile module will look for the “AllowPassword” and “PortForwarding” lines in demo.conf file and replace it with “AllowPasswords yes” and “PortForwarding yes”.

Insertafter and Insertbefore

The lineinfile module uses the "insertafter" parameter to specify a regular expression pattern or a line number, after which the new line should be inserted.

Here's an example of using the "lineinfile" module with the "insertafter" parameter:

---
- hosts: all
  tasks:
    - name: Insert a line after a specific pattern
      lineinfile:
        path: /home/ubuntu/file.txt
        line: "This is the new line"
        insertafter: "^Pattern to match"

In the above example, the "lineinfile" module is used to insert the line "This is the new line" after the line that matches the regular expression pattern "^Pattern to match" in the file “home/ubuntu/file.txt".

Alternatively, you can use the "insertafter" parameter with a line number instead of a regular expression pattern. Here's an example:

---
- hosts: all
  tasks:
    - name: Insert a line after a specific line number
      lineinfile:
        path: / home/ubuntu/file.txt
        line: "This is the new line"
        insertafter: 5

In this case, the "lineinfile" module will insert the line "This is the new line" after line number 5 in the file "/ home/ubuntu/file.txt".

The "lineinfile" module in Ansible also provides the "insertbefore" parameter, which allows you to insert a line before a specific pattern or line number in a file.

Advanced Options and Use Cases

Next, let us see how to use the Ansible lineinfile module for advanced use cases.

Setting File Permissions and Ownership

The lineinfile module allows you to set file permissions explicitly using the mode parameter. The mode parameter accepts the octal representation of file permissions, such as 0644 for read-write permissions for the owner and read-only permissions for others.

---
- hosts: all
  tasks:
  - name: Create a new file with permissions
    lineinfile:
      path: "/home/ubuntu/demo.txt"
      state: touch
      mode: 0644
      owner: ubuntu

In this example, the file specified in the path parameter will have its permissions set to 0644, allowing read-and-write access for the owner and read-only access for others.

Validate Changes

The lineinfile module provides a way to validate file content before making any modifications. By using the validate parameter, you can specify a script or command to check the file's content against specific rules. If the validation fails, the lineinfile task will not proceed with any modifications. Here's an example:

---
- hosts: all
  tasks:
   - name: Validate file content before modification
     lineinfile:
       path: /home/ubuntu/demo.txt
       line: 'new line'
       validate: "/home/ubuntu/validation_script.sh"

In this example, the lineinfile task executes the specified validation script (validation_script.sh) before making any modifications to the file.

Backup

Modifying files using the lineinfile module can introduce changes that may have unintended consequences. Therefore, it is crucial to create backups of files before making any modifications. The lineinfile module offers the backup parameter to automatically create backups of files. Here's an example:

---
- hosts: all
  tasks:
   - name: Modify file with backup
     lineinfile:
       path: /home/ubuntu/demo.txt
       line: 'this is new line'
       backup: yes

Conclusion

The lineinfile module combines the simplicity of plain text lines with the power and flexibility of regular expressions to allow for both simple and complex manipulations. Even after many years of use, you will find new ways to use this Ansible module. Hopefully, the examples in this Ansible tutorial on lineinfile will help you improve your playbooks.

Enroll in our Ansible Basics Course to learn Ansible basic fundamentals with easy-to-do hands-on exercises.