CertGrid CertGrid
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

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.

One managed node, with a small `/etc/demo.conf` created for the guide and removed at the end.
Server NameIP AddressOSRolesCPURAMHDD
ANS-CTL01192.168.0.36Ubuntu 26.04 LTSAnsible Control Node2 Core3 GB50 GB
ANS-A01192.168.0.37Ubuntu 26.04 LTSManaged Node (group: web)2 Core3 GB50 GB

This guide includes

Use this when you cannot template a file because you do not own all of it. This matters because lineinfile without a regexp duplicates rather than replaces - which is the trap this guide exists to show you.

Before you start

  1. The configuration this guide assumes

  2. A file to edit

  3. lineinfile with a regexp

  4. The duplicate trap

  5. replace changes every match

  6. blockinfile for more than one line

Official sources