Ansible Lineinfile Tutorial

Paul Hill

April 3, 2024 • 4 min read

    Embarking on an Ansible journey introduces you to a myriad of modules, each designed to simplify specific tasks within your infrastructure management workflow. Among these tools, the lineinfile module holds a unique place. This guide aims to illuminate the various functionalities of the lineinfile module, providing practical examples to enhance your playbook’s capabilities.

    If you want to take your Ansible skills to the next level, then you should defnitely enroll in our Ansible course! Click the course box below to get started!

    Course: Ansible for Complete Beginners

    What is Ansible? Ansible is an easy to learn automation tool that streamlines complex IT tasks with …

    58 Lessons
    6 Quizzes
    8 Labs
    18.5 Hr

    Lineinfile Module

    At its core, the lineinfile module is Ansible’s Swiss Army knife for text manipulation, adept at adding, removing, or modifying lines in configuration files across your hosts. This module’s beauty lies in its precision, allowing you to target specific lines with the finesse of a surgeon, thanks to its support for regular expressions.

    The module is versatile, equipped with a host of parameters for tailoring its operation:

    • path: The target file on your remote host.
    • line: The content you wish to manage within the file.
    • state: Defines what action to take on the line, with options like present, absent, before, or after.
    • regexp: A regular expression to find a line in the file.
    • backrefs, insertafter, insertbefore: Advanced options for refined text manipulation.
    • create: Decides if a non-existent file should be brought into existence.

    Ensuring idempotency, the lineinfile module guarantees that operations are only performed when necessary, maintaining your system’s desired state without redundancy.

    Practical Applications

    Let’s explore some common use cases:

    Adding a Line

    To insert a new line, specify the line content and the file path, as shown below:

    - hosts: all
      tasks:
        - name: Add a new line
          lineinfile:
            path: /path/to/file
            line: 'Your new line here'
            state: present
            create: true

    Removing a Line

    To eliminate a specific line, use the regexp parameter to match and the state set to absent.

    - hosts: all
      tasks:
        - name: Remove a specific line
          lineinfile:
            path: /path/to/file
            regexp: 'Line to remove'
            state: absent

    Replacing a Line

    Modify existing lines by combining the regexp parameter with the new line content.

    - hosts: all
      tasks:
        - name: Replace an existing line
          lineinfile:
            path: /path/to/file
            regexp: 'Line to replace'
            line: 'New line content'

    Inserting After a Match

    This will insert a line after a matched pattern:

    - hosts: all
      tasks:
        - name: Insert a line after a specific pattern
          lineinfile:
            path: /path/to/your/file
            line: 'This is the newly added line.'
            insertafter: '^A pattern to match$'
    

    Inserting Before a Match

    Insert a line of code before a match:

    - hosts: all
      tasks:
        - name: Insert a line before a specific pattern
          lineinfile:
            path: /path/to/your/file
            line: 'This line goes before the pattern.'
            insertbefore: '^Pattern$'
    

    Insert Multiple Single Lines

    Insert multiple lines of code in a file:

    - hosts: all
      tasks:
        - name: Add multiple lines ensuring idempotency
          lineinfile:
            path: /path/to/your/file
            line: "{{ item.line }}"
            regexp: "{{ item.regexp }}"
            state: present
          loop:
            - { line: 'Line 1 to be added', regexp: '^Exact match of Line 1$' }
            - { line: 'Line 2 to be added', regexp: '^Exact match of Line 2$' }
    

    Set File Permissions with Lineinfile

    You can also specify the file permissions when using lineinfile:

    - hosts: all
      tasks:
        - name: Modify a line and set file permissions
          lineinfile:
            path: /path/to/your/file
            line: 'This line adjusts permissions.'
            state: present
            mode: '0644'
    

    Backup for Safety: With the backup parameter, lineinfile ensures that you always have a fallback, creating backups of your files before any modification.

    Wrapping Up

    The lineinfile module stands as a testament to Ansible’s flexibility and power, offering a straightforward yet potent solution for managing file content across your infrastructure. Whether you’re a seasoned Ansible veteran or just starting, the lineinfile module is an invaluable asset in your automation toolkit.

    Further Learning

    Eager to deepen your Ansible knowledge? Consider enrolling in our comprehensive Ansible Basics Course, where hands-on exercises guide you through the fundamentals, equipping you with the skills to leverage Ansible’s full potential.

    We invite you to share your experiences and tips on using the Ansible lineinfile module in the comments below. Your insights can help enrich the learning journey for everyone.

    Join our Ansible Basics Course to embark on a hands-on exploration of Ansible fundamentals.

    Coding and AutomationDevOpsLinuxSystem Administrator

    Want to improve your IT skillset? Start with a free account and get access to our IT labs!

    Blogpostctadesktop

    Sign up free and start learning today!

    Practice on REAL servers, learn from our video lessons, interact with the Server Academy community!