Ansible Replace Module: The Best Guide for Efficient Text Substitution

Ansible Replace Module

Table of Contents

Get up to 50% off now

Become a partner with CyberPanel and gain access to an incredible offer of up to 50% off on CyberPanel add-ons. Plus, as a partner, you’ll also benefit from comprehensive marketing support and a whole lot more. Join us on this journey today!

Ansible replace module is your go-to solution for automating text substitutions efficiently and reliably.

If you’re struggling to update your configuration files across multiple servers without manually editing each one, this guide is a complete solution for you. We cover how the Ansible Replace module works, and 4 easy examples.

What Is The Ansible Replace Module?

The Ansible Replace Module is simply designed to search for specific patterns in files and replace them with new values. It is designed to find and substitute text or specific patterns in files on remote hosts. It works much like the replace feature in a text editor.

The Ansible replace module functions by searching the specified file in the task for a particular string or regular expression and replacing it with a new value. This is helpful for modifying configuration files to change database connection strings, update port settings or API keys, or adjust file paths on multiple servers.

The replace module is beneficial when you need to change the version number in a configuration file after upgrading an application, or when you want to swap hardcoded values in configuration files with variables that are specific to the environment.

Here are several important features of the Ansible replace module:

Tech Delivered to Your Inbox!

Get exclusive access to all things tech-savvy, and be the first to receive 

the latest updates directly in your inbox.

  1. Idempotency: Guarantees that changes are applied only when needed.
  2. Flexibility: Allows the use of regular expressions for more complex text matching.
  3. Simplicity: User-friendly with clear parameters.

This is how the Ansible replace module actually works. These are some parameters:

The Ansible replace module has a few parameters to work with. Let’s go over some key ones that are essential for using the replace module.

  • Path: This is the path to the destination file. Before Ansible version 2.3, it was referred to as dest, destfile, or name.
  • Regexp: These are the regular expressions used to find content in the file, which will then be replaced based on that.
  • Replace: This is the keyword or string that will replace the content in the file. If you don’t set this parameter and the regular expression finds a match, it will remove the entire keyword from all instances in the file.
  • Backup: The default is ‘no’. Setting it to ‘yes’ creates a backup with a timestamp before changes, preserving the original file in case something goes wrong.
  • Choices:
  • false ← (default)
  • true
  • Owner: This specifies the name of the owner of the file after the replacement. It uses the chown command to change the owner.
  • Group: This is the name of the group that will own the file after the replacement.
  • Mode: This indicates the permissions that the specified file should have.
  • Before: If this is specified, it will replace the content before the match and can be used together with after.
  • After: If this is specified, it will replace the content after the match and can be used together with before.

Basic Usage

- name: Replace a string in a file ansible.builtin.replace: path: /path/to/file regexp: 'old_string' replace: 'new_string'
  • path: This refers to the complete path of the file on the remote server that you wish to change.
  • regexp: This is the text or pattern you are looking for in the file. You can use either a string or a regular expression, which should be enclosed in single quotes.
  • replace: This specifies the string or text you want to use to replace the value obtained from the regexp.

Once you have defined these key parameters, you can substitute a string in your files with a new value. In the following sections, we will explore additional parameters that can help improve the functionality of this module.

Advanced Techniques

Multiline Text Replacement

- name: Replace multiline text<br>  ansible.builtin.replace:<br>    path: /etc/example.conf<br>    regexp: 'start_pattern.*?end_pattern'<br>    replace: 'new_multiline_text'<br>    backup: yes<br>

Conditional Replacements with before and after Parameters

name: Replace text between specific markers<br>ansible.builtin.replace:<br>path: /etc/example.conf<br>regexp: 'pattern_to_replace'<br>replace: 'new_value'<br>before: 'start_marker'<br>after: 'end_marker'

Best Practical Ansible Replace Module Examples

Here are some very good examples to learn as a beginner:

Example 1: Updating Configuration Files Across Multiple Servers

The Ansible replace module is handy for changing out an email contact with a new one on all your servers. This might be necessary if the company opts for a different email strategy and changes its support email. You just need to point to the application path where the email is set up and update it to the new address.

If your systems have various application paths, you’ll need to incorporate looping and variables to complete the task.

Check out the example below:

- name: Update contact email address in multiple application configurations
  hosts: myservers
  vars:
    applications:
      - { app_name: "app1", config_path: "/etc/app1/config/email_config.conf", old_email: "[email protected]", new_email: "[email protected]" }
      - { app_name: "app2", config_path: "/etc/app2/config/email_config.conf", old_email: "[email protected]", new_email: "[email protected]" }
      - { app_name: "app3", config_path: "/opt/app3/config/email_config.conf", old_email: "[email protected]", new_email: "[email protected]" }

  tasks:
    - name: Replace old email address with new one in each app config
      replace:
        path: "{{ item.config_path }}"
        regexp: "contact_email={{ item.old_email }}"
        replace: "contact_email={{ item.new_email }}"
      loop: "{{ applications }}"

Example 2: Change API URLs in Kubernetes ConfigMaps

In this example, we will try to update the API URL to a new one. Since the ConfigMap holds important environment variables that can influence our processes, we need to make sure we have a backup of this file.

Here is a sample ConfigMap:

Enhance Your CyerPanel Experience Today!
Discover a world of enhanced features and show your support for our ongoing development with CyberPanel add-ons. Elevate your experience today!

apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>name: app-api-config<br>data:<br>api_url: "http://old-api.example.com"

The following Ansible playbook will look for the specific API and update it with the new one:

name: Update old API URL with backup in Kubernetes ConfigMap<br>replace:<br>path: /kubernetes/configmap-api.yml<br>regexp: 'api_url: "http://old-api.example.com"'<br>replace: 'api_url: "http://new-api.example.com"'<br>backup: true

Example 3: Adding a new feature to the Kubernetes API server

Modifying the Kubernetes API file is delicate and can cause issues if an invalid character is present in the main Pod file, leading to downtime and troubleshooting. It’s essential to back up the file before making any changes.

Here is the sample kube-apiserver manifest file we will be using:

apiVersion: v1<br>kind: Pod<br>metadata:<br>name: kube-apiserver<br>namespace: kube-system<br>spec:<br>containers:<br>- name: kube-apiserver<br>image: k8s.gcr.io/kube-apiserver:v1.21.0<br>command:<br>- /bin/sh<br>- -c<br>- |<br>kube-apiserver --advertise-address=$(hostname -i) \<br>--allow-privileged=true \<br>--authorization-mode=Node,RBAC \<br>--enable-admission-plugins=NodeRestriction<br>ports:<br>- containerPort: 6443<br>protocol: TCP

We will try to update the command field with a new feature by changing the value in the enable-admission-plugins field. If we mistakenly add an extra space or use the wrong plugin name, the cluster could fail. Therefore, it’s essential to back up this file and have a rollback plan ready.

name: Backup and update kube-apiserver flags with new feature gate<br>replace:<br>path: /etc/kubernetes/manifests/kube-apiserver.yaml<br>regexp: '--enable-admission-plugins=NodeRestriction'<br>replace: '--enable-admission-plugins=NodeRestriction,AnotherPlugin'<br>backup: true<strong>                  
 </strong>name: Update kube-apiserver flags hosts: master_nodes tasks:

Example 4: Replacing a String with Backup

At times, you may want to keep the original file intact before making any modifications. For instance, if the string you want to replace is already present, you can use the backup option to ensure the original file remains unchanged before any alterations are applied.

name: Replace with backup<br>ansible.builtin.replace:<br>path: /etc/example.conf<br>regexp: 'old_string'<br>replace: 'new_string'<br>backup: yes

Now, execute the playbook above.

ansible-playbook idempotency_backup.yml

You’ll see the following output.

PLAY [Replace with backup] ***************************************************** TASK [Gathering Facts] ********************************************************* ok: [hostname] TASK [Replace old_string with new_string with backup] ************************** changed: [hostname] PLAY RECAP ********************************************************************* hostname : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

Conclusion

We took a look at the Ansible replace module and its real-world uses. We discussed how to swap out simple strings, modify specific lines, utilize regular expressions for more complex text changes, make backups, manage multiline patterns, and carry out case-insensitive replacements.

FAQ’s

1. What is the Ansible replace module used for?
A: The Ansible replace module helps you find a specific string or pattern in a file and swap it out for another string. It’s perfect for tweaking configuration files without having to rewrite the whole thing.

2: How do I use the Ansible replace module to update a specific line?
A: You can use the regexp parameter to identify a line and replace it with the new content. Here’s an example:

name: Replace line in config<br>ansible.builtin.replace:<br>path: /etc/example.conf<br>regexp: '^old_value='<br>replace: 'new_value=42'

3: Can the Ansible replace module work with multi-line strings?
A: Absolutely! The regexp parameter can handle multi-line regular expressions by using the (?s) flag to match across lines. Just be sure to test thoroughly for complex patterns.

4: What is the difference between the Ansible replace and lineinfile modules?
A: The replace module is all about pattern matching and text replacement, while lineinfile is used to ensure a specific line is either present or absent. Use replace for regex updates and lineinfile for adding or enforcing lines.

5: Does the Ansible replace module create a backup of the original file?
A: Yes, you can set backup: yes to make a backup of the file before making changes. This is a great way to avoid data loss if something goes wrong.

Areeba Nauman
Areeba is a Content Writer with expertise in web content and social media, she can simplify complex concepts to engage diverse audiences. Fueled by creativity and driven by results, she brings a unique perspective and a keen attention to detail to every project she undertakes with her creativity and passion for delivering impactful content strategies for success. Let's connect on Linkedin: https://www.linkedin.com/in/areeba-bhatti/
Unlock Benefits

Become a Community Member

SIMPLIFY SETUP, MAXIMIZE EFFICIENCY!
Setting up CyberPanel is a breeze. We’ll handle the installation so you can concentrate on your website. Start now for a secure, stable, and blazing-fast performance!