0

I create a playbook that will harden my linux servers. Part of the process is to replace the umask in the default profiles. So, I have created this task:

- name: Change the umask for default profiles
  replace:
    path: "{{ profile_file }}"
    regexp: "(\s+)umask"
    replace: "\1 027"
  loop:
    - /etc/profile
    - /etc/bashrc
  loop_control:
    loop_var: profile_file

The problem with it is that it's idempotence is not maintained. Everytime I run the task it will replace the umask even if it's the correct one. If I remove the (\s+), then the umask is written at the start of the line, not in the correct place, which is not an functional issue of course, but it breaks the readability of the file.

So, what I want to do is this:

regexp: "(\s+)umask 002"
replace: "<something> 027"

where will give me only the umask with the whitespaces and then add the 027. I am really weak in RegExps and I know nothing about regex in Python, so any help would be appreciated.

Peter
  • 802
  • 2
  • 10
  • 23

1 Answers1

2

Try using https://regex101.com wich is an excellent tool for learning/debugging regex.

Ansibles documentation states the following in regards to the capture groups on the replace line: The string to replace regexp matches. May contain backreferences that will get expanded with the regexp capture groups if the regexp matches. If not set, matches are removed entirely.

It should be possible, but your statement from the question (\s+)umask matches any whitespace, which you capture in group 1, and umask. So the replace line will effectively only contain the whitespaces from capture group one plus 027.

Most likely you want to do it like that (\s+umask).*, which captures any whitespace and umask into capture group 1. On the replace line you can than use \1 027. Be careful .* matches the whole rest of the line. It may be that this is not what you intend to do.

Although it is not part of the question, I think it would be good to specify umask in 4 digits instead of three.

The regexp could look like that, to be very specific for that use-case: regexp: (\s+umask\s+)([0-7]{4}|[0-7]{3}) replace: \1 0027

hargut
  • 3,848
  • 6
  • 10