Ansible: Comment Out & Uncomment Lines in a File

To comment out or uncomment lines in a file in automated deployments we can use the Ansible’s replace module.

This module is used to replace all instances of a pattern within a file and perfectly suits our needs.

In this note i will show several examples of the Ansible tasks for commenting out and uncommenting lines in a file.

Cool Tip: How to check if a file exists in Ansible! Read more →

Comment Out & Uncomment Lines using Ansible

To comment out or uncomment all the lines in a file matching the particular string:

- name: "Comment out the line"
  replace:
    path: /path/to/file
    regexp: 'Comment me out'
    replace: '#Comment me out'

- name: "Uncomment the line"
  replace:
    path: /path/to/file
    regexp: '#Uncomment me'
    replace: 'Uncomment me'

Often the exact content of a string to comment out or uncomment is unknown.

Imagine a config file with some foo option that you need to disable or enable without knowing the current value of this option.

In Ansible this can be achieved by using the \1 in replace to match (…every character inside brackets…) in regexp.

To comment out lines starting with any number of the whitespace characters and with any characters after the foo=:

- name: "Comment out the line"
  replace:
    path: /path/to/file
    regexp: '^\s*(foo=.*)'
    replace: '#\1'

This Ansible task results to the changes as follows:

# Before commenting out
---
foo=bar
 foo=baz
     foo=qux

# After commenting out
---
#foo=bar
#foo=baz
#foo=qux

To uncomment lines starting with any number of the whitespace characters, followed by any number of the # (pound) signs, followed again by any number of the whitespace characters and with any characters after the foo=:

- name: "Uncomment the line"
  replace:
    path: /path/to/file
    regexp: '^\s*#*\s*(foo=.*)'
    replace: '\1'

This Ansible task results the changes as follows:

# Before uncommenting
---
#foo=bar
   #   foo=baz
  #### foo=qux

# After uncommenting
---
foo=bar
foo=baz
foo=qux
Was it useful? Share this post with the world!

2 Replies to “Ansible: Comment Out & Uncomment Lines in a File”

  1. The last example also changes
    foo=bat
    to
    foo=bar
    If you change the #* to #+ in the regex it will only affect commented lines.

  2. Ansible playbooks are idempotent, meaning you can run them multiple times without causing unintended changes. This ensures consistent and predictable results.

Leave a Reply