Ansible lineinfile Module: A Comprehensive Guide

In a system administration or DevOps toolkit, the ability to manipulate files is fundamental. Ansible offers a powerful module called lineinfile to perform such tasks. This module is specifically designed to ensure that a particular line is present or replaced in a file using a back-referenced regular expression. This blog post is aimed to provide a comprehensive overview of the lineinfile module and its usage.

Getting to Know the lineinfile Module

Ansible’s lineinfile module is a versatile tool used to ensure a certain line is in a text file. It can either add the line if it does not exist or replace an existing line using a regular expression. A core feature of this module is its idempotency, meaning that whether it’s run once or many times over, the result will always be the same.

Parameters of the lineinfile Module

The lineinfile module accepts several parameters that provide flexibility for various use-cases:

  • path (required): The file to modify.
  • line (required): The line to insert/replace into the file. If the regexp parameter is also provided, this replaces the matched line.
  • regexp: The regular expression to look for in every line of the file.
  • backrefs: This allows the module to replace a matched line using backreferences.
  • insertafter: Used when the line should be inserted after a certain place in the existing content.
  • insertbefore: Used when the line should be inserted before a certain place in the existing content.
  • create: Used to create a file if it does not already exist.
  • state: This parameter sets whether the line should be there or not. It can be absent or present.
  • validate: Validation to run before copying into place.

Parameter Examples

Real-World Examples of lineinfile Module Usage

The lineinfile module has a wide range of applications:

  1. Updating Configuration Files: You can add or replace lines in configuration files.
  1. Editing /etc/hosts File: Adding a new host to the /etc/hosts file is straightforward.
  1. Replacing Patterns: If you need to replace a particular pattern in a file, lineinfile is the module to use.


Ansible’s lineinfile module is a convenient and powerful way to handle text file contents. With its range of parameters and the ability to handle idempotency, it is an essential module in the Ansible playbook.