Skip to main content Logo

Quis custodiet ipsos custodes?
Home | About | All pages | Cluster Status | RSS Feed | Gopher

Ansible - sudoers safety and sanity checking in playbook

Published: 23-03-2013 | Author: Remy van Elst | Text only version of this article

❗ This post is over nine years old. It may no longer be up to date. Opinions may have changed.

Using Ansible to manage the /etc/sudoers file is fine, except when you have a syntax error in your template. This method helps you to only deploy a correct sudoers file.

I'm developing an open source monitoring app called Leaf Node Monitoring, for windows, linux & android. Go check it out!

Consider sponsoring me on Github. It means the world to me if you show your appreciation and you'll help pay the server costs.

You can also sponsor me by getting a Digital Ocean VPS. With this referral link you'll get $100 credit for 60 days.

I manage the sudo config (/etc/sudoers/) via Ansible. My sudo playbook creates an admin group, adds me to that admin group, and sets some variables in /etc/sudoers/. I do not have a sudoers template file, because I created the playbook at a client which has various different sudoers files, which they do not want to have changed ,because of different nagios checks that needed sudo on different hosts. However, if you start of clean, then a template file for /etc/sudoers is the best choice.

This is the playbook:

      - hosts: all
        sudo: True
        user: remy
        connection: ssh # or paramiko

          distro: {{ ansible_distribution }}
          pkg_mgr: {{ ansible_pkg_mgr }}
          pbname: {{ inventory_hostname }}


        - name: Copy sudoers file for safety
          command: cp -f /etc/sudoers /etc/sudoers.tmp

        - name: Create sudoers file backup
          command: cp -f /etc/sudoers /etc/sudoers.bak

        - name: Create admins group
          group: name=admins system=yes state=present

        - name: make sure we can sudo as admin group
          lineinfile: dest=/etc/sudoers.tmp state=present regexp='^%admin' line='%admin ALL=(ALL) ALL'

        - name: also make sure ssh-agent works via sudo
          lineinfile: dest=/etc/sudoers.tmp state=present regexp='^Defaults env_keep\+\=SSH_AUTH_SOCK' line='Defaults env_keep+=SSH_AUTH_SOCK'

        - name: Final sudoers file check
          shell: visudo -q -c -f /etc/sudoers.tmp && cp -f /etc/sudoers.tmp /etc/sudoers

By using the temp file we make sure we don't have any syntax errors and lock ourselves out of machines, needing to use ILO/DRAC to reset passwords and such. Been there, done that, not funny at all.

Tags: ansible , configuration-management , deployment , python , sudo , sudoers , tutorials , visudo