---
title: "How to Use the Ansible lineinfile Module to Manage Text Files"
description: "Learn how to make changes to text files using the Ansible lineinfile module in this step-by-step tutorial."
canonical: "https://adamtheautomator.com/ansible-lineinfile/"
---

# How to Use the Ansible lineinfile Module to Manage Text Files

> Learn how to make changes to text files using the Ansible lineinfile module in this step-by-step tutorial.

Source: https://adamtheautomator.com/ansible-lineinfile/

---

ATA Learning

Tap to hide

[

ATA Learning

](/)

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Search for:  

*   [](https://twitter.com/adbertram)
*   [](https://github.com/Adam-the-Automator)
*   [](https://www.linkedin.com/company/adam-the-automator-llc)
*   [](/feed/)

![How to Use the Ansible lineinfile Module to Manage Text Files](https://adamtheautomator.com/wp-content/uploads/2021/09/How-to-Use-Ansibles-lineinfile-Module-to-Manage-Text-Files.jpg)

# How to Use the Ansible lineinfile Module to Manage Text Files

[![](https://secure.gravatar.com/avatar/2beb65fca997135120ed98dc6a2e57dcdf1a7d7d2f5ff687b5d91dc7ccd7a6b5?s=192&d=mm&r=g)Sagar](https://adamtheautomator.com/author/shanky-mendiratta/)1 October 20215 min. read

Categories: [IT Ops](/category/it-ops/)

Tags:[Ansible](/tag/ansible/)

Table of Contents

*   [Prerequisites](#prerequisites)
*   [Modifying a Text File with the Ansible lineinfile module.](#modifying-a-text-file-with-the-ansible-lineinfile-module)
*   [Modifying Multiple Text Files Within a Playbook](#modifying-multiple-text-files-within-a-playbook)
*   [Conclusion](#conclusion)

Ansible is a widely used automation tool that can manage hundreds of nodes in one go. Ansible has lots of great features, and one of them is its ability to manage a single line within a file on remote nodes using the [Ansible lineinfile module](https://docs.ansible.com/ansible/latest/collections/ansible/builtin/lineinfile_module.html).

The Ansible lineinfile module is a module that performs various actions on a single line on a file, such as replacing a line, updating a line, or adding a particular line.

In this tutorial, you’re going to learn what the Ansible lineinfile module is, how it works, and how to use it to manage text files.

## Prerequisites

This post will be a step-by-step tutorial on the Ansible lineinfile module. If you’d like to follow along, be sure you have the following in place:

*   An [Ansible controller host](https://docs.ansible.com/ansible/latest/installation_guide/index.html) – This tutorial will be using Ansible v2.9.24 on an Ubuntu 18.04.5 LTS machine.

Related:[Guide: How to Setup Ansible (Ubuntu, RHEL, CentOS, macOS)](https://adamtheautomator.com/install-ansible/)

*   A remote computer to run commands. You’ll need an [inventory file](https://docs.ansible.com/ansible/latest/user_guide/intro_inventory.html) set up and one or more hosts already configured to run Ansible command and playbooks on. The remote Linux computer will be called _myserver,_ and the tutorial will use an inventory group called _web_.
    
*   Apache should already be installed on the remote computer if you’d like to follow along with the tutorial exactly.
    

Related:[How to Set up an Apache Docker Container](https://adamtheautomator.com/apache-docker/)

## Modifying a Text File with the Ansible lineinfile module.

Let’s begin this tutorial by running Ansible lineinfile module using the ad hoc commands. Ad hoc commands are a quick way to test or run a single command on a remote host.

Log onto your Ansible controller and run the following command. This command uses the lineinfile module (`-m`) to connect to the web machine and pass an argument (`-a`) which is the command to execute.

In this instance, the lineinfile module updates the localhost entry by mapping IP-address `127.0.0.1` with `myapache` in the/etc/hosts file. By mapping the `127.0.0.1` with `myapache` allows you to navigate to the apache test page locally on HTTP://myapache:80

*   `path` denotes the file location.
*   `regexp` finds the regular expression, if any, in the file and updates with `127.0.0.1 myapache` specified in the `line` parameter.
*   [–become](https://docs.ansible.com/ansible/latest/user_guide/become.html#become-command-line-options) flag allows you to run the command as a privileged user.
*   The `web` is the inventory group that is a collection of all servers.
*   `ansible.builtin.lineinfile` or simply lineinfile is the module name.

```bash
ansible web -m ansible.builtin.lineinfile -a "path=/etc/hosts regexp='^127\.0\.0\.1'  line='127.0.0.1 myapache' state=present" --become
```

After you execute the command, you should see a **CHANGED** message that confirms that the line has been successfully updated on the remote host.

![Running the ad hoc command with ansible lineinfile module](https://adamtheautomator.com/wp-content/uploads/2021/09/image-263.png)

Running the ad hoc command with ansible lineinfile module

Log in to the remote node using an SSH client and verify if the _/etc/hosts_ file has been updated with the new value using the `cat` command.

As you can see below, the localhost entry has successfully been updated with `127.0.0.1 myapache` on the remote machine.

![Verifying the host file on remote machine](https://adamtheautomator.com/wp-content/uploads/2021/09/image-264.png)

Verifying the host file on remote machine

## Modifying Multiple Text Files Within a Playbook

Working with single ad hoc command to manage lines on a remote machine may be OK, but it’s going to be difficult if you have lines in multiple files or multiple lines in a file to manage. Instead of using ad-hoc commands, consider using Ansible lineinfile module within the playbook using the [ansible-playbook](https://docs.ansible.com/ansible/latest/user_guide/playbooks.html) command.

Related:[Creating and Running Ansible Windows Playbooks](https://adamtheautomator.com/ansible-windows/#Creating_and_Running_Ansible_Windows_Playbooks)

Now, let’s learn how to use Ansible lineinfile module within the playbook and modify few lines.

Assuming you’re already logged into Ansible controller host:

1\. Create a directory called _ansible\_lineinfile\_module\_demo_ in your home directory. This directory will contain the [playbook](https://www.redhat.com/en/topics/automation/what-is-an-ansible-playbook#:~:text=An%20Ansible%C2%AE%20playbook%20is,make%20up%20an%20Ansible%20inventory) you’ll use to invoke the lineinfile module.

```yaml
mkdir ~/ansible_lineinfile_module_demo
cd ~/ansible_lineinfile_module_demo
```

2\. Create another file called _my\_playbook.yml_ in the _~/ansible\_lineinfile\_module\_demo_ directory and paste in the following YAML playbook contents. This playbook has multiple tasks that use Ansible `lineinefile` module to manage lines of different config files for Apache on the remote machine.

The playbook below contains the following tasks:

1\. Checks if `ADMIN` is present in _/etc/sudoers_ file; if not, the task adds it.

2\. Ensures the Apache default is listening on 8080 within the _/etc/apache2/ports.conf_ file; if it finds any other port lineinfile module updates it to port `8080`. Similarly under _/etc/apache2/apache2.conf_ file, it updates the `MaxKeepAliveRequests` to 1000 and `KeepAliveTimeout` to 100.

3\. Adds the line with the text “Hello This is my Apache Page” at the end of the `index.html` page on the remotes server under the _/var/www/html_ directory.

> _Ansible playbooks are written in YAML. To learn more about YAML, [click here](https://docs.ansible.com/ansible/latest/reference_appendices/YAMLSyntax.html#:~:text=This%20page%20provides%20a%20basic,formats%20like%20XML%20or%20JSON)_

```yaml
---
- name: Ansible lineinfile module example
# Defining the remote server where Ansible lineinfile module will take effect
  hosts: web
  remote_user: ubuntu   # Using Remote host as ubuntu
  become: true
  tasks:

# (Task-1) Checking the Sudoers file if Admins are allowed to perform all operations 
    - name: Validate the sudoers file before saving
      ansible.builtin.lineinfile:
         path: /etc/sudoers
         state: present
         regexp: '^%ADMIN ALL='
         line: '%ADMIN ALL=(ALL) NOPASSWD: ALL'

# (Task-2) Updating the Apache Default Port to 8080 
    - name: Ensure the default Apache port is 8080
      ansible.builtin.lineinfile:
         path: /etc/apache2/ports.conf
         regexp: '^Listen '
         insertafter: '^#Listen '
         line: Listen 8080

# (Task-3) Adding the Line at the end of the html page Hello This is my Apache Page
    - name: Add a line to a file if the file does not exist
      ansible.builtin.lineinfile:
         path: /var/www/html/index.html
         line: Hello This is my Apache Page
         create: yes

# (Task-4) Checking the Sudoers file if Admins are allowed to perform all operations 
    - name: Ensure MaxKeepAliveRequests is set to greater than 100
      ansible.builtin.lineinfile:
         path: /etc/apache2/apache2.conf
         regexp: '^MaxKeepAliveRequests'
         line: MaxKeepAliveRequests=1000

# (Task-5) Checking the Sudoers file if Admins are allowed to perform all operations 
    - name: Ensure KeepAliveTimeout is set to greater than 50
      ansible.builtin.lineinfile:
         path: /etc/apache2/apache2.conf
         regexp: '^KeepAliveTimeout'
         line: KeepAliveTimeout=100
```

3\. Now, invoke the playbook and execute the tasks using the `ansible-playbook` command to add or update all the lines defined in the playbook on the remote host.

```bash
ansible-playbook my_playbook.yml 
```

![Invoking the ansible playbook ](https://adamtheautomator.com/wp-content/uploads/2021/09/image-265.png)

Invoking the ansible playbook

Below, you can see that the **TASK** has a status of **changed,** meaning the remote host wasn’t in the proper state and was modified to run the command. For that **TASK** which has OK status, shows they don’t require any changes.

4\. Next, SSH into the remote host using your favorite SSH client.

5\. Finally, verify if all the lines defined in the _my\_playbook.yml_ are updated or added on the remote host using the `cat` command.

```bash
# To verify if admin is present with full privileges and if not add it
cat /etc/sudoers
# To verify the MaxKeepAliveRequests and KeepAliveTimeout have been updated to 1000 and 100, respectively. 
cat /etc/apache2/apache.config | grep Alive
# To verify if Apache is listening on Port 8080
cat /etc/apache2/ports.config
```

The below screenshot confirms that the `admin` is already added in the sudoers file.

![Verifying the sudoers file ](https://adamtheautomator.com/wp-content/uploads/2021/09/image-266.png)

Verifying the sudoers file

Again, the below screenshot confirms that the apache is listening on `Port 8080` by default.

![Verifying the ports for in the config file ](https://adamtheautomator.com/wp-content/uploads/2021/09/image-267.png)

Verifying the ports for in the config file

Finally, verify the `MaxKeepAliveRequests` and `KeepAliveTimeout` if they have been updated to 1000 and 100, respectively.

![Verifying the MaxKeepAliveRequests and KeepAliveTimeout in the config file](https://adamtheautomator.com/wp-content/uploads/2021/09/image-268.png)

Verifying the `MaxKeepAliveRequests` and `KeepAliveTimeout` in the config file

## Conclusion

The Ansible lineinfile module is a great way to modify text files on remote hosts. The module provides a great way to add, remove and modify lines in text files within your playbooks.

What other use cases do you see would benefit from the Ansible lineinfile module?

Share this article

[Share on X](https://twitter.com/intent/tweet?url=https%3A%2F%2Fadamtheautomator.com%2Fansible-lineinfile%2F&text=How%20to%20Use%20the%20Ansible%20lineinfile%20Module%20to%20Manage%20Text%20Files)[Share on Facebook](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fadamtheautomator.com%2Fansible-lineinfile%2F)[Share on LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fadamtheautomator.com%2Fansible-lineinfile%2F)

## Related Posts

![](https://adamtheautomator.com/wp-content/uploads/2022/05/Manage-Playbooks-and-Inventories-Easily-with-Ansible-Tower.jpg)

### [Ansible Tower Basics for Easy Playbook and Inventory Management](/ansible-tower/)

Master Ansible Tower for effortless playbook and inventory management, elevating your automation skills to the next level with practical, user-friendly strategies.

![](https://adamtheautomator.com/wp-content/uploads/2022/08/How-to-Manage-Services-With-the-Ansible-Service-Module.jpg)

### [How to Manage Services With the Ansible Service Module](/ansible-service/)

Learn how to manage, control, and integrate OS services with the Ansible Service module in this ATA Learning tutorial!

![](https://adamtheautomator.com/wp-content/uploads/2022/05/Secure-Your-Secrets-With-Ansible-Vault.jpg)

### [Secure Your Secrets With Ansible Vault](/ansible-vault/)

Make sure your playbook and environment secrets are secure with the Ansible Vault and level up your playbooks in this ATA Learning tutorial!

## Categories

*   [IT Ops](/category/it-ops/)
*   [Cloud](/category/cloud/)
*   [DevOps](/category/devops/)
*   [Home Ops](/category/home-ops/)
*   [Information Security](/category/infosec/)
*   [Software Development](/category/software-development/)

## Site

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Copyright 2026© ATA Learning | [Privacy Policy](/privacy/)
