Manage Lines in Text File with Ansible lineinfile Module

Ansible lineinfile Module Example

Ansible’s lineinfile module allows you to manage lines in text files on remote hosts. This module is used when you need to ensure a specific line exists in a file or modify an existing line based on a pattern. It’s ideal for tasks like adding or updating configuration settings in text files. This module allows you to match, replace, or append lines without rewriting the entire file in a declarative and idempotent way.

In this guide, we’ll cover the basic usage of the Ansible lineinfile module with several practical examples.

Basic Syntax and Parameters

The basic syntax of the Ansible lineinfile module is as follows:

- name: Description of the task
  ansible.builtin.lineinfile:
    path: /path/to/file   
    line: 'text to add'   
    regexp: 'pattern'     
    state: present       
    insertafter: 'pattern' 
    insertbefore: 'pattern'

Here is the explanation of key parameters:

  • path: The path to the file that you want to modify.
  • line: The line to be inserted or modified in the file.
  • state: Ensures the line is present (present, default) or absent (absent).
  • regexp: A regular expression to match lines in the file.
  • insertafter: Specifies where to insert the line relative to lines matching a pattern.
  • insertbefore: Specifies where to insert the line relative to lines matching a pattern.
  • create: If the file does not exist, this parameter creates it.

Example 1 – Ensure a Configuration Setting is Present

Suppose you have a configuration file for a web server, /etc/nginx/nginx.conf, and you want to modify worker_connections setting to 1024.

The following playbook ensures that the line “worker_connections 1024″ is present in /etc/nginx/nginx.conf. If the file does not exist, it will be created. This ensures that the configuration setting is consistently applied.

- name: Ensure a configuration setting is present
  hosts: all
  tasks:
    - name: Add or update the worker_connections setting
      ansible.builtin.lineinfile:
        path: /etc/nginx/nginx.conf
        line: 'worker_connections 1024;'
        create: yes

Example 2 – Comment Out a Line in a Configuration File

You might need to disable a feature in a configuration file without deleting the line. For example, you might comment out a debug setting in an application configuration file so it does not log additional information.

The following playbook finds the line starting with debug=true and comments it out by prepending it with #. The regexp parameter identifies the specific line, and backrefs: yes ensures that the original line’s matching portion is included in the replacement.

- name: Comment out a line in a configuration file
  hosts: all
  tasks:
    - name: Comment out the debug setting
      ansible.builtin.lineinfile:
        path: /etc/myapp/config.conf
        regexp: '^debug=true'
        line: '#debug=true'
        backrefs: yes

Example 3 – Replace a Line Matching a Pattern

If you have a configuration file where the IP address of a server needs to be updated, you can use lineinfile to replace the old IP address with a new one. For example, updating server_ip in a configuration file to point to a new server.

This playbook searches for any line starting with server_ip= and replaces it with server_ip=192.168.1.100.

- name: Replace a line matching a pattern
  hosts: all
  tasks:
    - name: Update the server IP address
      ansible.builtin.lineinfile:
        path: /etc/myapp/config.conf
        regexp: '^server_ip=.*'
        line: 'server_ip=192.168.1.100'

Example 4 – Remove a Line Matching a Pattern

If you need to remove deprecated settings from a configuration file, such as removing an old logging level configuration that is no longer used.

This playbook removes the line that starts with log_level=debug from /etc/myapp/config.conf.

- name: Remove a line matching a pattern
  hosts: all
  tasks:
    - name: Remove the deprecated logging level line
      ansible.builtin.lineinfile:
        path: /etc/myapp/config.conf
        regexp: '^log_level=debug'
        state: absent

Example 5 – Insert a Line After a Specific Line

You might need to add a new setting in a configuration file immediately after an existing line. For example, adding max_connections right after server_name in an application configuration.

Here is an example playbook that inserts the line max_connections=100 immediately after the line that starts with server_name. The insertafter parameter specifies the pattern to match the line after which the new line should be inserted.

- name: Insert a line after a specific line
  hosts: all
  tasks:
    - name: Add max_connections setting after server_name
      ansible.builtin.lineinfile:
        path: /etc/myapp/config.conf
        line: 'max_connections=100'
        insertafter: '^server_name'

Example 6 – Ensure a Line is Only Present Once

To avoid duplication of configuration settings, you might want to ensure that a specific line, like enable_feature=true, appears only once in a configuration file.

This playbook ensures that enable_feature=true is present only once in /etc/myapp/config.conf. It also uses the validate option to check for duplicates.

- name: Ensure a line is only present once
  hosts: all
  tasks:
    - name: Ensure enable_feature is present only once
      ansible.builtin.lineinfile:
        path: /etc/myapp/config.conf
        line: 'enable_feature=true'
        create: yes
        state: present
        validate: 'grep -q ^enable_feature /etc/myapp/config.conf'

Example 7 – Add Multiple Lines Based on a Pattern

When setting up a new application, you might need to add multiple configuration lines at once.

The following playbook adds multiple lines to /etc/myapp/config.conf using a list of items. Each item in the list is added to the file, ensuring that multiple settings are configured at once.

- name: Add multiple lines based on a pattern
  hosts: all
  tasks:
    - name: Add multiple configuration lines
      ansible.builtin.lineinfile:
        path: /etc/myapp/config.conf
        line: "{{ item }}"
        with_items:
          - 'logging_level=info'
          - 'timeout=30'
        create: yes

Conclusion

The Ansible lineinfile module is a handy tool for managing text file configurations across multiple systems. By leveraging its ability to add, modify, or delete lines based on patterns, you can ensure consistent and correct configurations. The practical examples demonstrate common use cases for this module, making it easier to implement and manage configuration settings effectively.

FAQs

1. What is the Ansible lineinfile module used for?

The lineinfile module is used to add, modify, or remove lines in a text file.

2. Can the lineinfile module match and modify existing lines?

Yes, you can use the regexp parameter to match existing lines and the line parameter to specify the modification.

3. How do I remove a line from a file using the lineinfile module?

Use lineinfile with the state: absent parameter and a regexp to match the line you want to remove.

4. Is the lineinfile module idempotent?

Yes, the lineinfile module is idempotent, meaning it will only make changes if the desired state is not already present.

About Hitesh Jethva

I am Hitesh Jethva Founder and Author at LinuxBuz.com. I felt in love with Linux when i was started to learn Linux. I am a fan of open source technology and have more than 15+ years of experience in Linux and Open Source technologies.

View all posts by Hitesh Jethva

Leave a Reply

Your email address will not be published. Required fields are marked *