Search code examples
pythonunixansibleuser-management

Ansible: best practice for maintaining list of sudoers


In the documentation, there is an example of using the lineinfile module to edit /etc/sudoers.

- lineinfile: "dest=/etc/sudoers state=present regexp='^%wheel' line='%wheel ALL=(ALL) NOPASSWD: ALL'"

Feels a bit hackish.

I assumed there would be something in the user module to handle this but there doesn't appear to be any options.

What are the best practices for adding and removing users to /etc/sudoers?


Solution

  • That line isn't actually adding an users to sudoers, merely making sure that the wheel group can have passwordless sudo for all command.

    As for adding users to /etc/sudoers this is best done by adding users to necessary groups and then giving these groups the relevant access to sudo. This holds true when you aren't using Ansible too.

    The user module allows you to specify an exclusive list of group or to simply append the specified groups to the current ones that the user already has. This is naturally idempotent as a user cannot be defined to be in a group multiple times.

    An example play might look something like this:

    - hosts: all
      vars:
        sudoers:
          - user1
          - user2
          - user3
      tasks:
        - name: Make sure we have a 'wheel' group
          group:
            name: wheel
            state: present
    
        - name: Allow 'wheel' group to have passwordless sudo
          lineinfile:
            dest: /etc/sudoers
            state: present
            regexp: '^%wheel'
            line: '%wheel ALL=(ALL) NOPASSWD: ALL'
            validate: visudo -cf %s
    
        - name: Add sudoers users to wheel group
          user:
            name: "{{ item }}"
            groups: wheel
            append: yes
          with_items: "{{ sudoers }}"