且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Ansible 中使用正则表达式?

更新时间:2023-09-02 15:58:10

除了尝试将 securitysystem 匹配的错误之外,您不需要对任一参数中的双引号或 replace 参数中的美元符号进行转义(否则反斜杠将被插入到文件中):

On top of the mistake in trying to match security with system, you don't need to escape the double quotes in either of the arguments or the dollar sign in the replace argument (otherwise the backslash will be inserted into the file):

- name: disable auto updates
  replace:
    dest: /etc/apt/apt.conf.d/50unattended-upgrades
    regexp: '(?:[ \t]*"\${distro_id}:\${distro_codename}-system";)'
    replace: '//  "${distro_id}:${distro_codename}-system";'

并且您可以使用 lineinfile 模块获得相同的结果(这使代码更具可读性,恕我直言):

And you can achieve the same result using lineinfile module (which makes code a bit more readable, imho):

- name: disable auto updates
  lineinfile:
    dest: /etc/apt/apt.conf.d/50unattended-upgrades
    regexp: '"\${distro_id}:\${distro_codename}-system"'
    line: '//  "${distro_id}:${distro_codename}-system";'