Ansible – add user to sudo

Ansible logo

I’m using Ansible for some time. Great tool! Now for some example; allow user to use sudo.

Many tasks samples look’s like this (tabs/spaces cut by dummy WP editor! sorry!):

- name: Ensuring that wheel is able to use sudo without password
path: /etc/sudoers
regexp: '^%wheel'
line: '%wheel ALL=(ALL) NOPASSWD: ALL'
validate: 'visudo -cf %s'

If it it’s not, they hack the /etc/sudoers file. Then they add a shell user as a member of wheel group:

- name: Setup Ansible User
name: ansible
comment: Ansible Management User
group: wheel

But we wish that new user had’s only it’s own group. Or they add a shell user to the main /etc/sudoers file:

- name: Add user to sudoers file
path: /etc/sudoers
regexp: '^ansibleuser'
line: 'ansibleuser ALL=(ALL) NOPASSWD: ALL'
validate: 'visudo -cf %s'

It is true, that the lineinfile module’s validate option will NOT write any changes to the path file if the result of validation command will not be positive. But why to hack the /etc/sudoers every time?

I prefare to create single file for each user, like so:

- name: Add user "ansibleuser" to sudo
path: /etc/sudoers.d/ansibleuser
line: 'ansibleuser ALL=(ALL) NOPASSWD: ALL'
state: present
mode: 0440
create: yes
validate: 'visudo -cf %s'

That’s all. We can make sure, that the includedir in sudoers is in /etc/sudoers file (this is one time hack if not present):

- name: Set includedir in sudoers
dest: /etc/sudoers
line: "#includedir /etc/sudoers.d"
state: present
validate: "/usr/sbin/visudo -cf %s"

That is easy to manage; both by hand and via automation tools like Ansible. Feel free to comment! :)

Dodaj komentarz

Twój adres email nie zostanie opublikowany. Pola, których wypełnienie jest wymagane, są oznaczone symbolem *

This site uses Akismet to reduce spam. Learn how your comment data is processed.