How to escape 1 or more whitespaces in a regex in the lineinfile module of Ansible?

16,783

Ansible playbooks are in YAML format. In a double quoted scalar, character sequences starting with the \ character are escape sequences, but the YAML specification says \s is a not a valid escape sequence.

In a double quoted scalar, you would have to write

"\\s"

Alternatively, in a single quoted scalar, the \ character has no special meaning, so you can write

'\s'
Share:
16,783
migueldavid
Author by

migueldavid

Computer Engineer by training. IT Infrastructure architect and implementer by trade.

Updated on June 19, 2022

Comments

  • migueldavid
    migueldavid almost 2 years

    I am using Ansible to set some variables on a file using the lineinfile module. The problem I'm bumping into is how to have a regular expression that is flexible enough to have some spaces in the middle of the string. Please see below:

    - name: Set DB IP in db conn file
      lineinfile: 
        dest=/path/to/db_conn
        regexp="{{ item.regexp }}"
        line="{{ item.line }}"
      with_items:
        - { regexp: "^.?dbschema_audit=",
            line: "$dbschema_audit=\'{{ db_schema_audit }}\';" }
        - { regexp: "^.?dbschema_audit_trail\s\*=",
            line: "$dbschema_audit_trail=\'{{ db_schema_audit_trail }}\';" }
    

    The file I'm trying to change has lines like these:

    $dbschema_audit='a';
    $dbschema_audit_trail ='a';
    

    I have tried different variations of \s* with {, ' and \ and nothing seems to work. Can I have some wisdom from out there?

  • migueldavid
    migueldavid almost 8 years
    Thanks, that was it! regexp: "^\\$dbschema_audit_trail\\s*=" worked