Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to edit /etc/sudoers with the Ansible "lineinfile" module?

Tags:

ansible

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

like image 927
El Ruso Avatar asked Oct 12 '17 23:10

El Ruso


People also ask

What is Lineinfile module in Ansible?

The lineinfile module provides the tools to define the context in which a line needs to be present by using the insertbefore and insertafter parameters. You can set these parameters to EOF or BOF, respectively, to place the configuration item at the end or at the beginning of the file.

What command can be used to safely edit the sudoers file?

As with the /etc/sudoers file itself, you should always edit files within the /etc/sudoers. d directory with visudo . The syntax for editing these files would be: sudo visudo -f /etc/sudoers.

What does the Lineinfile module do in Devops?

The Ansible lineinfile module Ansible lineinfile module is helpful when you want to add, remove, modify a single line in a file. You can also use conditions to match the line before modifying or removing using the regular expressions. You can reuse and modify the matched line using the back reference parameter.

How do I validate a sudoers file?

The answer is actually pretty easy, by using visudo; visudo has a flag that will perform a syntax check on the sudoers file. You can run this after deployment to ensure the syntax is correct. Another cool feature of visudo is you can tell it to check a specified file rather than the /etc/sudoers file.


1 Answers

There's a safenet option for such cases: validate.

The validation command to run before copying into place. The path to the file to validate is passed in via '%s' which must be present as in the example below. The command is passed securely so shell features like expansion and pipes won't work.

If you look at the examples section of lineinfile module, you'll see exactly what you need:

# Validate the sudoers file before saving
- lineinfile:
    path: /etc/sudoers
    state: present
    regexp: '^%ADMIN ALL='
    line: '%ADMIN ALL=(ALL) NOPASSWD: ALL'
    validate: '/usr/sbin/visudo -cf %s'
like image 158
Konstantin Suvorov Avatar answered Sep 18 '22 22:09

Konstantin Suvorov