Ashar
Ashar

Reputation: 3065

Append a string at the end of regex matched line using Ansible

Wherever I find the tar command in a file I wish to append 2>/dev/null at the end of the same line.

Thus, if /tmp/test.sh file has tar -cf test.tar /myfolder entry then it should get changed to tar -cf test.ta /myfolder 2>/dev/null

Below is my playbook for the same:

 - name: Suppress tar errors
     replace:
       path: "/tmp/test.sh"
       regexp: 'tar *'
       replace: '\1 >2/dev/null'

However i get the below error:

TASK [Suppress tar errors] **********************************************************************************************************************************************
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: sre_constants.error: invalid group reference
fatal: [10.9.9.126]: FAILED! => {"changed": false, "module_stderr": "Traceback (most recent call last):\n  File \"<stdin>\", line 102, in <module>\n  File \"<stdin>\", line 94, in _ansiballz_main\n  File \"<stdin>\", line 40, in invoke_module\n  File \"/usr/lib64/python2.7/runpy.py\", line 176, in run_module\n    fname, loader, pkg_name)\n  File \"/usr/lib64/python2.7/runpy.py\", line 82, in _run_module_code\n    mod_name, mod_fname, mod_loader, pkg_name)\n  File \"/usr/lib64/python2.7/runpy.py\", line 72, in _run_code\n    exec code in run_globals\n  File \"/tmp/ansible_replace_payload_FUlN7y/ansible_replace_payload.zip/ansible/modules/files/replace.py\", line 302, in <module>\n  File \"/tmp/ansible_replace_payload_FUlN7y/ansible_replace_payload.zip/ansible/modules/files/replace.py\", line 272, in main\n  File \"/usr/lib64/python2.7/re.py\", line 162, in subn\n    return _compile(pattern, flags).subn(repl, string, count)\n  File \"/usr/lib64/python2.7/re.py\", line 275, in filter\n    return sre_parse.expand_template(template, match)\n  File \"/usr/lib64/python2.7/sre_parse.py\", line 802, in expand_template\n    raise error, \"invalid group reference\"\nsre_constants.error: invalid group reference\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}

I even tried the below:

   replace: '\g\1 >2/dev/null'
   replace: '\g<1> >2/dev/null'
   replace: '\1 >2/dev/null'

But none of them helped.

Upvotes: 1

Views: 2258

Answers (1)

franklinsijo
franklinsijo

Reputation: 18300

The error was: sre_constants.error: invalid group reference

You have not defined any group in your regexp, but the replace is looking for the first capturing group \1.

Define groups within paranthesis (), the regexp must be '(tar.+)'

And the task would look like,

- name: Suppress tar errors
  replace:
    path: "/tmp/test.sh"
    regexp: '(tar.+)'
    replace: '\1 >2/dev/null'

Upvotes: 1

Related Questions