DEV Community

Janak Shrestha
Janak Shrestha

Posted on

Ansible Replace Module

There is some data on all app servers in Stratos DC. The Nautilus development team shared some requirement with the DevOps team to alter some of the data as per recent changes they made. The DevOps team is working to prepare an Ansible playbook to accomplish the same. Below you can find more details about the task.

Write a playbook.yml under /home/thor/ansible on jump host, an inventory is already present under /home/thor/ansible directory on Jump host itself. Perform below given tasks using this playbook:

  1. We have a file /opt/finance/blog.txt on app server 1. Using Ansible replace module replace string xFusionCorp to Nautilus in that file.
  2. We have a file /opt/finance/story.txt on app server 2. Using Ansiblereplace module replace the string Nautilus to KodeKloud in that file.
  3. We have a file /opt/finance/media.txt on app server 3. Using Ansible replace module replace string KodeKloud to xFusionCorp Industries in that file.

Note: Validation will try to run the playbook using command ansible-playbook -i inventory playbook.yml so please make sure the playbook works this way without passing any extra arguments.


Introduction

In real-world infrastructure management, you often need to update configuration files, data files, or content across multiple servers. Sometimes the same change applies to every server. More often, each server requires a different change. Ansible handles both scenarios cleanly.

This article walks through a practical lab exercise where three application servers each need a different string replacement in a different file. The solution uses the replace module combined with conditional logic to target each server precisely. Every command and output shown below is from an actual run.


The Requirements

The task had the following requirements:

  1. On stapp01, replace the string xFusionCorp with Nautilus in /opt/finance/blog.txt.
  2. On stapp02, replace the string Nautilus with KodeKloud in /opt/finance/story.txt.
  3. On stapp03, replace the string KodeKloud with xFusionCorp Industries in /opt/finance/media.txt.
  4. The playbook must be at /home/thor/ansible/playbook.yml and must run with the exact command ansible-playbook -i inventory playbook.yml.

The key challenge is that each server requires a different replacement. The playbook cannot simply apply the same replace task to all hosts. It must differentiate between them.


Step 1: Navigate to the Working Directory

cd /home/thor/ansible
Enter fullscreen mode Exit fullscreen mode

Verify the inventory file:

cat inventory
Enter fullscreen mode Exit fullscreen mode

Output:

stapp01 ansible_host=stapp01 ansible_ssh_pass=Ir0nM@n ansible_user=tony
stapp02 ansible_host=stapp02 ansible_ssh_pass=Am3ric@ ansible_user=steve
stapp03 ansible_host=stapp03 ansible_ssh_pass=BigGr33n ansible_user=banner
Enter fullscreen mode Exit fullscreen mode

Three hosts are listed in a flat inventory with no group headers. The playbook will use hosts: all and then differentiate using host names.


Step 2: Verify Connectivity

Before running any playbook, confirm that Ansible can reach every host:

ansible all -i inventory -m ping
Enter fullscreen mode Exit fullscreen mode

Output:

stapp01 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "ping": "pong"
}
stapp02 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "ping": "pong"
}
stapp03 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "ping": "pong"
}
Enter fullscreen mode Exit fullscreen mode

All three hosts respond with pong, confirming the connection works.


Step 3: Create the Playbook

Open the playbook file:

vi /home/thor/ansible/playbook.yml
Enter fullscreen mode Exit fullscreen mode

Add the following content:

---
- name: Replace strings on specific app servers
  hosts: all
  become: yes
  tasks:
    - name: Replace xFusionCorp with Nautilus in blog.txt on stapp01
      ansible.builtin.replace:
        path: /opt/finance/blog.txt
        regexp: 'xFusionCorp'
        replace: 'Nautilus'
      when: inventory_hostname == 'stapp01'

    - name: Replace Nautilus with KodeKloud in story.txt on stapp02
      ansible.builtin.replace:
        path: /opt/finance/story.txt
        regexp: 'Nautilus'
        replace: 'KodeKloud'
      when: inventory_hostname == 'stapp02'

    - name: Replace KodeKloud with xFusionCorp Industries in media.txt on stapp03
      ansible.builtin.replace:
        path: /opt/finance/media.txt
        regexp: 'KodeKloud'
        replace: 'xFusionCorp Industries'
      when: inventory_hostname == 'stapp03'
Enter fullscreen mode Exit fullscreen mode

Save the file and exit the editor.


Understanding the Playbook

The playbook uses a single play with hosts: all and become: yes. It contains three tasks, and each task uses the when conditional to restrict execution to one specific host.

hosts: all runs the play against every host in the inventory. This is a common approach when the logic for each host differs, and it avoids creating multiple plays with repeated module parameters.

when: inventory_hostname == 'stapp01' is the key mechanism. The inventory_hostname variable contains the name of the host currently being processed. When the condition is true, the task runs. When false, Ansible reports the task as skipped on that host.

ansible.builtin.replace is the fully qualified collection name for the replace module. It performs a regular expression search and replacement in a file. For simple literal strings like xFusionCorp, the string itself works as the regexp.

An important detail: the regexp parameter is a regular expression. If your search string contains regex special characters such as ., *, +, ?, (, ), or [, you must escape them. The strings used in this exercise do not contain such characters, so no escaping is needed.


Step 4: Validate the Syntax

Before running the playbook, check the YAML syntax:

ansible-playbook -i inventory playbook.yml --syntax-check
Enter fullscreen mode Exit fullscreen mode

Output:

playbook: playbook.yml
Enter fullscreen mode Exit fullscreen mode

A successful syntax check returns the playbook filename with no error messages.


Step 5: Run the Playbook

ansible-playbook -i inventory playbook.yml
Enter fullscreen mode Exit fullscreen mode

Output:

PLAY [Replace strings on specific app servers] ***************************************************************

TASK [Gathering Facts] ***************************************************************************************
ok: [stapp02]
ok: [stapp03]
ok: [stapp01]

TASK [Replace xFusionCorp with Nautilus in blog.txt on stapp01] **********************************************
skipping: [stapp02]
skipping: [stapp03]
changed: [stapp01]

TASK [Replace Nautilus with KodeKloud in story.txt on stapp02] ***********************************************
skipping: [stapp01]
skipping: [stapp03]
changed: [stapp02]

TASK [Replace KodeKloud with xFusionCorp Industries in media.txt on stapp03] *********************************
skipping: [stapp01]
skipping: [stapp02]
changed: [stapp03]

PLAY RECAP ***************************************************************************************************
stapp01                    : ok=2    changed=1    unreachable=0    failed=0    skipped=2    rescued=0    ignored=0
stapp02                    : ok=2    changed=1    unreachable=0    failed=0    skipped=2    rescued=0    ignored=0
stapp03                    : ok=2    changed=1    unreachable=0    failed=0    skipped=2    rescued=0    ignored=0
Enter fullscreen mode Exit fullscreen mode

The output shows exactly what is expected.

For each host, one task is changed and the other two are skipped. On stapp01, only the first replace task runs and makes a change. The other two tasks are skipped because the when condition evaluates to false.

The play recap confirms the result. Each host shows ok=2 (the fact-gathering task plus one successful replace task), changed=1, and skipped=2. All hosts report failed=0.


Step 6: Verify the File Contents

Confirm that the replacements happened correctly by reading each file:

ansible stapp01 -i inventory -m shell -a "cat /opt/finance/blog.txt"
ansible stapp02 -i inventory -m shell -a "cat /opt/finance/story.txt"
ansible stapp03 -i inventory -m shell -a "cat /opt/finance/media.txt"
Enter fullscreen mode Exit fullscreen mode

Output:

stapp01 | CHANGED | rc=0 >>
Welcome to Nautilus Industries !
stapp02 | CHANGED | rc=0 >>
Welcome to KodeKloud Group !
stapp03 | CHANGED | rc=0 >>
Welcome to xFusionCorp Industries !
Enter fullscreen mode Exit fullscreen mode

Each file now contains the correct replacement string:

  • blog.txt on stapp01 now says Nautilus instead of xFusionCorp.
  • story.txt on stapp02 now says KodeKloud instead of Nautilus.
  • media.txt on stapp03 now says xFusionCorp Industries instead of KodeKloud.

The replacement preserved the surrounding text such as "Welcome to" and "Industries!" and "Group!". This is because the replace module only replaces the matched pattern and leaves the rest of the line intact.


Why the when Conditional Is Necessary

Without the when conditional, each task would attempt to run on every host. This would cause several problems.

First, the file paths are specific to each server. If the task for stapp01 ran on stapp02, it would try to open /opt/finance/blog.txt on stapp02, which may not exist. The task would fail.

Second, even if the files existed everywhere, the replacement logic would be wrong. Replacing xFusionCorp with Nautilus is only desired on stapp01. Applying the same replacement on stapp03 would corrupt its data.

The when conditional solves both problems. It ensures that each task only runs on the host it was designed for. The skipped status on other hosts confirms the logic is working correctly.


Alternative Approach: Separate Plays

Another valid approach is to write three separate plays, each targeting a specific host:

---
- name: Replace on stapp01
  hosts: stapp01
  become: yes
  tasks:
    - name: Replace xFusionCorp with Nautilus
      ansible.builtin.replace:
        path: /opt/finance/blog.txt
        regexp: 'xFusionCorp'
        replace: 'Nautilus'

- name: Replace on stapp02
  hosts: stapp02
  become: yes
  tasks:
    - name: Replace Nautilus with KodeKloud
      ansible.builtin.replace:
        path: /opt/finance/story.txt
        regexp: 'Nautilus'
        replace: 'KodeKloud'

- name: Replace on stapp03
  hosts: stapp03
  become: yes
  tasks:
    - name: Replace KodeKloud with xFusionCorp Industries
      ansible.builtin.replace:
        path: /opt/finance/media.txt
        regexp: 'KodeKloud'
        replace: 'xFusionCorp Industries'
Enter fullscreen mode Exit fullscreen mode

Both approaches work. The single-play version with when conditionals is more compact and avoids repeating the become and other play-level settings. The multi-play version is more explicit about which host each task belongs to.

For a small number of hosts, either style is fine. For larger inventories, the conditional approach scales better because it keeps the play definition in one place.


Key Concepts Demonstrated

Concept What It Does in This Playbook
hosts: all Targets every host in the inventory
when: inventory_hostname == '...' Restricts a task to one specific host
ansible.builtin.replace Performs regex-based find and replace in a file
regexp The pattern to search for
replace The string to substitute for the matched pattern
become: yes Ensures the task can write to files under /opt

Final Playbook

---
- name: Replace strings on specific app servers
  hosts: all
  become: yes
  tasks:
    - name: Replace xFusionCorp with Nautilus in blog.txt on stapp01
      ansible.builtin.replace:
        path: /opt/finance/blog.txt
        regexp: 'xFusionCorp'
        replace: 'Nautilus'
      when: inventory_hostname == 'stapp01'

    - name: Replace Nautilus with KodeKloud in story.txt on stapp02
      ansible.builtin.replace:
        path: /opt/finance/story.txt
        regexp: 'Nautilus'
        replace: 'KodeKloud'
      when: inventory_hostname == 'stapp02'

    - name: Replace KodeKloud with xFusionCorp Industries in media.txt on stapp03
      ansible.builtin.replace:
        path: /opt/finance/media.txt
        regexp: 'KodeKloud'
        replace: 'xFusionCorp Industries'
      when: inventory_hostname == 'stapp03'
Enter fullscreen mode Exit fullscreen mode

Conclusion

This exercise demonstrates two important Ansible concepts working together: the replace module for in-place text modification and the when conditional for controlling which task runs on which host.

The replace module is the right tool when you need to change specific strings within a file without rewriting the entire file. Unlike the copy module, which overwrites the whole file, replace preserves everything except the matched pattern. Unlike lineinfile, which manages whole lines, replace works on substrings within lines.

The when conditional is essential whenever different hosts need different treatment. The inventory_hostname variable provides a reliable way to identify the current host. The skipped status in the output confirms that the conditions are evaluated correctly.

Verification with cat after the run confirms that each server received the exact replacement it needed. This habit of verifying after running should be standard in any automation workflow.

Top comments (0)