Ansible playbook for hardening Ubuntu 24.04 servers using the dev-sec/ansible-collection-hardening collection.
- ✅ Creates admin user with SSH key authentication
- ✅ Configures UFW firewall with custom SSH port
- ✅ Applies comprehensive SSH hardening (dev-sec.hardening.ssh_hardening)
- ✅ Applies OS-level hardening (dev-sec.hardening.os_hardening)
- ✅ Disables password authentication
- ✅ Removes weak cryptographic algorithms
- ✅ Hardens system permissions and configurations
- Ansible: 2.16 or higher
- Target System: Ubuntu 24.04 LTS (may work on other versions)
- Initial Access: Root SSH access to target server
# Install Ansible (if not already installed)
pip3 install ansible
# Install required collections
ansible-galaxy collection install devsec.hardening
ansible-galaxy collection install community.general
ansible-galaxy collection install ansible.posixgit clone https://github.com/yourusername/harden-ubuntu-server.git
cd harden-ubuntu-server
# Copy and customize configuration
cp group_vars/all.yml.example group_vars/all.yml
cp inventory/hosts.example inventory/hosts
# Edit with your values
vi group_vars/all.yml # Configure admin user, SSH keys, port
vi inventory/hosts # Add your server IP/hostname# Test connectivity
ansible all -m ping
# Dry run (check mode)
ansible-playbook playbook.yml --check
# Execute hardening
ansible-playbook playbook.yml# Admin user that will be created
admin_user: "yourname"
admin_home: "/home/{{ admin_user }}"
admin_shell: "/bin/bash"
# SSH keys (GitHub or local file)
ssh_keys:
- "https://github.com/yourusername.keys"
# Custom SSH port (reduces bot attacks)
sshd_port: 2222[ubuntu]
myserver ansible_host=203.0.113.10 ansible_user=root
[all:vars]
ansible_python_interpreter=/usr/bin/python3- Creates admin user with sudo access
- Installs SSH public keys
- Configures UFW firewall
- Sets custom SSH port
- Disables password authentication
- Removes weak ciphers and MACs
- Configures secure SSH daemon settings
- Hardens SSH client configuration
- Installs and configures auditd
- Hardens file permissions (shadow, passwd, cron)
- Configures sysctl for network security
- Disables core dumps
- Hardens filesystem mount options
- And much more...
After running the playbook:
-
Test SSH access with your admin user:
ssh -p 2222 yourname@your-server-ip
-
Verify sudo works:
sudo whoami # Should return 'root' -
Check firewall:
sudo ufw status verbose
-
Update your SSH config (~/.ssh/config):
Host myserver HostName your-server-ip Port 2222 User yourname
- Check if you're using the correct port:
ssh -p 2222 user@host - Verify SSH keys are correct in
group_vars/all.yml - Check firewall allows your SSH port:
sudo ufw status
The dev-sec roles are highly configurable. See their documentation:
Add overrides to group_vars/all.yml.
It's recommended to test this playbook on a disposable VM or VPS before applying to production servers.
MIT
This playbook uses the excellent dev-sec/ansible-collection-hardening collection.