·8 min read·Updated Nov 28, 2026

Ansible VPS Setup: Rebuild a Server in Minutes, Not Hours

Ansible VPS setup for a disposable server: one playbook for users, SSH, nftables, updates, plus vault secrets and restores so a rebuild takes minutes.

If your VPS setup lives only in your shell history, every rebuild becomes an afternoon of guesswork. An Ansible playbook turns that afternoon into one command. You describe the server once (users, SSH policy, firewall, updates, secrets, data restore), and every new or reinstalled VPS ends up in the same known-good state. This guide builds a small, practical playbook for a single Debian VPS. It covers the order of operations that keeps you from locking yourself out, how to keep secrets out of the repository, and how to check that the result matches what you intended.

Why bother with a single server? Because many failures are easier to recover from when the server is disposable. A compromise, a botched upgrade, a missed renewal, or a move to a bigger plan all end the same way: a fresh VM that needs to become your server again, fast.

Requirements and assumptions

  • Control machine: your laptop or workstation running Linux, macOS, or WSL. Ansible runs here. Nothing extra is installed on the server except Python, which most images already include.
  • Target: a fresh Debian 12 or 13 VPS with root SSH access. Ubuntu 22.04/24.04 works with minor changes. AlmaLinux needs dnf instead of apt and the sshd service name instead of ssh.
  • An SSH key pair dedicated to this server. Don't reuse your everyday key if you care about separating identities.
  • Optional: an existing restic repository if you want the playbook to restore application data. Our encrypted off-site backup guide covers setting one up.

Install Ansible on the control machine. pipx keeps it isolated from system Python:

pipx install --include-deps ansible
ansible --version

The full ansible package includes the ansible.posix collection used below for authorized_key. If you install only ansible-core, add it with ansible-galaxy collection install ansible.posix.

Repository layout

Keep the project small and readable:

infra/
├── inventory.ini
├── site.yml
├── files/
│   └── admin.pub
├── templates/
│   └── nftables.conf.j2
└── group_vars/
    └── all/
        ├── vars.yml
        └── vault.yml      # encrypted with ansible-vault

The inventory tells Ansible where the server is. On the very first run you connect as root, because that is all a fresh image gives you:

[vps]
web1 ansible_host=203.0.113.10 ansible_user=root

Non-secret variables go in group_vars/all/vars.yml:

admin_user: admin
ssh_port: 22
open_tcp_ports: [80, 443]
do_restore: false

Before the first connection: verify the host key

Ansible uses normal OpenSSH underneath and respects known_hosts. Resist the common advice to set host_key_checking = False. Doing that throws away the only protection you have against connecting to the wrong machine on day one. Connect once by hand, compare the fingerprint against what the provider's console shows (ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub run inside the console), and then let Ansible take over. Our SSH hardening guide explains why this step matters more than most config tweaks.

If a minimal image ships without Python, bootstrap it with the raw module. It needs nothing on the target but a shell:

ansible vps -i inventory.ini -m raw -a "apt-get update && apt-get install -y python3"
ansible vps -i inventory.ini -m ping

The playbook

The order of tasks is deliberate. The admin user and key are created and the firewall allows SSH before root login and passwords are disabled. Reverse that order and the first run can cut off its own connection.

# site.yml
- name: Baseline a disposable VPS
  hosts: vps
  become: true

  tasks:
    - name: Update package cache and apply safe upgrades
      ansible.builtin.apt:
        update_cache: true
        cache_valid_time: 3600
        upgrade: safe

    - name: Install baseline packages
      ansible.builtin.apt:
        name: [sudo, nftables, unattended-upgrades, restic]
        state: present

    - name: Create admin user
      ansible.builtin.user:
        name: "{{ admin_user }}"
        groups: sudo
        append: true
        shell: /bin/bash

    - name: Install admin SSH key (and remove any others)
      ansible.posix.authorized_key:
        user: "{{ admin_user }}"
        key: "{{ lookup('file', 'files/admin.pub') }}"
        exclusive: true

    - name: Allow admin to use sudo
      ansible.builtin.copy:
        dest: /etc/sudoers.d/90-admin
        content: "{{ admin_user }} ALL=(ALL) NOPASSWD:ALL\n"
        mode: "0440"
        validate: visudo -cf %s

    - name: Deploy nftables ruleset
      ansible.builtin.template:
        src: templates/nftables.conf.j2
        dest: /etc/nftables.conf
        mode: "0644"
        validate: nft -c -f %s
      notify: Restart nftables

    - name: Enable nftables at boot
      ansible.builtin.service:
        name: nftables
        enabled: true
        state: started

    - name: Enable automatic security updates
      ansible.builtin.copy:
        dest: /etc/apt/apt.conf.d/20auto-upgrades
        content: |
          APT::Periodic::Update-Package-Lists "1";
          APT::Periodic::Unattended-Upgrade "1";
        mode: "0644"

    - name: Harden sshd via drop-in
      ansible.builtin.copy:
        dest: /etc/ssh/sshd_config.d/10-hardening.conf
        content: |
          PermitRootLogin no
          PasswordAuthentication no
          KbdInteractiveAuthentication no
        mode: "0644"
      notify: [Validate sshd, Restart ssh]

  handlers:
    - name: Restart nftables
      ansible.builtin.service:
        name: nftables
        state: restarted

    - name: Validate sshd
      ansible.builtin.command: sshd -t
      changed_when: false

    - name: Restart ssh
      ansible.builtin.service:
        name: ssh
        state: restarted

A few points that aren't obvious:

  • Drop-in files override the main config. Debian 12+ and Ubuntu 22.04+ include /etc/ssh/sshd_config.d/*.conf at the top of sshd_config, and for most directives sshd uses the first value it reads. A drop-in is therefore cleaner than editing the main file with lineinfile, and package upgrades won't fight you over it.
  • Handlers run in the order they're defined, not the order they're notified. Validate sshd therefore runs before Restart ssh. If validation fails, the play stops and the old, working sshd keeps running.
  • validate: runs before the file is moved into place. A typo in the sudoers line or the nftables template never reaches the live path. That protects you from a broken sudo or an empty firewall.
  • NOPASSWD is a trade-off. It makes unattended runs easy. It also means anyone holding the admin key has root. If that bothers you, set a sudo password stored in the vault (below) and run with --ask-become-pass.
  • Ubuntu 24.04 uses socket activation for SSH. Restarting the service works for the settings above. Changing the port also requires systemctl daemon-reload and a restart of ssh.socket.

The firewall template

The template opens SSH plus whatever you list in open_tcp_ports, and drops everything else:

#!/usr/sbin/nft -f
flush ruleset

table inet filter {
  chain input {
    type filter hook input priority 0; policy drop;
    ct state established,related accept
    ct state invalid drop
    iif "lo" accept
    ip protocol icmp accept
    tcp dport {{ ssh_port }} accept
{% for port in open_tcp_ports %}
    tcp dport {{ port }} accept
{% endfor %}
  }
  chain forward { type filter hook forward priority 0; policy drop; }
  chain output  { type filter hook output priority 0; policy accept; }
}

The established/related rule is what keeps your current Ansible session alive when the ruleset reloads. For the reasoning behind each line, rate limiting, and recovery if you do get locked out, see the nftables baseline ruleset guide. If you run Docker, remember that published container ports bypass this input chain entirely.

Secrets: ansible-vault, not plain text

Your restic password, repository URL, and any API tokens belong in an encrypted vault file:

ansible-vault create group_vars/all/vault.yml
vault_restic_repo: "sftp:[email protected]:/srv/restic/web1"
vault_restic_password: "long-random-passphrase"

Ansible decrypts the file in memory at run time when you pass --ask-vault-pass. The file on disk stays encrypted with AES-256. Two things the vault does not protect: values you print with debug, and task output in verbose mode. Add no_log: true to any task that handles a secret.

Also consider what the repository itself reveals. Even with secrets encrypted, an inventory of IPs, hostnames, open ports, and backup destinations is a map of your infrastructure. If you keep server identities separated, don't push it to a public Git host. Keep it local or on a private remote you control.

Restoring data as part of the rebuild

A rebuilt server with no data isn't very useful. This optional block restores one application path from the latest restic snapshot. It is gated behind do_restore because restoring to / overwrites existing files under the included path:

    - name: Restore application data from restic
      ansible.builtin.command:
        cmd: restic restore latest --target / --include /var/lib/myapp
        creates: /var/lib/myapp
      environment:
        RESTIC_REPOSITORY: "{{ vault_restic_repo }}"
        RESTIC_PASSWORD: "{{ vault_restic_password }}"
      no_log: true
      when: do_restore | bool

creates: makes the task skip if the directory already exists, so a second run won't clobber live data. If the repository uses SFTP, the server also needs an SSH key authorised on the backup host. Deploy that key from the vault the same way, with no_log: true.

Running it and verifying the result

Do a dry run first. --check --diff shows what would change without changing anything (the command-based tasks are skipped in check mode):

ansible-playbook -i inventory.ini site.yml --ask-vault-pass --check --diff
ansible-playbook -i inventory.ini site.yml --ask-vault-pass

Root login is now disabled, so update the inventory to ansible_user=admin and run the playbook a second time. A correct playbook is idempotent: the recap should show changed=0. Anything that reports a change on every run is a task that doesn't really know the state it is aiming for. Fix it now, before you rely on it.

Then confirm on the server itself:

sudo sshd -T | grep -E 'permitrootlogin|passwordauthentication'
sudo nft list ruleset
systemctl is-enabled nftables unattended-upgrades

Keep your existing SSH session open while you test a new login as the admin user from a second terminal. Only close the old one once the new login works.

Troubleshooting

  • REMOTE HOST IDENTIFICATION HAS CHANGED after a rebuild on the same IP. This is expected: a reinstalled VM generates new host keys. Remove the old entry with ssh-keygen -R 203.0.113.10 and verify the new fingerprint through the console before you accept it. Don't make this a reflex. A host-key change you didn't cause is exactly the warning you want.
  • UNREACHABLE on the second run. You're still connecting as root, and root login is now off. Switch ansible_user to the admin account.
  • Missing sudo password. You removed NOPASSWD but didn't pass --ask-become-pass.
  • The play stops at Validate sshd. Run sshd -t on the server for the exact line number. The running daemon is unaffected.

Limitations

A playbook rebuilds configuration. It does not rebuild trust. If a server was compromised, a fresh VM plus this playbook is the right recovery path, but only once you know how the attacker got in. Otherwise you are re-creating the same hole. Our guide to detecting and rebuilding a compromised VPS covers that investigation. A playbook also can't restore data you never backed up, and it drifts from reality whenever you make manual changes and don't put them back into the code. The discipline that makes this work is simple: if you changed it by hand, add it to the playbook the same day.

Pairing a playbook with a fast-deploying VPS

Rebuild speed depends on two things: how quickly a fresh VM exists and how quickly it becomes your server. On IronBalkans, a KVM VPS in Bucharest is typically deployed about two minutes after your Monero, Bitcoin, or Litecoin payment confirms, with full root and no email or ID required to sign up. With a playbook like this one ready, that same VM can be hardened and running your services shortly after. If you want a disposable server you can stand up again on demand, start with the smallest plan, run the playbook against it twice, and check that the second run reports nothing to change.

Written by IronBalkans. Last reviewed Nov 28, 2026.