# From Bash Scripts to Ansible: An Introduction to Server Automation

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:

@[code](../snippets/ansible/bash-example.sh)

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 are `shell` and `command`: they don't know what your command does, so they always report `changed`. Prefer a dedicated module. If you must use `command`, add `creates` (skip the command if the file already exists) or `changed_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 `ok` and are not touched, and only the remaining ones are applied.
- **Multi-distro, with caveats.** The `ansible.builtin.package` module hides the difference between `apt` and `dnf`, but not package names (`apache2` vs `httpd`) or firewall tools (UFW vs firewalld). For those you branch on facts such as `ansible_os_family` or use distro-specific modules. This playbook targets Debian and Ubuntu and uses `apt` and 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](https://docs.astral.sh/uv/): it is faster than pip and keeps each tool in its own isolated environment.

::: window title="Terminal" height="260" gap="10"
```bash
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.

::: tip 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:

::: file-tree title="my-server-setup"
- 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.

::: steps
- 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.yaml` file. Use the SSH user that has already been granted access to the server, and do not assume that it is the `root` user.
- 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 in `known_hosts`.
:::

**inventory.yaml**

@[code](../snippets/ansible/my-server-setup/inventory.yaml)

### Verify the connection

```bash
ansible -i inventory.yaml all -m ping
```

```text
myserver | SUCCESS => {
    "changed": false,
    "ping": "pong"
}
```

> This is not an ICMP ping. The `ping` module 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:

::: steps
- Install `ufw` and `fail2ban`.
- Allow SSH, HTTP, and HTTPS in `ufw`, deny all other incoming traffic, and enable `ufw`.
- Configure Fail2Ban to protect SSH and ensure it runs and starts at boot.
:::

**playbook.yaml**

@[code](../snippets/ansible/my-server-setup/playbook.yaml)

::: warning 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

```bash
ansible-playbook -i inventory.yaml playbook.yaml # first run
ansible-playbook -i inventory.yaml playbook.yaml # second run
```

Compare the results.

::: code-tabs
@tab First run
```
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   
```

@tab Second run
```
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:

```bash
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:

```bash
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.

::: tip
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

::: timeline card placement="between" line="dashed"
- Learn inventory patterns
  time="Next step" type=info icon=mdi:format-list-text placement=right

  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`".

- Explore modules and roles
  time="Then" type=warning icon=mdi:cube-outline

  Browse the [module and collection index](https://docs.ansible.com/ansible/latest/collections/index.html) and [Ansible Galaxy](https://galaxy.ansible.com/). 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.

- Write your own roles
  time="Eventually" type=success icon=mdi:hammer-wrench placement=right

  Once you find yourself repeating similar tasks in your playbooks, move them into a role.
:::

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.