无法在Ansible中进行替换

时间:2018-08-11 10:31:52

标签: regex ansible

我尝试替换这些行:

## Allows people in group wheel to run all commands
%wheel  ALL=(ALL)       ALL

## Same thing without a password
# %wheel        ALL=(ALL)       NOPASSWD: ALL

通过:

## Allows people in group wheel to run all commands
# %wheel  ALL=(ALL)       ALL

## Same thing without a password
%wheel        ALL=(ALL)       NOPASSWD: ALL

我的剧本看起来像这样:

  - replace:
      path: /etc/sudoers
      regexp: '^%wheel\s\sALL=\(ALL\)\s\s\s\s\s\s\sALL$'
      replace: '^#\s%wheel\s\sALL=\(ALL\)\s\s\s\s\s\s\sALL$'
    become: yes

  - replace:
      path: /etc/sudoers
      regexp: '^#\s%wheel\s\s\s\s\s\s\s\sALL=\(ALL\)\s\s\s\s\s\s\sNOPASSWD:\sALL'
      replace: '^%wheel\s\s\s\s\s\s\s\sALL=\(ALL\)\s\s\s\s\s\s\sNOPASSWD:\sALL'
    become: yes

已更新但对我不起作用:

  - replace:
      path: /etc/sudoers
      regexp: '^%wheel\s\sALL=\(ALL\)\s\s\s\s\s\s\sALL$'
      replace: '# %wheel  ALL=(ALL)       ALL'
    become: yes

  - replace:
      path: /etc/sudoers
      regexp: '^#\s%wheel\s\s\s\s\s\s\s\sALL=\(ALL\)\s\s\s\s\s\s\sNOPASSWD:\sALL'
      replace: '# %wheel    ALL=(ALL)   NOPASSWD: ALL'
    become: yes

我在做什么错了?

1 个答案:

答案 0 :(得分:1)

替换模式是文字字符串,但反向引用除外。不要在那里使用正则表达式模式。

使用

regexp: '^(%wheel\s+ALL=\(ALL\)\s+ALL)$'
replace: '# \1'

第二次替换:

regexp: '^#\s+(%wheel\s+ALL=\(ALL\)\s+NOPASSWD:\s+ALL)'
replace: '\1'

在这里,正则表达式模式中的(...)定义了捕获组,而替换中的\1则引用了这些捕获的部分。使用反向引用,我们可以避免在替换模式中重复使用正则表达式模式中使用的文字字符串。 \s+匹配1个或多个出现的空白字符。您可能会看到how the second regex works here

相关问题