Visudo with Ansible

How can we construct and validate a dynamic sudoers file using Ansible?

Salle J Ingle
locusinnovations.com
2 min readMar 8, 2018

--

By using some Jinja2 conditionals and Ansible variables, let’s piece one together.

Here is my auth.yml playbook (the end result) referencing the auth_vars.yml file and doing a standard loop against the user and group item variables:

Screen Shot 2018-03-07 at 11.38.32 PM

auth.yml playbook

Next is a simple sudoers.j2 Jinja2 template that will be copied into the /etc/sudoers.d/ directory and become our custom sudoers file.

Members of the ‘admins’ group will always have root privileges, while members of ‘developers’ will only have root privileges on their own dev environments but nothing else.

Screen Shot 2018-03-07 at 11.36.57 PM

sudoers.j2 template

In my last blog, I covered a few different ways to reference and make use of some custom Ansible variables. In the sudoers.j2 file above, I am referencing the server ROLE as

which is a custom variable I have defined based on the EC2 instance tag. You could use any variation of conditionals based on Ansible variables here that work for your use case.

And lastly, here is my auth_vars.yml variable file that we are referencing and looping through in the auth.yml playbook:

Screen Shot 2018-03-07 at 11.36.12 PM

auth_vars.yml var_file

I hope this helps save someone else a little time! Let me know if you found this helpful or have any tips, suggestions or questions in the comments below!

--

--

Salle J Ingle
locusinnovations.com

AWS Solutions Architect trying to keep up with the singularity while striving to maintain a work-life balance. https://locusinnovations.com