Ansible replace Module: Find & Replace Text in Files (Complete Guide)
By Luca Berton · Published 2024-01-01 · Category: database-automation
How to use the Ansible replace module (ansible.builtin.replace) to find and replace text in files using regex.
Ansible replace Module: Find & Replace Text in Files (Complete Guide)
The Ansible replace module (ansible.builtin.replace) performs regex-based find-and-replace operations on files. It's the go-to module for updating configuration values, modifying settings, and performing bulk text changes across your fleet.
See also: Ansible regex_replace Filter: Find & Replace with Regex (Complete Guide)
Basic Usage
---
- name: Replace text in files
hosts: all
become: true
tasks:
- name: Change server name in config
ansible.builtin.replace:
path: /etc/nginx/nginx.conf
regexp: 'server_name\s+old\.example\.com'
replace: 'server_name new.example.com'
Key Parameters
| Parameter | Description | Required |
|-----------|-------------|----------|
| path | File to modify | ✅ |
| regexp | Regex pattern to find | ✅ |
| replace | Replacement text | ❌ (empty = delete match) |
| backup | Create backup before modifying | ❌ |
| before | Only replace before this pattern | ❌ |
| after | Only replace after this pattern | ❌ |
| owner | File owner after modification | ❌ |
| group | File group after modification | ❌ |
| mode | File permissions | ❌ |
| validate | Validation command before placing | ❌ |
| encoding | File encoding | ❌ (utf-8) |
See also: Ansible regex_search & regex_replace Filters: Pattern Matching Guide
Common Examples
Change a Configuration Value
- name: Update max connections
ansible.builtin.replace:
path: /etc/postgresql/16/main/postgresql.conf
regexp: '^max_connections\s*=\s*\d+'
replace: 'max_connections = 200'
- name: Change listen port
ansible.builtin.replace:
path: /etc/nginx/nginx.conf
regexp: 'listen\s+\d+;'
replace: 'listen 8080;'
Comment/Uncomment Lines
- name: Comment out a line
ansible.builtin.replace:
path: /etc/ssh/sshd_config
regexp: '^(PermitRootLogin\s+yes)'
replace: '#\1'
- name: Uncomment a line
ansible.builtin.replace:
path: /etc/ssh/sshd_config
regexp: '^#\s*(PermitRootLogin\s+no)'
replace: '\1'
Replace with Variables
- name: Update database host
ansible.builtin.replace:
path: /opt/app/.env
regexp: '^DB_HOST=.*$'
replace: 'DB_HOST={{ db_host }}'
- name: Update version number
ansible.builtin.replace:
path: /opt/app/version.txt
regexp: 'version:\s*[\d.]+'
replace: 'version: {{ app_version }}'
Delete Matching Lines
- name: Remove debug lines
ansible.builtin.replace:
path: /opt/app/config.yml
regexp: '^\s*debug:.*\n'
replace: ''
Replace Within a Section (before/after)
- name: Change port only in [server] section
ansible.builtin.replace:
path: /etc/app/config.ini
after: '\[server\]'
before: '\[database\]'
regexp: 'port\s*=\s*\d+'
replace: 'port = 9090'
Multi-Line Replacement
- name: Replace a multi-line block
ansible.builtin.replace:
path: /etc/nginx/nginx.conf
regexp: |
location /old-api \{
[^}]*\}
replace: |
location /api {
proxy_pass http://backend:8080;
proxy_set_header Host $host;
}
Backup Before Replacing
- name: Replace with backup
ansible.builtin.replace:
path: /etc/app/config.yml
regexp: 'api_endpoint:\s*https?://.*'
replace: 'api_endpoint: https://api.new-domain.com'
backup: true
Validate After Replacement
- name: Replace nginx config with validation
ansible.builtin.replace:
path: /etc/nginx/nginx.conf
regexp: 'worker_connections\s+\d+'
replace: 'worker_connections 4096'
validate: nginx -t -c %s
replace vs lineinfile vs template
| Use Case | Module |
|----------|--------|
| Replace text matching a regex anywhere in file | replace |
| Ensure a specific line exists | lineinfile |
| Replace with Jinja2 logic/loops | template |
| Replace all occurrences of a pattern | replace |
| Add/modify one line | lineinfile |
| Manage entire file content | template or copy |
# replace — changes ALL matching lines
- ansible.builtin.replace:
path: /etc/hosts
regexp: '192\.168\.1\.10'
replace: '10.0.0.10'
# lineinfile — ensures ONE line exists
- ansible.builtin.lineinfile:
path: /etc/hosts
regexp: '^10\.0\.0\.10'
line: '10.0.0.10 app.local'
See also: Ansible troubleshooting — Invalid plugin name: regex.replace Error in Ansible
Regex Tips for Ansible replace
# Match beginning of line
regexp: '^setting_name'
# Match end of line
regexp: 'value$'
# Match any whitespace
regexp: 'key\s*=\s*value'
# Capture groups (use \1, \2 in replace)
regexp: '(listen)\s+\d+'
replace: '\1 8080'
# Case-insensitive (Python regex flag (?i))
regexp: '(?i)debug\s*=\s*true'
replace: 'debug = false'
# Match across lines (use [\s\S] instead of .)
regexp: 'start[\s\S]*?end'
Loop Over Multiple Files
- name: Update config across multiple files
ansible.builtin.replace:
path: "{{ item }}"
regexp: 'old-server\.example\.com'
replace: 'new-server.example.com'
loop:
- /etc/app/config.yml
- /etc/app/database.yml
- /opt/scripts/backup.sh
- name: Replace in all config files
ansible.builtin.replace:
path: "{{ item.path }}"
regexp: 'old-server\.example\.com'
replace: 'new-server.example.com'
loop: "{{ lookup('fileglob', '/etc/app/*.conf', wantlist=True) | map('community.general.dict_kw', path=item) }}"
FAQ
What is the Ansible replace module?
The ansible.builtin.replace module performs regex-based find-and-replace on files. It replaces ALL occurrences of a pattern in a file, unlike lineinfile which manages single lines. It's ideal for bulk text changes and configuration updates.
How do I find and replace text in Ansible?
Use ansible.builtin.replace with path (file to modify), regexp (pattern to find), and replace (replacement text). The module uses Python regular expressions and replaces all matching occurrences.
What is the difference between Ansible replace and lineinfile?
replace finds and replaces ALL occurrences of a regex pattern anywhere in the file. lineinfile ensures a specific line exists (adds it if missing, replaces if the regex matches). Use replace for bulk changes; lineinfile for managing individual lines.
Can Ansible replace use regex capture groups?
Yes. Use parentheses in regexp to capture groups and \1, \2 in replace to reference them. Example: regexp: '(port)\s+\d+' with replace: '\1 8080'.
How do I replace text only in a specific section of a file?
Use the after and before parameters to limit the replacement scope. For example, after: '\[server\]' and before: '\[database\]' only replaces within the [server] section.
Conclusion
The Ansible replace module is essential for regex-based text modifications across your infrastructure. Use it for configuration updates, bulk changes, and pattern-based modifications. Combine with backup for safety and validate for configuration verification.
Related Articles
• Ansible lineinfile Module: Add & Replace Lines • Ansible template Module: Deploy Jinja2 Templates • Ansible blockinfile Module: Insert Text BlocksCategory: database-automation