Skip to main content

Raymii.org Logo (IEC resistor symbol) logo

Quis custodiet ipsos custodes?
Home | About | All pages | 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


Table of Contents


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.

If you like this article, consider sponsoring me by trying out a Digital Ocean VPS. With this link you'll get $100 credit for 60 days). (referral link)

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

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

        tasks:

        - 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