I want to change sudo session timeout according to this answer. I can edit ordinary file:
lineinfile:
path: /etc/sudoers
regexp: ^Defaults env_reset
line: Defaults env_reset,timestamp_timeout=60
But in first line of my /etc/sudoers
written: # This file MUST be edited with the 'visudo' command as root.
How to deal with it?
P.S.
Despite the fact that the short answer is yes, one must read Konstantin Suvorov answer about right way to do it with lineinfile
and very interesting techraf answer about possible pitfalls on this way
While this answer defines things correctly and this one provides a mitigation to potential problems, let's look at your code.
You ask Ansible to (potentially) replace the line defined in the following way:
This is clearly a bad practice and if repeated for a parameter other than
Defaults
insudoers
file, it is likely to cause a critical problem.Generally
Defaults
is the configuration parameter andenv_reset
is one of possible values.You cannot assume that the actual configuration file will always contain
^Defaults env_reset
string.If there was a different value set, the regexp wouldn't match and you'd end up adding a second line starting with
Defaults
.So the proper way to use
lineinfile
is to useregexp
argument to match only the configuration parameter, not its value. In your case:The other potential pitfall is that
sudoers
contain sections which should be written in proper order. If the file you modify does not contain the line specified by the regular expression,lineinfile
will add a new line to the end of the file, where it might get ignored, or result in an error (but that should be discovered by validation), and most likely cause confusion if human looked at the file later. So it might be wise to specifyinsertafter
orinsertbefore
.It's safe if you've tested the syntax to be correct.
The point of encouraging
visudo
is to prevent someone from locking themselves out from administering a system by creating an invalid/etc/sudoers
, whether by a typo or a thinko.When you're using Ansible to perform an edit, you can test the code performing that edit to do the right thing with your actual config files, environment, and version of
sudo
before you roll it out. Thus, the concerns about people making a typo or a syntax error by hand aren't immediately relevant.There's a safenet option for such cases:
validate
.If you look at the examples section of lineinfile module, you'll see exactly what you need:
I think what you are missing is that in order to edit
/etc/sudoers
you need sudo-access. To do this in Ansible, you just need to add the become flag.Instead of directly editing the
/etc/sudoers
you can place your desired setting into the/etc/sudoers.d
directory like this: