Ansible: Replacing text in file complex example

From Wiki
Revision as of 20:44, 13 March 2024 by Ebasso (talk | contribs) (Created page with "I need to replace umask into /etc/profile from: if [ $UID -gt 199 ] && [ "`/usr/bin/id -gn`" = "`/usr/bin/id -un`" ]; then umask '''022''' else umask '''027''' fi to if [ $UID -gt 199 ] && [ "`/usr/bin/id -gn`" = "`/usr/bin/id -un`" ]; then umask '''002''' else umask '''022''' fi Below, an ansible script that do this: <nowiki> - name: Verify existence of file /etc/profile locally hosts: localhost gather_facts: false vars: myfile: /etc/...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

I need to replace umask into /etc/profile from:

if [ $UID -gt 199 ] && [ "`/usr/bin/id -gn`" = "`/usr/bin/id -un`" ]; then
  umask 022
else
  umask 027
fi

to

if [ $UID -gt 199 ] && [ "`/usr/bin/id -gn`" = "`/usr/bin/id -un`" ]; then
  umask 002
else
  umask 022
fi


Below, an ansible script that do this:

- name: Verify existence of file /etc/profile locally
  hosts: localhost
  gather_facts: false
  vars:
    myfile:  /etc/profile
  tasks:
    - name: "Read {{ myfile }}"
      ansible.builtin.slurp:
        src: "{{ myfile }}"
      register: etc_profile

    - name: Convert file content to string
      ansible.builtin.set_fact:
        profile_txt: "{{ etc_profile['content'] | b64decode }}"

    - name: Change to 'umask_002' between then_else
      ansible.builtin.replace:
        path: "{{ myfile }}"
        regexp: '(then\s+)umask\s\d+(\s+else)'
        replace: '\1umask 002\2'
      when: profile_txt | regex_search('then\s+umask\s002\s+else') is none

    - name: Check 'umask 022' between else_fi
      ansible.builtin.replace:
        path: "{{ myfile }}"
        regexp: '(else\s+)umask\s\d+(\s+fi)'
        replace: '\1umask 022\2'
      when: profile_txt | regex_search('else\s+umask\s022\s+fi') is none

See also