Ansible remains one of the most popular tools for automating server configs. Using Ansible will help you keep up your setup repeatable and error free. In this post, I’ll shares some Ansible best practices with examples on a VPS running Ubuntu 24.04.

Use Clear Ansible Inventory Structure
First. Keep the inventory files organized. Use directory with group files instead of a single flat file.
# inventory/hosts.ini
[webservers]
vpspreprod ansible_host=192.168.1.100 ansible_user=deploySplit vars into group and host level when needed:
# inventory/group_vars/webservers.yml
nginx_port: 80Keep Playbooks Simple
Avoid putting everything in one file. Use roles to split logic into tasks, handlers, templates, and vars.
# ❌ playbooks/nginx.yml
- name: Deploy Nginx on Ubuntu 24.04
hosts: webservers
become: true
roles:
- nginx
# ✅ roles/nginx/tasks/main.yml
- name: Install Nginx
apt:
name: nginx
state: present
update_cache: true
- name: Start and enable Nginx
service:
name: nginx
state: started
enabled: trueUse a template for the Nginx config (this is a simple nginx config):
# roles/nginx/templates/nginx.conf
server {
listen {{ nginx_port }};
location / {
return 200 'Nginx is running';
}
}Then apply it with:
- name: Upload custom nginx config
template:
src: nginx.conf
dest: /etc/nginx/sites-available/default
mode: 0644
notify: Reload nginxHandlers respond to changes:
# roles/nginx/handlers/main.yml
- name: Reload nginx
service:
name: nginx
state: reloadedUse Ansible Vault for Secrets
Avoid putting plain passwords in your code. Encrypt sensitive files:
ansible-vault encrypt secrets.ymlThen include them:
- name: Include secrets
vars_files:
- secrets.ymlTest Your Playbooks Locally First
Use a local VM or container that matches your VPS. Test everything before touching production.
Use tags to test only parts of your playbook:
ansible-playbook playbooks/nginx.yml --tags "config"Run with --check for Dry Runs
Use the --check flag to preview changes without applying them:
ansible-playbook playbooks/nginx.yml --checkKeep Ansible Updated
Ubuntu 24.04 ships with recent versions of Python and system libraries. Use Ansible >= 9 for best compatibility.
pip install --upgrade ansibleTips
- Set up SSH keys for the target VPS
- Avoid hard coding IPs in playbooks
- Document your roles and variables
- Reuse roles across environments
These practices will help you stay ready for scaling and helps your work easier to share or hand over. Whether you’re deploying one VPS or many, using roles, vaults, and clean playbooks keeps things smooth.