Ansible: Replacing text in file complex example
I need to replace umask values 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: Replacing text in file complex example
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