Home > Net >  Ansible: Replace with regex
Ansible: Replace with regex

Time:08-28

I'm trying to replace a line in the file with Ansible replace module and parameter regex, which has a line password required pam_allow.so with password requisite pam_deny.so

- hosts: 127.0.0.1
  tasks:
  - name: replacing string
    replace:
      path: /var/log/common-password
      regexp: '(^password\s)(required\s)(pam\w_allow\.so(.*)$'
      replace: 'password requisite   pam_deny.so' 
PLAY [127.0.0.1] *******************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************************
ok: [127.0.0.1]

TASK [replacing string] ************************************************************************************************************************
ok: [127.0.0.1]

PLAY RECAP *************************************************************************************************************************************
127.0.0.1                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

Expected result : password requisite pam_deny.so should replace password required pam_allow.so

CodePudding user response:

The question isn't reproducible.
Thanks for @U880D for clearing it.
There is no need for brackets, just match the white spaces using \s with which means one or more white spaces, then skip the dot with \,see https://regexr.com/6sot0

regexp: '^password\s required\s pam_allow\.so'

CodePudding user response:

Based on your description and Zeitounator's given comment about regex101, I've found the following minimal reproducible example producing the requested result.

Config file login (annot. as usually used under /etc/pam.d/)

auth       substack     system-auth
auth       include      postlogin
account    required     pam_nologin.so
account    include      system-auth
password   include      system-auth

password   required     pam_allow.so

Test playbook replace.yml

---
- hosts: localhost
  become: false
  gather_facts: false

  tasks:

  - name: Replace allow to deny
    replace:
      path: login
      regexp: '^password\s required\s pam\w*_allow\.so$'
      replace: 'password   required     pam_deny.so'
      backup: true

resulting into a changed config file

...
password   required     pam_deny.so
  • Related