EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Ansible Replace Line in File

By Priya PedamkarPriya Pedamkar

Home » Software Development » Software Development Tutorials » Ansible Tutorial » Ansible Replace Line in File

Ansible Replace Line in File

Introduction to Ansible Replace Line in File

Ansible Replace Line in File is a module provided in Ansible package to replace a string pattern in a file. For Linux environment, where we have everything as a file. It becomes very important to manage all important configuration, library and scripts files. This is done by administrator by updating all such files regularly with all updates in infrastructure. Ansible provides modules like replace, blockinfile, copy, template and lineinfile to work with such situations. Selecting a module depends on the scope of tasks and number of iterations involved in same. So one should evaluate first then select a module to work with.

Working of Ansible Replace Line in File

In Ansible, like any other module, where we have a set of available parameters and possible acceptable values for same, in Ansible Replace module we have same as well.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Below list includes many important parameters if not all, which can be used in combination to generate desired results:

  • backup: This parameter is used for taking a backup of a file with timestamp before updating it. So that we will be able to restore it when needed later. Default is “no”.
  • attributes: This is used to set attributes of the resulting file. This can be checked by lsattrlater. Check the supported flags at man page of chattr on target systems.
  • owner: Name of the user, owning the resulting file.
  • group: Name of the group, owning the resulting file.
  • after: This is used to specify that only content after this match will be removed/replaced. This can be used with before in a combination.
  • before: This is used to specify that only content after this match will be removed/replaced. This can be used with after in a combination.
  • mode: The permission of resulting file. Better practice is use 4 octal numbers inside single quotes to represent the permission like ‘0777’ or ‘0644’.
  • path: The file’s path, which is our task’s target.
  • regexp: The pattern to look for in every line of file. It uses python regular expression.
  • selevel, serole, setype, seuser: These are used to update the selinux file context.
  • validate: This is used to validate the command before running on target system shell. The file path to be validated is passed in via ‘%s’.
  • encoding: The character encoding for a file. Default s utf-8.
  • others: All arguments accepted by file also works here.
  • replace: The string pattern which will replace the mated patterns. If this is not set, then matched regex/patterns are removed entirely.

Examples of Ansible Replace Line in File

We will see some examples, but before going there, we first understand our lab, we used for testing purpose. Here we have an Ansible control server named ansible-controller and two remotes hosts named host-one and host-two. We will create playbooks and run ansible commands on ansible-controller node and see the results on remote hosts.

Example #1

In this example, we have a sample file, in which we are trying to replace a string using Ansible. For this, we have a playbook like below, where we are using Ansible replace and debug modules to replace and display the outputs.

Code:

---
- hosts: all
gather_facts: no
tasks:
- name: Here we check the contents of /var/tmp/sample_file file on target machines.
shell: 'cat /var/tmp/sample_file'
register: var_output
- name: Here are the contents of /var/tmp/sample_file file on target machines before replace
debug:
var: var_output.stdout_lines
- name: Here we are replacing the string pattern
replace:
path: /var/tmp/sample_file
regexp: 'Hello World'
replace: "Namaste To All"
- name: Here we are again checking the contents of /var/tmp/sample_file file on target machines.
shell: 'cat /var/tmp/sample_file'
register: var_output_1
- name: Here are the contents of /var/tmp/sample_file file on target machines after replace
debug:
var: var_output_1.stdout_lines

Now executing this playbook like below:

ansible-playbook ansible_replace.yaml

We have below output where we can see the Hello World is replaced with Namaste To All.

Popular Course in this category
Ansible Training (1 Course, 4 Projects)1 Online Courses | 4 Hands-on Projects | 8+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (3,201 ratings)
Course Price

View Course

Related Courses
Linux Training Program (16 Courses, 3+ Projects)Kali Linux Training (3 Courses, 3+ Projects)Red Hat Linux Training Program (4 Courses, 1+ Projects)

Output:

Ansible Replace Line in File

Example #2

In this example, we have a playbook like below where we are trying to remove the matched pattern from out sample file. For this we have a playbook like below, where we are not using replace parameter in replace module, which will result in removing the matched pattern ‘To All’ from target file.

Code:

---
- hosts: all
gather_facts: no
tasks:
- name: Here we check the contents of /var/tmp/sample_file file on target machines.
shell: 'cat /var/tmp/sample_file'
register: var_output
- name: Here are the contents of /var/tmp/sample_file file on target machines before replace
debug:
var: var_output.stdout_lines
- name: Here we are replacing the string pattern
replace:
path: /var/tmp/sample_file
regexp: 'To All'
- name: Here we are again checking the contents of /var/tmp/sample_file file on target machines.
shell: 'cat /var/tmp/sample_file'
register: var_output_1
- name: Here are the contents of /var/tmp/sample_file file on target machines after replace
debug:
var: var_output_1.stdout_lines

Now executing this playbook like below:

ansible-playbook ansible_replace.yaml

We have below output where we can see the ‘To All’ is removed from the file.

Output:

trying to remove the matched pattern from out sample

Example #3

In this example, we are going to replace a string in /etc/hosts and also will set ownership and permissions. For this we have a playbook like below.

Code:

---
- hosts: host-one
gather_facts: no
tasks:
- name: Here we check the contents of /etc/hosts
shell: 'cat /etc/hosts| grep "192.168.0.11"'
register: var_output
- name: Here are the contents of /etc/hosts file on target machines before replace
debug:
var: var_output.stdout_lines
- name: Here we are replacing the string pattern
replace:
backup: yes
path: /etc/hosts
regexp: '(\s+)host1\.example\.com(\s+.*)?$'
replace: '\1server1.example.com\2'
owner: root
group: root
mode: 0644
- name: Here we again check the contents of /etc/hosts
shell: 'cat /etc/hosts| grep "192.168.0.11"'
register: var_output
- name: Here are the contents of /etc/hosts file on target machines after replace
debug:
var: var_output.stdout_lines

Now running this playbook will give output like below where we can clearly see that string host1.example.com has been replaced by server1.example.com.

Also check the other parameters used to set permission and ownership of the file after changes.

ansible-playbook ansible_replace_IP.yaml --syntax-check

Output:

Ansible Replace Line in File 3

Conclusion

As we saw in this article, this module can replace a line in a file on target remote machines. Also it can set permissions, ownership etc. to a file. This module is easy to use and works with basics of Linux systems.

Recommended Articles

This is a guide to Ansible Replace Line in File. Here we discuss the introduction to Ansible Replace Line in File, working and programming examples. You may also have a look at the following articles to learn more –

  1. Ansible local_action
  2. Ansible Lookup
  3. Ansible Playbooks
  4. Ansible Synchronize

Ansible Training (1 Course, 4 Projects)

1 Online Courses

4 Hands-on Projects

8+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
Ansible Tutorial
  • Ansible Basics
    • What is Ansible
    • Is Ansible free
    • How to Install Ansible
    • Ansible Versions
    • Ansible Architecture
    • Ansible Commands
    • Ansible ad-hoc Commands
    • Ansible Playbooks
    • Ansible Roles
    • Ansible Tags
    • Ansible Ping
    • Ansible Apt
    • Ansible Facts
    • Ansible Tower
    • Ansible Galaxy
    • Ansible Handlers
    • Ansible Loop
    • Ansible Block
    • Ansible Conditional
    • Ansible YAML
    • Ansible Debug
    • Ansible Synchronize
    • Ansible Template
    • Ansible group_vars
    • Ansible Lookup
    • Ansible File Module
    • Ansible Yum Module
    • Ansible Shell Module
    • Ansible lineinfile
    • Ansible Service Module
    • Ansible User Module
    • Ansible Windows Modules
    • ansible-doc
    • Ansible Filters
    • Ansible Add User to Group
    • Ansible Register
    • Ansible Set Fact
    • Ansible Hosts File
    • Ansible add_host
    • Ansible Collections
    • Ansible with_items
    • Ansible Replace Line in File
    • Ansible inventory_hostname
    • Ansible Dynamic Inventory
    • Ansible local_action
    • Ansible Firewalld
    • Ansible Unarchive
    • Ansible Sudo
    • Ansible Create Directory
    • Ansible Reboot
    • Ansible wait_for
    • Ansible run_once
    • Ansible Authorized_key
    • Ansible Interview Questions

Related Courses

Linux Training Course

Kali Linux Training

Red Hat Training Course

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - Ansible Training (1 Course, 4 Projects) Learn More