This post is for those who are new to Ansible. We will keep it practical and skip the theory. By the end, you will have a working playbook that sets up a firewall and Fail2Ban on a fresh Debian or Ubuntu server.
So, you have a virtual private server (VPS), and every time you create one, you copy and paste the same set of commands from a notes file. Eventually these commands become a Bash script that sets up a firewall, installs Fail2Ban, and opens ports for a future web server. It works the first few times, but then you need to do the same on other servers. One of them runs Fedora, and the "quick setup script" becomes a complicated mess of if statements and TODO: fix later comments.
Why Bash Scripts Fall Short
Imperative, not declarative. A script is a list of instructions executed in order. It knows nothing about the current state of the server unless you code the checks yourself, so running it twice, or on a partially configured machine, can cause problems.
No idempotency. Idempotency means that running a command multiple times leaves the system in the same state as running it once. Some commands have this property: apt install nginx is a no-op if nginx is already installed. Many don't. echo "Port 2222" >> /etc/ssh/sshd_config appends a duplicate line on every run, iptables -A INPUT -p tcp --dport 80 -j ACCEPT adds another identical rule, and useradd deploy fails the second time. A script is idempotent only if you guard every such line yourself, and that is where the if statements come from.
Error handling is your responsibility. If a script fails in the middle, the server remains half-configured. Without set -euo pipefail, the script continues and makes things worse. With it, the script halts, but you still need to figure out where it stopped and what state the server was left in.
Distro differences. Package managers, service managers, and firewall tools vary between distributions, so the script grows separate branches for Debian, Fedora, Alpine, and so on.
Here is an example of what a typical "server setup" script might look like after a few months of updates:
#!/bin/bash
set -euo pipefail
# Detect OS because of course we have to
if [ -f /etc/debian_version ]; then
apt update && apt install -y nginx fail2ban ufw
ufw allow 22
ufw allow 80
ufw allow 443
ufw --force enable
elif [ -f /etc/redhat-release ]; then
dnf install -y nginx fail2ban firewalld
systemctl start firewalld
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload
# Wait, this fails on Fedora 39+ because dnf replaced yum
fi
# This breaks if sshd_config was already modified
if ! grep -q "PermitRootLogin no" /etc/ssh/sshd_config; then
echo "PermitRootLogin no" >>/etc/ssh/sshd_config
fi
# TODO: make this not break on re-run
systemctl restart sshd
Each additional branch and repetition of a command creates another potential place for bugs to hide. This can lead to spending more time fixing the script than actually configuring the servers.
Enter Ansible
Instead of telling the server what commands to run, you describe the desired state in YAML. Each module checks the current state of the thing it is responsible for (is the package installed, does the file contain this content, is the port open) and changes it only if necessary.
- Idempotent, as long as you use proper modules. Running the same playbook on a configured server changes nothing, and every task reports
ok. The exceptions areshellandcommand: they don't know what your command does, so they always reportchanged. Prefer a dedicated module. If you must usecommand, addcreates(skip the command if the file already exists) orchanged_when(define when the task counts as a change). - No rollback, but easy recovery. If a task fails, the play stops and the server stays in the state it was in at that moment. Fix the cause and run the playbook again: tasks that already succeeded report
okand are not touched, and only the remaining ones are applied. - Multi-distro, with caveats. The
ansible.builtin.packagemodule hides the difference betweenaptanddnf, but not package names (apache2vshttpd) or firewall tools (UFW vs firewalld). For those you branch on facts such asansible_os_familyor use distro-specific modules. This playbook targets Debian and Ubuntu and usesaptand UFW directly. - Agentless. No agent or daemon needs to be installed on the servers. Ansible connects via SSH and requires only Python 3, which is included by default in Debian and Ubuntu.
Getting Started
First, install Ansible on your local machine. I recommend uv: it is faster than pip and keeps each tool in its own isolated environment.
Terminal
curl -LsSf https://astral.sh/uv/install.sh | sh
source $HOME/.local/bin/env
# ansible-core: the core engine (ansible, ansible-playbook, etc.)
# ansible: the community package with bundled collections (community.general, etc.)
uv tool install ansible-core==2.21.5 --with ansible --python 3.14
ansible --version
You should see something like ansible [core 2.21.5] in the output.
ansible-core vs ansible
Two packages have similar names: ansible-core and ansible. ansible-core is the main engine: it contains the ansible and ansible-playbook commands and the built-in modules (ansible.builtin.*). ansible is a community package that adds dozens of collections, such as community.general, which provides the ufw module we use later. Without that collection, the playbook fails with a "couldn't resolve module" error.
If you only need the ufw module, you can skip the large ansible package: install ansible-core and then run ansible-galaxy collection install community.general.
Create a project directory with two files:
my-server-setup
inventory.yaml# The servers you want to manage
playbook.yaml# What to do with them
Your First Inventory: Tell Ansible Where to Connect
An inventory is a list of hosts that Ansible can manage. In this example, there is only one server listed. You can use either an IP address or a DNS name as long as your local machine can access it over SSH.
- Find your server's public IP address or DNS name and confirm which SSH user to use.
- Add the host and connection details to the
inventory.yamlfile. Use the SSH user that has already been granted access to the server, and do not assume that it is therootuser. - Make sure your SSH key or other authentication method is working properly. Connect once using plain
ssh, so the server's host key can be recorded inknown_hosts.
inventory.yaml
all:
children:
servers:
hosts:
myserver:
ansible_host: 172.30.0.2
ansible_user: lab
ansible_ssh_private_key_file: ~/.ssh/id_ed25519
ansible_python_interpreter: /usr/bin/python3
Verify the connection
ansible -i inventory.yaml all -m ping
myserver | SUCCESS => {
"changed": false,
"ping": "pong"
}
This is not an ICMP ping. The
pingmodule logs in over SSH and runs a tiny Python script on the server. Depending on your Ansible version, you may also see a warning about interpreter discovery. This is normal and harmless.
Your First Playbook: Firewall and Fail2Ban
On a Debian or Ubuntu server, the playbook will:
- Install
ufwandfail2ban. - Allow SSH, HTTP, and HTTPS in
ufw, deny all other incoming traffic, and enableufw. - Configure Fail2Ban to protect SSH and ensure it runs and starts at boot.
playbook.yaml
---
- name: Configure firewall and Fail2Ban
hosts: all
become: true
vars:
ssh_port: 22
firewall_tcp_ports:
- "{{ ssh_port }}"
- 80
- 443
fail2ban_bantime: 3600
fail2ban_findtime: 600
fail2ban_maxretry: 3
tasks:
- name: Install ufw and fail2ban
ansible.builtin.apt:
name:
- ufw
- fail2ban
- python3-systemd
state: present
update_cache: true
cache_valid_time: 3600
- name: Allow TCP ports through UFW
community.general.ufw:
rule: allow
port: "{{ item | string }}"
proto: tcp
loop: "{{ firewall_tcp_ports }}"
- name: Deny all other incoming traffic
community.general.ufw:
direction: incoming
default: deny
- name: Enable UFW
community.general.ufw:
state: enabled
- name: Configure Fail2Ban
ansible.builtin.copy:
dest: /etc/fail2ban/jail.local
mode: "0644"
content: |
[DEFAULT]
ignoreip = 127.0.0.1/8 ::1
bantime = {{ fail2ban_bantime }}
findtime = {{ fail2ban_findtime }}
maxretry = {{ fail2ban_maxretry }}
backend = systemd
[sshd]
enabled = true
port = {{ ssh_port }}
notify: Restart Fail2Ban
- name: Ensure Fail2Ban is running and enabled
ansible.builtin.systemd_service:
name: fail2ban
state: started
enabled: true
handlers:
- name: Restart Fail2Ban
ansible.builtin.systemd_service:
name: fail2ban
state: restarted
Don't lock yourself out
SSH is allowed before UFW is enabled, so keep this order. Make sure ssh_port matches the port your sshd actually listens on, otherwise you will cut off your own connection. If possible, keep a provider console or a second open session as a way back in.
Your First Run
The playbook uses become: true, so the SSH user needs sudo rights. If sudo asks for a password, add --ask-become-pass (-K) to the commands below.
Run the playbook twice
ansible-playbook -i inventory.yaml playbook.yaml # first run
ansible-playbook -i inventory.yaml playbook.yaml # second run
Compare the results.
PLAY [Configure firewall and Fail2Ban] ******************************
TASK [Gathering Facts] **********************************************
ok: [myserver]
TASK [Install ufw and fail2ban] *************************************
changed: [myserver]
TASK [Allow TCP ports through UFW] **********************************
changed: [myserver] => (item=22)
changed: [myserver] => (item=80)
changed: [myserver] => (item=443)
TASK [Deny all other incoming traffic] ******************************
ok: [myserver]
TASK [Enable UFW] ***************************************************
changed: [myserver]
TASK [Configure Fail2Ban] *******************************************
changed: [myserver]
TASK [Ensure Fail2Ban is running and enabled] ***********************
changed: [myserver]
RUNNING HANDLER [Restart Fail2Ban] **********************************
changed: [myserver]
PLAY RECAP **********************************************************
myserver: ok=8 changed=6 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
PLAY [Configure firewall and Fail2Ban] ******************************
TASK [Gathering Facts] **********************************************
ok: [myserver]
TASK [Install ufw and fail2ban] *************************************
ok: [myserver]
TASK [Allow TCP ports through UFW] **********************************
ok: [myserver] => (item=22)
ok: [myserver] => (item=80)
ok: [myserver] => (item=443)
TASK [Deny all other incoming traffic] ******************************
ok: [myserver]
TASK [Enable UFW] ***************************************************
ok: [myserver]
TASK [Configure Fail2Ban] *******************************************
ok: [myserver]
TASK [Ensure Fail2Ban is running and enabled] ***********************
ok: [myserver]
PLAY RECAP **********************************************************
myserver: ok=7 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
changed means Ansible modified something on the server, ok means it was already in the desired state.
On the second run, the tasks should report ok and the recap should show changed=0: Ansible looked at the server, found it already in the desired state and touched nothing. The handler didn't run either, because the Fail2Ban configuration didn't change. That is idempotency, and it is the main difference from a Bash script, which would run every command again.
Check the result
Log in to the server and make sure that the firewall and Fail2Ban are set up correctly:
sudo ufw status verbose
sudo fail2ban-client status sshd
Dry run with --check --diff
Check mode asks each module what it would change without actually changing anything, and the --diff flag shows the differences in the files:
ansible-playbook -i inventory.yaml playbook.yaml --check --diff
It works best on a server that has already been configured. On a freshly installed server, later tasks may depend on previous tasks that have not yet been run: in check mode, nothing is installed, so the ufw binary and fail2ban service may not be present. As a result, some tasks may fail in check mode even if the playbook is correct.
Tips
Keep in mind that command and shell tasks are skipped in check mode by default, because Ansible cannot know what an arbitrary command would do.
Where to Go Next
Learn inventory patterns
Group servers and target them with patterns: 'webservers:&staging' (quote it in the shell, because of the &) means "hosts that are in both webservers and staging".
Next step
Explore modules and roles
Browse the module and collection index and Ansible Galaxy. The quality of community roles varies, so check when a role was last updated and read what it does before running it on a production server. Roles that modify the SSH configuration can lock you out, just like a bad firewall rule. Also look at variables and templates (ansible.builtin.template) in more depth.
Then
Write your own roles
Once you find yourself repeating similar tasks in your playbooks, move them into a role.
Eventually
The most important thing to understand is the shift in mindset. You are no longer writing scripts; you are describing infrastructure. Once this concept clicks, everything else will follow naturally.