Ansible – add user to sudo
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
lineinfile:
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
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
lineinfile:
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
lineinfile:
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
lineinfile:
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! :)
Thanks Wojciech !
Nice example I will inspired from to config my own sudoers groups.
Thanks !
Thanks!!!
thank you nice examples!
Very nice example. It has saved me a lot of time
There is a small mistake in the last task, you mean
line: „includedir /etc/sudoers.d”
and not
line: „#includedir /etc/sudoers.d”
(remove the '#’ before included)
No, you need # in „#includedir /etc/sudoers.d”
whata fuck is %s ??