Troubleshooting Sudoers.d Syntax Errors: Why Directives Work in /etc/sudoers But Fail in /etc/sudoers.d


3 views

Many Linux administrators encounter a puzzling situation where sudo directives work perfectly when placed in /etc/sudoers but fail with syntax errors when moved to /etc/sudoers.d/. The specific error message typically appears as:

>>> /etc/sudoers.d/custom_rule:1: syntax error near line 1 <<<

Files in /etc/sudoers.d/ have stricter formatting requirements than the main sudoers file. Here are the key differences:

  • The file must have the correct permissions (0440)
  • The file must not contain a trailing newline
  • The file should be named without extensions (.conf, .sudo, etc.)

Here's the correct way to create a sudoers.d file for www-data:

# Create the file with correct permissions
sudo touch /etc/sudoers.d/www-data-script
sudo chmod 440 /etc/sudoers.d/www-data-script

# Add content using visudo (recommended)
sudo visudo -f /etc/sudoers.d/www-data-script

When using visudo, add this content (note no trailing newlines):

www-data ALL=(ALL) NOPASSWD: /path/to/script.sh

After creating the file, always validate it:

# Check syntax
sudo visudo -c -f /etc/sudoers.d/www-data-script

# Test the rule
sudo -u www-data sudo -l

For multiple commands, use this format:

www-data ALL=(ALL) NOPASSWD: /path/to/script1.sh, /path/to/script2.sh

Or for better organization:

# Allow script directory
www-data ALL=(ALL) NOPASSWD: /usr/local/scripts/*

When configuring sudo permissions, it's common to use /etc/sudoers.d/ for modular configuration. However, some users encounter syntax errors when placing directives here, even though the same rules work fine in /etc/sudoers.

The key difference is that files in /etc/sudoers.d/ must follow stricter formatting rules. A bare directive like:

www-data ALL=(ALL) NOPASSWD: /path/to/script.sh

may trigger syntax errors because the file lacks proper structure.

Each file in /etc/sudoers.d/ should be a complete configuration snippet. Here's the proper format:

# Allow www-data to run specific script without password
Defaults:www-data !authenticate
www-data ALL=(ALL) NOPASSWD: /path/to/script.sh

After creating your file, always verify it with:

sudo visudo -c -f /etc/sudoers.d/yourfile

This checks for syntax errors without modifying anything.

  • File permissions must be 0440: sudo chmod 440 /etc/sudoers.d/yourfile
  • File must be owned by root: sudo chown root:root /etc/sudoers.d/yourfile
  • No file extension (like .conf) unless specifically configured in sudoers

For multiple commands, use this format:

# Web server sudo permissions
Cmnd_Alias WEB_SCRIPTS = /path/to/script1.sh, /path/to/script2.sh
www-data ALL=(ALL) NOPASSWD: WEB_SCRIPTS

If issues persist, check:

# Check main sudoers includes
grep -r "includedir" /etc/sudoers

# Verify file is being read
sudo -l -U www-data