Commands.page Logo

Include External Files in Ubuntu Sudoers Configuration

Managing sudo privileges in Ubuntu is more efficient when configurations are modular. This article confirms that you can include external files in the main sudoers configuration and outlines the standard directory structure and commands required to implement this safely without risking administrative access.

Yes, External Files Are Supported

Ubuntu supports including external configuration files within the main /etc/sudoers file. This feature allows system administrators to manage permissions for specific users or applications in separate files rather than editing the core configuration directly. By default, Ubuntu is preconfigured to look for these additional files in a specific directory.

The #includedir Directive

The mechanism for including external files is the #includedir directive. In a standard Ubuntu installation, the main /etc/sudoers file already contains the following line near the end:

#includedir /etc/sudoers.d

This directive tells the sudo system to read all valid files located within the /etc/sudoers.d/ directory. You do not need to add this line manually unless it was previously removed. Any file placed in this directory will be processed as part of the sudo configuration.

Creating and Editing External Files

To add new sudo rules, create a new file inside /etc/sudoers.d/. It is critical to use the visudo command to edit these files rather than a standard text editor. visudo checks for syntax errors before saving, preventing you from locking yourself out of sudo access.

To edit a specific file within the directory, use the following command:

sudo visudo -f /etc/sudoers.d/filename

Replace filename with a descriptive name, such as the username or application name. Inside this file, you can add standard sudoers rules. For example, to allow a user named deploy to run specific commands without a password, you would add:

deploy ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart nginx

File Permissions and Ownership

For security reasons, sudo will ignore files in /etc/sudoers.d/ that do not have the correct permissions. Every file in this directory must be owned by the root user and should not be writable by anyone else.

Set the correct ownership and permissions using these commands:

sudo chown root:root /etc/sudoers.d/filename
sudo chmod 0440 /etc/sudoers.d/filename

If the permissions are too open, such as 0644, sudo will refuse to read the file and may issue a warning during execution.

Verifying the Configuration

Before relying on the new configuration, verify that the syntax is correct across all sudoers files. Run the following command to check the main configuration and all included files:

sudo visudo -c

If the output returns “parsed ok”, the configuration is valid. If there are syntax errors, visudo will indicate the file and line number where the issue occurred, allowing you to fix it before it causes system issues.