BLOG POSTS
    MangoHost Blog / Create a New Sudo User on Ubuntu – Fast Admin Guide
Create a New Sudo User on Ubuntu – Fast Admin Guide

Create a New Sudo User on Ubuntu – Fast Admin Guide

Creating a new sudo user on Ubuntu is one of those fundamental server management tasks that every sysadmin needs to master, whether you’re setting up a new development environment, onboarding a team member, or implementing proper access controls. The sudo mechanism provides a secure way to grant specific users administrative privileges without sharing the root password, following the principle of least privilege. In this guide, you’ll learn how to create new sudo users, configure their permissions properly, troubleshoot common issues, and implement security best practices that’ll keep your Ubuntu server locked down tight.

How Sudo Works Under the Hood

Before diving into user creation, it’s worth understanding what’s actually happening when you grant sudo access. The sudo system relies on the /etc/sudoers file and the /etc/sudoers.d/ directory to define which users can execute which commands as which other users. When a user runs a command with sudo, the system checks these configuration files to verify permissions.

Ubuntu comes with a predefined group called sudo that has full administrative privileges. Any user added to this group inherits these permissions automatically. The relevant line in /etc/sudoers looks like this:

%sudo   ALL=(ALL:ALL) ALL

This translates to: “Members of the sudo group can run any command as any user on any host.” Pretty straightforward, but there’s more granular control available when you need it.

Step-by-Step User Creation and Sudo Configuration

Method 1: Using adduser (Recommended)

The adduser command provides an interactive way to create users with proper home directories and shell configuration:

# Create the new user
sudo adduser newusername

# Add the user to the sudo group
sudo usermod -aG sudo newusername

# Verify the user was added to the sudo group
groups newusername

The adduser command will prompt you for a password and optional user information. Don’t skip the password step – passwordless sudo users are a security nightmare waiting to happen.

Method 2: Using useradd (Manual Configuration)

For more control over the user creation process, you can use useradd with manual configuration:

# Create user with home directory and bash shell
sudo useradd -m -s /bin/bash newusername

# Set the user's password
sudo passwd newusername

# Add to sudo group
sudo usermod -aG sudo newusername

# Set proper home directory permissions
sudo chown -R newusername:newusername /home/newusername
sudo chmod 755 /home/newusername

Method 3: Creating Custom Sudo Rules

Sometimes you need more granular control than the default sudo group provides. Create custom rules using the visudo command:

# Open sudoers configuration safely
sudo visudo

# Add custom rules at the end of the file
newusername ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart nginx
newusername ALL=(ALL) /usr/bin/apt update, /usr/bin/apt upgrade

Alternatively, create a separate file in /etc/sudoers.d/:

# Create a dedicated sudo file for the user
sudo visudo -f /etc/sudoers.d/newusername

# Add the rules
newusername ALL=(ALL:ALL) ALL

Real-World Use Cases and Examples

Let’s look at some practical scenarios where different sudo configurations make sense:

Scenario User Type Sudo Configuration Use Case
Development Team developer Full sudo access Need to install packages, restart services, modify configs
DevOps Engineer deploy Limited sudo (systemctl, nginx, docker) Application deployment and service management
Monitoring User monitor Read-only access + specific restart commands System monitoring with emergency restart capabilities
Backup User backup File access + mount/unmount Automated backup processes

Example: Creating a Deployment User

Here’s a complete example for creating a deployment user with limited but practical sudo privileges:

# Create the deployment user
sudo adduser deploy

# Create custom sudo rules file
sudo visudo -f /etc/sudoers.d/deploy

# Add these lines to the file:
deploy ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart nginx
deploy ALL=(ALL) NOPASSWD: /usr/bin/systemctl reload nginx  
deploy ALL=(ALL) NOPASSWD: /usr/bin/systemctl status nginx
deploy ALL=(ALL) NOPASSWD: /bin/chown -R www-data:www-data /var/www/*
deploy ALL=(ALL) NOPASSWD: /bin/chmod -R 755 /var/www/*

# Test the configuration
sudo -u deploy sudo systemctl status nginx

Comparison with Alternative Approaches

Method Pros Cons Best For
sudo group membership Simple, standard, well-documented All-or-nothing access Trusted administrators
Custom sudoers rules Granular control, principle of least privilege Complex configuration, harder to maintain Specific service accounts
SSH key-based with restricted commands No local user needed, very secure Limited flexibility, complex setup Automated deployments
Docker/container-based isolation Complete isolation, reproducible Resource overhead, complexity Development environments

Security Best Practices and Common Pitfalls

Essential Security Practices

  • Always use strong passwords – Consider enforcing password complexity policies in /etc/pam.d/common-password
  • Enable sudo logging – All sudo commands are logged to /var/log/auth.log by default, but you can enhance this
  • Set sudo timeouts – Configure timestamp_timeout in sudoers to require password re-entry
  • Use NOPASSWD sparingly – Only for specific, low-risk commands in automated environments
  • Regular audit – Periodically review /etc/group and /etc/sudoers.d/ for unnecessary access

Advanced Security Configuration

# Enhanced sudo security settings
sudo visudo

# Add these lines to /etc/sudoers
Defaults    timestamp_timeout=15
Defaults    passwd_tries=3
Defaults    badpass_message="Incorrect password, try again"
Defaults    log_input, log_output
Defaults    logfile="/var/log/sudo.log"
Defaults    requiretty

Common Mistakes to Avoid

  • Never edit /etc/sudoers directly – Always use visudo to prevent syntax errors that could lock you out
  • Don’t use NOPASSWD for ALL commands – This defeats the purpose of sudo entirely
  • Avoid duplicate user entries – Check existing users with getent passwd before creating new ones
  • Don’t forget to test – Always verify sudo access works before logging out of your root session
  • Watch out for typos in usernames – Unlike most Linux commands, user creation won’t always warn you about questionable names

Troubleshooting Common Issues

User Not in Sudoers File Error

If you see “user is not in the sudoers file. This incident will be reported,” check these items:

# Verify group membership
groups username

# Check if sudo group exists and has proper permissions
getent group sudo

# Manually add user to sudo group if needed
sudo usermod -aG sudo username

# User needs to log out and back in for group changes to take effect
# Or use this command to switch to the user's context:
sudo su - username

Permission Denied Issues

When sudo commands fail with permission errors:

# Check sudoers file syntax
sudo visudo -c

# Verify the user's environment
sudo -u username env

# Test with explicit shell
sudo -u username -i sudo whoami

Sudoers File Corruption

If you’ve accidentally broken the sudoers file, you’ll need to fix it from a recovery mode or different privileged session:

# Boot into recovery mode or use existing root access
pkexec visudo

# Or if you have physical access
# Boot from live USB, mount the filesystem, and edit /etc/sudoers

Advanced Use Cases and Integration

LDAP Integration

For larger environments, you might want to integrate sudo with LDAP for centralized management. The sudo-ldap package provides this functionality:

sudo apt update
sudo apt install sudo-ldap

This allows you to store sudo rules in your LDAP directory and manage them centrally across multiple servers.

Automation and Configuration Management

When using tools like Ansible, Terraform, or custom scripts, you can automate user creation:

#!/bin/bash
# Script to create multiple users with sudo access

USERS=("developer1" "developer2" "devops1")
DEFAULT_PASSWORD="TempPass123!"

for user in "${USERS[@]}"; do
    if ! id "$user" &>/dev/null; then
        sudo adduser --disabled-password --gecos "" "$user"
        echo "$user:$DEFAULT_PASSWORD" | sudo chpasswd
        sudo usermod -aG sudo "$user"
        echo "Created user: $user"
    else
        echo "User $user already exists"
    fi
done

Remember to force password changes on first login for security:

sudo chage -d 0 username

SSH Key Integration

Combine sudo user creation with SSH key setup for passwordless authentication:

# Create user and setup SSH keys
sudo adduser newuser
sudo usermod -aG sudo newuser

# Setup SSH directory
sudo mkdir /home/newuser/.ssh
sudo chmod 700 /home/newuser/.ssh

# Add public key (replace with actual key)
echo "ssh-rsa AAAAB3NzaC1yc2E... user@hostname" | sudo tee /home/newuser/.ssh/authorized_keys

# Set proper permissions
sudo chmod 600 /home/newuser/.ssh/authorized_keys
sudo chown -R newuser:newuser /home/newuser/.ssh

This approach is particularly useful when setting up servers for development teams or automated deployment processes. For production environments on VPS or dedicated servers, always combine this with proper firewall rules and fail2ban configuration.

For more detailed information about sudo configuration and security, check the official documentation at sudo.ws and the Ubuntu Server Guide at ubuntu.com.



This article incorporates information and material from various online sources. We acknowledge and appreciate the work of all original authors, publishers, and websites. While every effort has been made to appropriately credit the source material, any unintentional oversight or omission does not constitute a copyright infringement. All trademarks, logos, and images mentioned are the property of their respective owners. If you believe that any content used in this article infringes upon your copyright, please contact us immediately for review and prompt action.

This article is intended for informational and educational purposes only and does not infringe on the rights of the copyright owners. If any copyrighted material has been used without proper credit or in violation of copyright laws, it is unintentional and we will rectify it promptly upon notification. Please note that the republishing, redistribution, or reproduction of part or all of the contents in any form is prohibited without express written permission from the author and website owner. For permissions or further inquiries, please contact us.

Leave a reply

Your email address will not be published. Required fields are marked