Editing /etc/sudoers is one of the few routine admin tasks that can end your session permanently: a stray character, a save, and the next sudo call refuses everything on a host you can only reach as a non-root user. The protection is visudo, which parses before it installs, and the discipline is to never test a rule from the only shell you have. This guide covers the sudoers rule grammar, drop-in files under /etc/sudoers.d/, aliases, the Defaults settings that matter, and the part most guides skip — proving that the rule you wrote is the rule sudo actually applies. The worked example is a deploy user granted exactly three commands, and nothing else.
What you’ll accomplish
- Edit sudoers through
visudoso a syntax error can never reach the live policy file. - Grant a
deployaccount exactly three commands via a drop-in in/etc/sudoers.d/, with no password prompt and no path to a root shell. - Read the rule grammar —
user host=(runas) NOPASSWD: commands— well enough to audit someone else’s file. - Verify the grant with
sudo -l -U deployand a negative test, rather than trusting the file you just wrote. - Recognise rules that look limited but hand out root, and know the recovery path if you do lock yourself out.
Prerequisites
- Root or existing sudo access on the host, plus a second terminal you can keep open. That second session is the single most useful safety measure in this guide.
- sudo 1.8 or newer (
sudo -V). Drop-in directories work throughout;@includediras a synonym for#includedirarrived in 1.9.1. Both forms work in current versions — older sudo only understands#includedir. - Know your admin group. Debian and Ubuntu put administrators in
sudo; RHEL, Rocky, AlmaLinux and Fedora usewheel. The rules are written the same way, only the group name differs. - Know your real binary paths.
command -v systemctlreturns/usr/bin/systemctlon current distributions. Older layouts and some minimal images differ, and sudoers rules are written against the actual path. - A service account (
deploybelow) that already exists. Creating it is out of scope here.
How it works
Every sudo invocation is a fresh policy decision. sudo reads /etc/sudoers, follows the #includedir /etc/sudoers.d line at the bottom, reads each drop-in in sorted order, and evaluates the whole assembled policy against three questions: who is asking, on which host, and to run what as whom.
The rule that catches people is the matching order. Firewalls, ACLs and routing tables have trained everyone to expect first-match-wins. sudoers is the opposite: when several rules match, the last one wins — and “last” means last in parse order, not most specific. A tight NOPASSWD grant in 10-deploy is silently cancelled by a broad rule in 90-ops, because 90-ops sorts later.
A rule reads as one sentence with four slots:
deploy ALL=(root) NOPASSWD: /usr/bin/systemctl restart app.service
| | | | |
who host runas tag command
ALL in the host slot means “this rule applies on every host” — useful when one sudoers file is distributed to a fleet, and harmless on a single machine. (root) is the runas slot: the identity the command is allowed to become. NOPASSWD: is a tag that switches off authentication for the commands after it. The command must be a fully qualified path; a bare systemctl is a syntax error, which is the one place sudoers protects you by default.
/etc/sudoers.d/ exists so that packages and configuration management can each own a file without fighting over one shared document. Two filename rules govern it, and both fail silently: sudo ignores any file whose name contains a dot or ends in a tilde. 30-deploy.conf and 30-deploy~ are not read. There is no warning — the file simply does not exist as far as sudo is concerned. That rule is what keeps .rpmsave, .dpkg-dist and editor backups from becoming live policy, and it is also the most common reason a drop-in “does nothing”.
Step-by-step
1. Open a root shell and leave it open. Do this before touching anything. If you break sudo, this session is how you fix it — it is already authenticated and does not re-read sudoers.
sudo -i
root@web01:~#
Leave that terminal alone. Do the rest of the work in a second one.
2. Confirm the includedir line exists. Everything below depends on /etc/sudoers actually pulling in the drop-in directory. It is present by default on Debian, Ubuntu and RHEL, but a hand-edited sudoers may have lost it.
sudo grep -n 'includedir' /etc/sudoers
28:#includedir /etc/sudoers.d
That # at the start of the line is not a comment — in sudoers, #includedir is a directive. Do not “clean it up”. If the line is missing, add it with visudo, at the bottom, so drop-ins are parsed last.
3. Resolve the real command paths. Write rules against what the shell actually resolves, not what you remember.
command -v systemctl journalctl
/usr/bin/systemctl
/usr/bin/journalctl
4. Create the drop-in with visudo -f. Never open a sudoers file in a plain editor. visudo -f edits a specific file, locks it, parses it on save, and refuses to install anything that does not parse. Note the filename: 30-deploy, no extension, no dot.
sudo visudo -f /etc/sudoers.d/30-deploy
Enter this content:
# Commands the deploy account is allowed to run as root
Cmnd_Alias DEPLOY_CMDS = /usr/bin/systemctl restart app.service, \
/usr/bin/systemctl reload nginx.service, \
/usr/bin/journalctl --no-pager -u app.service -n 200
# Accounts that get them
User_Alias DEPLOYERS = deploy, ci
# No credential caching for these accounts: every call is checked
Defaults:DEPLOYERS timestamp_timeout=0
DEPLOYERS ALL=(root) NOPASSWD: DEPLOY_CMDS
On save, visudo parses the file before installing it. Silence means it parsed:
sudo: /etc/sudoers.d/30-deploy: parsed OK
Three things in that file are deliberate. The arguments are pinned: restart app.service is a different command from restart plus anything, so the grant cannot be pointed at nginx.service or --user-scoped units. --no-pager is not decoration: journalctl opens less on a terminal by default, and less will spawn a shell with !sh. Pinning --no-pager means the command has no pager to escape through. timestamp_timeout=0 disables the credential cache for these accounts — with NOPASSWD it changes nothing today, but it means a future rule that removes NOPASSWD starts prompting immediately instead of inheriting a warm 15-minute ticket.
5. Check the file mode. visudo sets this correctly; a file you copied in with Ansible or cp may not be. sudo refuses to read a drop-in that is group- or world-writable.
sudo ls -l /etc/sudoers.d/30-deploy
-r--r----- 1 root root 341 Jul 16 09:12 /etc/sudoers.d/30-deploy
6. Look for anything that matches later. This is the step almost everyone skips, and it is the one that decides what the policy actually is. Because the last match wins, a broad rule in a later-sorting file overrides everything you just wrote.
sudo grep -rn 'deploy\|DEPLOYERS\|%sudo\|%wheel' /etc/sudoers /etc/sudoers.d/
/etc/sudoers:31:%sudo ALL=(ALL:ALL) ALL
/etc/sudoers.d/30-deploy:12:DEPLOYERS ALL=(root) NOPASSWD: DEPLOY_CMDS
Here %sudo grants everything to members of the sudo group — harmless only because deploy is not in it. Confirm that rather than assume it:
id -nG deploy
deploy
Validate it works
The file parsing is not the test. The test is what sudo resolves.
Parse the whole policy, not just your file. visudo -c checks /etc/sudoers and every drop-in it includes, and exits non-zero on failure — which makes it usable in CI or a pre-deploy hook.
sudo visudo -c
/etc/sudoers: parsed OK
/etc/sudoers.d/30-deploy: parsed OK
Read back the resolved grant. sudo -l -U deploy asks sudo what deploy may do, after all files are merged and all overrides settled. This output is the answer — not the file you wrote.
sudo -l -U deploy
Matching Defaults entries for deploy on web01:
env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin,
timestamp_timeout=0
User deploy may run the following commands on web01:
(root) NOPASSWD: /usr/bin/systemctl restart app.service
(root) NOPASSWD: /usr/bin/systemctl reload nginx.service
(root) NOPASSWD: /usr/bin/journalctl --no-pager -u app.service -n 200
Three commands, (root), NOPASSWD on each, and no fourth line. If a broad rule matched later, you would see (ALL : ALL) ALL here instead — and that is the whole point of reading it back.
Run a positive test as the deploy account. -n makes sudo fail rather than prompt, so a hung test is a failed test.
sudo -u deploy sudo -n /usr/bin/systemctl restart app.service
(no output — exit status 0)
Run a negative test. A grant you have not tried to break is a guess. Ask for a command that is deliberately outside the list:
sudo -u deploy sudo -n /usr/bin/systemctl restart nginx.service
Sorry, user deploy is not allowed to execute '/usr/bin/systemctl restart nginx.service' as root on web01.
That refusal is the grant proving its own edge. Repeat it for sudo -n /bin/bash and for sudo -n /usr/bin/systemctl restart app.service --now — the argument pinning should refuse the last one too.
Troubleshooting
You broke sudoers and every sudo now fails. The symptom is total: sudo: parse error in /etc/sudoers near line 31 followed by sudo: no valid sudoers sources found, quitting. In order of preference: use the root shell you left open in step 1 and run visudo there. If you closed it, try pkexec visudo — polkit is a separate path to privilege and is unaffected by sudoers. If the root account has a password, su - works. Failing all of that, it is console access: reboot, edit the kernel command line to add init=/bin/bash, remount / read-write, and fix the file. The lesson is cheap in advance and expensive afterwards — keep the second session.
Your drop-in is ignored and sudo -l -U deploy shows nothing. Check the filename before anything else. Files containing a dot or ending in a tilde are skipped silently:
sudo ls -la /etc/sudoers.d/
-r--r----- 1 root root 341 Jul 16 09:12 30-deploy.conf
Rename it with no extension (mv /etc/sudoers.d/30-deploy.conf /etc/sudoers.d/30-deploy) and re-check sudo -l -U deploy. The same rule silently disables 30-deploy.bak, 30-deploy~ and anything Ansible left as 30-deploy.j2.
NOPASSWD is not taking effect — sudo still prompts. Your rule is correct and is being overridden by a later match. Because the last match wins, a file sorting after yours re-grants the same command with authentication on:
sudo grep -rn 'deploy' /etc/sudoers.d/ | sort
/etc/sudoers.d/30-deploy:12:DEPLOYERS ALL=(root) NOPASSWD: DEPLOY_CMDS
/etc/sudoers.d/90-ops:3:deploy ALL=(root) ALL
90-ops matches later, so its (password-requiring) terms replace yours. Fix the conflict rather than renumbering around it — remove the broad rule, or if it must stay, place your specific rule in a file that sorts after it. Renaming files to win an ordering race is a fragile habit; two people can play it, and the loser is whoever deploys second.
sudo: command not found for a command that plainly exists. secure_path replaces the caller’s PATH with a fixed list, deliberately, so a user cannot put a fake systemctl earlier in their PATH. Anything outside that list is invisible:
sudo grep -n 'secure_path' /etc/sudoers
19:Defaults secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
Do not remove secure_path — that is a real protection. Either call the binary by full path (sudo /opt/app/bin/deploy-tool), or append the directory to secure_path in visudo if the tool belongs there permanently.
sudo: sorry, you must have a tty to run sudo. Old requiretty builds — RHEL 6 and 7 shipped it on — refuse to run sudo from cron, CI or a non-interactive SSH command. Modern sudo defaults it off. Where it is still on, scope the exception rather than switching it off globally:
Defaults:DEPLOYERS !requiretty
The rule looks limited but hands out root. This is the failure that does not announce itself. deploy ALL=(root) /usr/bin/vi /etc/app.conf is a root shell — :!sh from inside vi inherits the privilege. So is any rule granting less, more, man, find, tar, awk, or systemctl status without --no-pager. And per the sudoers manual’s own warning, a wildcard in the arguments is rarely what you intended: /usr/bin/passwd * matches passwd root.
For editing files, use sudoedit (sudo -e) instead of granting an editor: it copies the file to a temporary path, runs the editor as the invoking user with no privilege, and copies it back as root. For the rest, prefer wrapper scripts you own over granting general-purpose tools, and pin arguments.
When this is the wrong approach
- Interactive administrators do not need command lists. A named human in
sudoorwheelwithALL=(ALL:ALL) ALLand a password prompt is the right configuration — you are authenticating a person and logging what they did, not sandboxing them. Enumerating commands for someone who could edit sudoers anyway is theatre. NOPASSWDfor a human is a downgrade. It exists for non-interactive callers that have no one to type a password. Given to a person, it turns any code execution in their session into root.- Command grants are not a security boundary against a hostile account. They are a guardrail against mistakes and a way to keep automation narrow. If the account itself is untrusted, the answer is a separate user with no sudo at all, a systemd unit with the privilege attached, or its own container or VM.
- More than a handful of hosts means configuration management. Hand-edited drop-ins drift. Ship
/etc/sudoers.d/30-deployfrom Ansible, Puppet or an image build withvisudo -c -fin the pipeline, and the fleet stays uniform. - One grant on one host is not a policy. This guide is the mechanics: writing a single rule and proving it does what you think it does. Deciding who gets sudo in the first place, how often the grants are re-read, and what gets revoked the day someone changes teams is a fleet-wide posture — sudo best practices covers that side of it.
- This is one layer. Sudo governs privilege once someone is on the host; it says nothing about how they got there. Pair it with fail2ban SSH protection at the front door and kernel sysctl hardening underneath.
The authoritative reference is the sudoers manual, whose SECURITY NOTES section is worth reading in full before you write a rule containing a wildcard; the Linux man-pages sudoers(5) copy is the same document. If you want an audit trail beyond syslog, Defaults log_output with iolog_dir records full session transcripts.
If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.