使用 Ansible 在正则表达式匹配行的末尾附加一个字符串

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

只要我在文件中找到 tar 命令,我就希望在同一行的末尾附加 2>/dev/null

因此,如果 /tmp/test.sh 文件有 tar -cf test.tar /myfolder 条目,那么它应该更改为 tar -cf test.ta /myfolder 2>/dev/null

下面是我的剧本:

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

但是我得到以下错误:

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}

我什至尝试了以下方法:

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

但其中 none 有帮助。

The error was: sre_constants.error: invalid group reference

您尚未在 regexp 中定义任何组,但 replace 正在寻找第一个捕获组 </code>。</p> <p>在括号 <code>() 中定义组,正则表达式必须是 '(tar.+)'

任务看起来像,

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