Ansible regexp match parenthesis

2019-08-20 05:02发布

I need to match a string NAME ALL=(ALL) NOPASSWD: ALL However I'm getting stuck with the parenthesis.

I used a website to help me build the expression but am unable to figure it out. Thusfar I got: \sNAME\sALL=\(ALL\)\s\s\s\s\s\s\sNOPASSWD:\sALL However that doesn't get the parenthesis signs... Also I use a ton of \s, which I'm sure there is a better way for?

I'm using the Ansible Lineinfile module to remove the line. All help is appreciated, thank you!

EDIT: Just in case, my little playbook added, might be that I do something wrong there:

Hi.

Yeah it matches in all those generators, but for whatever reason I can't get it working in my playbook, am I such an idiot or?

- hosts: all
  become: true
  tasks:
  - name: Remove user
    lineinfile:
      dest: /etc/sudoers
      regexp: '^.*NAME.*$'
      state: 'absent'

标签: regex ansible
1条回答
成全新的幸福
2楼-- · 2019-08-20 05:11
  • You need to escape ( and ) with \;
  • a space in the string is matched by a space in the regular expression;
  • you can write the expression between ^ and $ (or just one of them) to be sure it matches only the exact line (not a commented-out line, for example).

To match the exact line from the question:

regexp: '^NAME ALL=\(ALL\)       NOPASSWD: ALL$'

You can also use \s with a multiplier to match a random-length whitespace, for example before NOPASSWD string:

regexp: '^NAME ALL=\(ALL\)\s*NOPASSWD: ALL$'

BUT

You are trying to modify /etc/sudoers ― take some time to read Is it safe to edit /etc/sudoers with the Ansible "lineinfile" module? and particularly this answer.

查看更多
登录 后发表回答