Hands-on Lab·Ansible
Ansible File Editing with lineinfile and blockinfile
Sometimes you cannot template a file because you do not own all of it - a package-managed config, or one another team also edits. Three modules edit in place, and each has a distinct job and a distinct failure. The important one is `lineinfile` without a `regexp`, which appends a duplicate instead of changing anything.
Templates, Files and Vault Guide 19 of 45 Intermediate
- OSUbuntu 26.04 LTS
- ansible-core2.20.1
- Python3.14.4
- TimeAbout 16 min
- Reviewed23 August 2026
Written against the versions above. `lineinfile` acts on the **last** line matching `regexp`. If several lines match, the others are left alone - which is why `replace` exists, and why a config with a repeated directive needs care.
| Server Name | IP Address | OS | Roles | CPU | RAM | HDD |
|---|---|---|---|---|---|---|
| ANS-CTL01 | 192.168.0.36 | Ubuntu 26.04 LTS | Ansible Control Node | 2 Core | 3 GB | 50 GB |
| ANS-A01 | 192.168.0.37 | Ubuntu 26.04 LTS | Managed Node (group: web) | 2 Core | 3 GB | 50 GB |
Before you start
- A control node configured as shown in the first step.
- The session creates
/etc/demo.confcontaining a deliberately duplicatedTimeoutline.
-
The configuration this guide assumes
-
A file to edit
-
lineinfile with a regexp
-
The duplicate trap
-
replace changes every match
-
blockinfile for more than one line