DenCowboy
DenCowboy

Reputation: 15116

Can not make replace working in Ansible

I try to replace these lines:

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

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

By:

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

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

My playbook looks like this:

  - 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

Updated but also not working for me:

  - 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

What am I doing wrong?

Upvotes: 2

Views: 616

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627380

Replacement patterns are literal strings except for backreferences. Do not use regex patterns there.

Use

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

And as for the second replacement:

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

Here, the (...) in the regex patterns define capturing groups and \1 in the replacement refers to these captured parts. Backreferences allow us to avoid repeating literal strings that are used in the regex pattern in the replacement pattern. \s+ matches 1 or more occurrences of whitespace chars. You may see how the second regex works here.

Upvotes: 1

Related Questions