As per my question above: "Ansible, attempting to get specific regex pattern to work with lineinfile module"

Essentially, I'm trying to get it to work in a single play as opposed to 2 separate plays, and for this a regex is required. I've tried a few variations that would work with sed, but they don't appear to work here. Maybe I'm crazy. Example of what I am trying to do is below:

  - name: Change file contents on CentOS and Redhat servers.
    dest: /etc/blah/randomfile
    regexp: '^ThisValueHere|^#ThisValueHere'
    line: 'ThisValueHere no'
    when: (ansible_distribution == "CentOS")  or (ansible_distribution == "RedHat")

(Yeah yeah, ignore bad yml syntax, it's just fine in the actual playbook)

Basically I want to match lines STARTING WITH: (ThisValueHere, OR, #ThisValueHere), and then replace either of those lines with the line: (ThisValueHere no)

However, I can't seem to get it to work properly, maybe I just really have to brush up on regex stuffs. In any case, if anyone has any suggestions that would be highly appreciated!

Additionally if there is a link that could be provided to the "keys" to successful ansible regex usage, that would be greatly helpful as well.

  • 1
    The "keys" tosuccessful ansible regex usage is to understand that is python regular expression. You can try with an online tool using flavor python.
    – xtrmz
    Dec 13, 2016 at 15:53
  • 3
    Your example works for me. Your YAML indenting (or lack of) may be part of the problem. When my indenting matches yours it doesn't work. When I indent properly it does. As for regex, it's Python regex, link requested: docs.python.org/2/library/re.html Dec 13, 2016 at 16:40

1 Answer 1


It works with the replace task, lineinfile does not provide the multiline python regexp.

- name: Change file contents on CentOS and Redhat servers. replace: dest: /etc/blah/randomfile regexp: '^(#?ThisValueHere)' replace: 'ThisValueHere no' when: (ansible_distribution == "CentOS") or (ansible_distribution == "RedHat")

  • Exactly as @xtrmz has said. You are using the wrong ansible module. From the 'lineinfile' module synopsis, This is primarily useful when you want to change a single line in a file only. See the "replace" module if you want to change multiple, similar lines ... in a file. docs.ansible.com/ansible/latest/collections/ansible/builtin/…
    – 0xSheepdog
    Sep 14, 2021 at 15:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .