Visudo with Ansible
How can we construct and validate a dynamic sudoers file using Ansible?
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:
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.
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
ansible_local.aws.ROLE == "dev"
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:
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!