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 '16 at 15:53
  • 1
    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 – Tim Kennedy Dec 13 '16 at 16:40

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")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.