Ansible lineinfile Module: Add, Replace, Remove Lines in Files (Complete Guide)
By Luca Berton · Published 2024-01-01 · Category: database-automation
How to use Ansible lineinfile module to manage lines in configuration files. Add, replace, remove, and insert lines with regex. Complete guide with playbook examples.
Ansible lineinfile Module: Add, Replace, Remove Lines in Files (Complete Guide)
The ansible.builtin.lineinfile module ensures a specific line exists (or doesn't exist) in a file. It's ideal for managing individual settings in configuration files without templating the entire file.
Add a Line
If the line already exists, nothing changes (idempotent).
Replace a Line (Regex)
The regexp finds the existing line. The line parameter replaces it.
Remove a Line
Insert at Specific Position
After a Line
Before a Line
At Beginning or End
Set Permissions and Ownership
Create File if Missing
Validate Before Writing
Common Use Cases
Configure SSH Security
Manage /etc/hosts
Set Environment Variables
Manage Kernel Parameters
lineinfile vs replace vs template
| Module | Use When | |--------|----------| | lineinfile | Managing single lines (key=value settings) | | replace | Replacing text patterns across multiple lines | | template | Managing entire file content from a Jinja2 template | | blockinfile | Managing a block of multiple lines |
Backup Before Changes
FAQ
How do I add a line to a file in Ansible?
Use ansible.builtin.lineinfile with path and line parameters. The module adds the line at the end of the file if it doesn't already exist. Set create: true to create the file if missing.
How do I replace a line in Ansible?
Use regexp to match the existing line and line to specify the replacement: ansible.builtin.lineinfile: path=/etc/config regexp='^old_setting' line='new_setting=value'.
What is the difference between lineinfile and replace?
lineinfile manages a single line — ensuring it exists, replacing it, or removing it. replace does regex find-and-replace across the entire file and can handle multi-line patterns.
How do I insert a line after a specific line?
Use insertafter: 'regex_pattern' to place the new line after the first match. Use insertbefore: 'regex_pattern' for before. Use BOF/EOF for beginning/end of file.
Is lineinfile idempotent?
Yes. If the line already exists (matching either line or regexp), no changes are made. Running the same task multiple times produces the same result.
Conclusion
ansible.builtin.lineinfile is essential for managing configuration files line by line. Use regexp for replacements, insertafter/insertbefore for positioning, and validate for safe changes to critical files like sudoers and sshd_config.
Related Articles • Ansible replace Module: Regex Find and Replace • Ansible blockinfile Module: Manage Text Blocks • Ansible template Module: Deploy Configuration Files
Category: database-automation