How to Add a User to Sudoers in Ansible with Examples

How to Add a User to Sudoers in Ansible

Managing sudo access across servers manually can be tedious and risky. A small typo in the /etc/sudoers file could lock you out of root access. That’s why automating this task with Ansible is a smarter choice.

In this guide, you’ll learn three safe and effective ways to add a user to the sudoers list using Ansible modules like user, lineinfile, and copy. You’ll also learn how to verify sudo access programmatically.

Let’s dive into each method with examples.

Methods to Add a User to Sudoers in Ansible

We’ll explore three approaches:

MethodBest Use CaseBenefits
user moduleSimple group-based sudo accessEasy to apply, minimal risk
lineinfileDirectly edit /etc/sudoers fileFine-tuned control
copy moduleDeploy standardized sudoers configurationIdeal for infrastructure at scale

Method 1: Using the Ansible user Module

In this method, we will use the Ansible user module to create a new user and add them to the sudo group, which typically grants sudo access.

Here’s an Example:

---
- name: Add user to sudo group using Ansible user module
  hosts: all
  become: true
  tasks:
    - name: Create a new user 'devuser'
      ansible.builtin.user:
        name: devuser
        state: present

    - name: Add 'devuser' to the sudo group
      ansible.builtin.user:
        name: devuser
        groups: sudo
        append: true

The above configuration creates a new user devuser and adds it to the sudo group. The append: true option ensures that the user is added to the group without removing them from existing groups.

🔎 Note: On RHEL/CentOS, replace sudo with wheel.

Method 2: Using the lineinfile Module

If you want to directly add a user to the sudoers file, you can use the lineinfile module. This method is useful when you need to specify custom sudo permissions.

Playbook Example:

---
- name: Add user to sudoers file using lineinfile module
  hosts: all
  become: true
  tasks:
    - name: Add 'devuser' to sudoers file
      ansible.builtin.lineinfile:
        path: /etc/sudoers
        line: 'devuser ALL=(ALL:ALL) NOPASSWD:ALL'
        validate: 'visudo -cf %s'

This playbook uses the lineinfile module to add a line to the /etc/sudoers file. The validate option runs visudo to check the syntax before making changes, preventing errors.

⚠️ Warning: Always use validate to avoid syntax errors that could lock you out.

Method 3: Using the copy Module

This method uses the copy module to deploy a custom sudoers configuration file. It’s useful for environments where you want standardized sudo configurations across multiple servers.

Playbook Example:

---
- name: Add user to sudoers using copy module
  hosts: all
  become: true
  tasks:
    - name: Copy custom sudoers file
      ansible.builtin.copy:
        src: files/my_sudoers
        dest: /etc/sudoers.d/devuser
        mode: '0440'

Now, create a my_sudoers file inside the files directory with the following content:

devuser ALL=(ALL:ALL) NOPASSWD:ALL

This playbook copies a custom sudoers configuration file to /etc/sudoers.d/devuser. The file permissions are set to 0440 to ensure it is read-only for security purposes. This configuration also allows users to run commands without providing a sudo password.

Verify the Sudo Access

To verify if a user has sudo access using Ansible, you can create a simple playbook that checks if the user can execute a command with elevated privileges using become: true.

Let’s see the below example playbook:

---
- name: Verify if a user has sudo access
  hosts: all
  become: true
  become_user: devuser
  tasks:
    - name: Check sudo access for the user
      ansible.builtin.command: whoami
      register: result
      ignore_errors: true

    - name: Display sudo access result
      debug:
        msg: "The user has sudo access."
      when: result.stdout == "root"

    - name: Display no sudo access result
      debug:
        msg: "The user does NOT have sudo access."
      when: result.stdout != "root"

Explanation:

  • become_user: Switches to the specified user (devuser in this example).
  • command: Executes the whoami command to check the current user identity.
  • debug: Outputs whether the user has sudo access based on the result.

Now, run the above playbook.

 # ansible-playbook verify_sudo_access.yml

If the user has sudo access, you will get the following output:

TASK [Display sudo access result] **********************************************
ok: [localhost] => {
    "msg": "The user has sudo access."
}

If the user does not have sudo access, you should see the following output:

TASK [Display no sudo access result] *******************************************
ok: [localhost] => {
    "msg": "The user does NOT have sudo access."
}

Comparison Table: Which Method Should You Use?

Use CaseRecommended MethodNotes
Basic sudo access via groupsuser moduleEasiest and safest
Add custom sudo rule (NOPASSWD)lineinfileUse with validate: to prevent lockouts
Deploy policy across all nodescopy moduleRequires file structure and permissions setup

Troubleshooting Tips

IssueFix
Syntax error in sudoersUse validate: 'visudo -cf %s' to pre-check configuration
Group doesn’t grant accessCheck if OS uses wheel instead of sudo
Permission denied on file copyEnsure mode: '0440' and become: true are used
Sudo verification failsTry using become_user and whoami task as shown above

Conclusion

With Ansible, you can manage sudo access in a reliable, repeatable, and secure way.

Whether you’re adding a single user to the sudo group or managing dozens of machines with custom policies, Ansible gives you the tools to automate user privilege management without risking manual errors.

🔒 Choose the method that fits your environment:

  • For quick group access, use the user module.

  • For custom rules, use lineinfile or copy.

  • Always verify access and validate changes using visudo.

FAQs

1. How do I safely edit the sudoers file with Ansible?

Use the lineinfile with the validate: 'visudo -cf %s' option to check the syntax before applying changes.

2. Can I conditionally add a user to sudoers in Ansible?

Yes, you can use when conditions to add users based on specific criteria or variables.

3. How can I verify if a user has sudo access using Ansible?

You can check group membership with the groups command or test sudo access using a simple command task like whoami with become: true.

About Hitesh Jethva

Experienced Technical writer, DevOps professional with a demonstrated history of working in the information technology and services industry. Skilled in Game server hosting, AWS, Jenkins, Ansible, Docker, Kubernetes, Web server, Security, Proxy, Iptables, Linux System Administration, Domain Name System (DNS), and Technical Writing.

View all posts by Hitesh Jethva