Ansible: Automate Everything from First Playbook to Production · Vault, Security and Secrets Management

Security Hardening Playbook: SSH, Users and Firewall

Write a playbook that locks down a fresh server: SSH hardening, a deploy user with key-only sudo, firewall rules, and fail2ban.

Members can save this page, take notes and track progress. See membership · Sign in

What you'll build

A hardening playbook that takes a fresh Ubuntu server and applies baseline security: creates a deploy user with SSH key authentication, disables root login and password authentication, opens only the ports the application needs, and installs fail2ban to block brute-force attempts.

The idea

Every server exposed to the internet receives automated SSH brute-force attempts within minutes of going live. A hardening playbook is the first thing you run on a new host — before deploying any application. The principle is least privilege: only the access that is needed, only the ports that are used, only the users that are required.

The hardening checklist:

  1. Create a deploy user with a home directory and an authorized SSH key.
  2. Grant sudo via the sudo group — no password for automation, but logged.
  3. Disable root SSH login and password authentication in sshd_config.
  4. Firewall — allow SSH (22), HTTP (80), HTTPS (443); deny everything else.
  5. fail2ban — ban IPs after repeated failed SSH attempts.
  6. File permissions — ensure no world-writable directories in the application path.

Ansible's become: true runs tasks as root. For specific tasks that should run as the deploy user, use become_user: deploy.

The code

The hardening playbook
cat <<'PLAYBOOK'
# hardening.yml
---
- name: Baseline security hardening
  hosts: all
  become: true
  vars:
    deploy_user: deploy
    ssh_port: 22
    allowed_ports:
      - "22"
      - "80"
      - "443"

  tasks:
    # ── 1. Deploy user ──
    - name: Create deploy user
      ansible.builtin.user:
        name: "{{ deploy_user }}"
        groups: sudo
        shell: /bin/bash
        create_home: true
        state: present

    - name: Add SSH authorized key for deploy user
      ansible.posix.authorized_key:
        user: "{{ deploy_user }}"
        key: "{{ lookup('file', 'files/deploy_id_ed25519.pub') }}"
        state: present

    - name: Allow deploy user passwordless sudo
      ansible.builtin.copy:
        content: "{{ deploy_user }} ALL=(ALL) NOPASSWD:ALL\n"
        dest: "/etc/sudoers.d/{{ deploy_user }}"
        mode: "0440"
        validate: "visudo -cf %s"

    # ── 2. SSH hardening ──
    - name: Disable root login over SSH
      ansible.builtin.lineinfile:
        path: /etc/ssh/sshd_config
        regexp: "^#?PermitRootLogin"
        line: "PermitRootLogin no"
      notify: restart sshd

    - name: Disable password authentication
      ansible.builtin.lineinfile:
        path: /etc/ssh/sshd_config
        regexp: "^#?PasswordAuthentication"
        line: "PasswordAuthentication no"
      notify: restart sshd

    - name: Set SSH port
      ansible.builtin.lineinfile:
        path: /etc/ssh/sshd_config
        regexp: "^#?Port "
        line: "Port {{ ssh_port }}"
      notify: restart sshd

    # ── 3. Firewall (UFW) ──
    - name: Install UFW
      ansible.builtin.apt:
        name: ufw
        state: present
        update_cache: true

    - name: Set UFW default deny incoming
      community.general.ufw:
        direction: incoming
        default: deny

    - name: Set UFW default allow outgoing
      community.general.ufw:
        direction: outgoing
        default: allow

    - name: Allow required ports
      community.general.ufw:
        rule: allow
        port: "{{ item }}"
        proto: tcp
      loop: "{{ allowed_ports }}"

    - name: Enable UFW
      community.general.ufw:
        state: enabled

    # ── 4. fail2ban ──
    - name: Install fail2ban
      ansible.builtin.apt:
        name: fail2ban
        state: present

    - name: Configure fail2ban for SSH
      ansible.builtin.copy:
        content: |
          [sshd]
          enabled = true
          port = {{ ssh_port }}
          maxretry = 5
          bantime = 3600
          findtime = 600
        dest: /etc/fail2ban/jail.local
        mode: "0644"
      notify: restart fail2ban

    # ── 5. File permissions ──
    - name: Ensure /var/www is not world-writable
      ansible.builtin.file:
        path: /var/www
        mode: "0755"
        state: directory

  handlers:
    - name: restart sshd
      ansible.builtin.service:
        name: sshd
        state: restarted

    - name: restart fail2ban
      ansible.builtin.service:
        name: fail2ban
        state: restarted
PLAYBOOK

Output

# hardening.yml
---
- name: Baseline security hardening
  hosts: all
  become: true
  vars:
    deploy_user: deploy
    ssh_port: 22
    allowed_ports:
      - "22"
      - "80"
      - "443"

  tasks:
    # ── 1. Deploy user ──
    - name: Create deploy user
      ansible.builtin.user:
        name: "{{ deploy_user }}"
        groups: sudo
        shell: /bin/bash
        create_home: true
        state: present

    - name: Add SSH authorized key for deploy user
      ansible.posix.authorized_key:
        user: "{{ deploy_user }}"
        key: "{{ lookup('file', 'files/deploy_id_ed25519.pub') }}"
        state: present

    - name: Allow deploy user passwordless sudo
      ansible.builtin.copy:
        content: "{{ deploy_user }} ALL=(ALL) NOPASSWD:ALL\n"
        dest: "/etc/sudoers.d/{{ deploy_user }}"
        mode: "0440"
        validate: "visudo -cf %s"

    # ── 2. SSH hardening ──
    - name: Disable root login over SSH
      ansible.builtin.lineinfile:
        path: /etc/ssh/sshd_config
        regexp: "^#?PermitRootLogin"
        line: "PermitRootLogin no"
      notify: restart sshd

    - name: Disable password authentication
      ansible.builtin.lineinfile:
        path: /etc/ssh/sshd_config
        regexp: "^#?PasswordAuthentication"
        line: "PasswordAuthentication no"
      notify: restart sshd

    - name: Set SSH port
      ansible.builtin.lineinfile:
        path: /etc/ssh/sshd_config
        regexp: "^#?Port "
        line: "Port {{ ssh_port }}"
      notify: restart sshd

    # ── 3. Firewall (UFW) ──
    - name: Install UFW
      ansible.builtin.apt:
        name: ufw
        state: present
        update_cache: true

    - name: Set UFW default deny incoming
      community.general.ufw:
        direction: incoming
        default: deny

    - name: Set UFW default allow outgoing
      community.general.ufw:
        direction: outgoing
        default: allow

    - name: Allow required ports
      community.general.ufw:
        rule: allow
        port: "{{ item }}"
        proto: tcp
      loop: "{{ allowed_ports }}"

    - name: Enable UFW
      community.general.ufw:
        state: enabled

    # ── 4. fail2ban ──
    - name: Install fail2ban
      ansible.builtin.apt:
        name: fail2ban
        state: present

    - name: Configure fail2ban for SSH
      ansible.builtin.copy:
        content: |
          [sshd]
          enabled = true
          port = {{ ssh_port }}
          maxretry = 5
          bantime = 3600
          findtime = 600
        dest: /etc/fail2ban/jail.local
        mode: "0644"
      notify: restart fail2ban

    # ── 5. File permissions ──
    - name: Ensure /var/www is not world-writable
      ansible.builtin.file:
        path: /var/www
        mode: "0755"
        state: directory

  handlers:
    - name: restart sshd
      ansible.builtin.service:
        name: sshd
        state: restarted

    - name: restart fail2ban
      ansible.builtin.service:
        name: fail2ban
        state: restarted

Run this on your computer — see “Get Started” for setup.

Run the hardening playbook, then verify:

Run and verify
cat <<'EOF'
$ ansible-playbook hardening.yml -i inventory.ini --vault-password-file .vault_pass

PLAY [Baseline security hardening] ********************************************

TASK [Gathering Facts] *********************************************************
ok: [web1.example.com]

TASK [Create deploy user] ******************************************************
changed: [web1.example.com]

TASK [Add SSH authorized key for deploy user] **********************************
changed: [web1.example.com]

TASK [Allow deploy user passwordless sudo] *************************************
changed: [web1.example.com]

TASK [Disable root login over SSH] *********************************************
changed: [web1.example.com]

TASK [Disable password authentication] *****************************************
changed: [web1.example.com]

TASK [Set SSH port] ************************************************************
ok: [web1.example.com]

TASK [Install UFW] *************************************************************
changed: [web1.example.com]

TASK [Set UFW default deny incoming] *******************************************
changed: [web1.example.com]

TASK [Set UFW default allow outgoing] ******************************************
ok: [web1.example.com]

TASK [Allow required ports] ****************************************************
changed: [web1.example.com] => (item=22)
changed: [web1.example.com] => (item=80)
changed: [web1.example.com] => (item=443)

TASK [Enable UFW] **************************************************************
changed: [web1.example.com]

TASK [Install fail2ban] ********************************************************
changed: [web1.example.com]

TASK [Configure fail2ban for SSH] **********************************************
changed: [web1.example.com]

TASK [Ensure /var/www is not world-writable] ***********************************
ok: [web1.example.com]

RUNNING HANDLER [restart sshd] *************************************************
changed: [web1.example.com]

RUNNING HANDLER [restart fail2ban] *********************************************
changed: [web1.example.com]

PLAY RECAP *********************************************************************
web1.example.com           : ok=17   changed=14   unreachable=0    failed=0
EOF

Output

$ ansible-playbook hardening.yml -i inventory.ini --vault-password-file .vault_pass

PLAY [Baseline security hardening] ********************************************

TASK [Gathering Facts] *********************************************************
ok: [web1.example.com]

TASK [Create deploy user] ******************************************************
changed: [web1.example.com]

TASK [Add SSH authorized key for deploy user] **********************************
changed: [web1.example.com]

TASK [Allow deploy user passwordless sudo] *************************************
changed: [web1.example.com]

TASK [Disable root login over SSH] *********************************************
changed: [web1.example.com]

TASK [Disable password authentication] *****************************************
changed: [web1.example.com]

TASK [Set SSH port] ************************************************************
ok: [web1.example.com]

TASK [Install UFW] *************************************************************
changed: [web1.example.com]

TASK [Set UFW default deny incoming] *******************************************
changed: [web1.example.com]

TASK [Set UFW default allow outgoing] ******************************************
ok: [web1.example.com]

TASK [Allow required ports] ****************************************************
changed: [web1.example.com] => (item=22)
changed: [web1.example.com] => (item=80)
changed: [web1.example.com] => (item=443)

TASK [Enable UFW] **************************************************************
changed: [web1.example.com]

TASK [Install fail2ban] ********************************************************
changed: [web1.example.com]

TASK [Configure fail2ban for SSH] **********************************************
changed: [web1.example.com]

TASK [Ensure /var/www is not world-writable] ***********************************
ok: [web1.example.com]

RUNNING HANDLER [restart sshd] *************************************************
changed: [web1.example.com]

RUNNING HANDLER [restart fail2ban] *********************************************
changed: [web1.example.com]

PLAY RECAP *********************************************************************
web1.example.com           : ok=17   changed=14   unreachable=0    failed=0

Run this on your computer — see “Get Started” for setup.

Common mistakes

Mistake Fix
Disabling password auth before adding a key Always add the authorized key first; otherwise you lock yourself out
Running the hardening playbook as the deploy user before the user exists First run targets root (the initial cloud-provider user), subsequent runs use the deploy user
Forgetting validate: "visudo -cf %s" on sudoers files A syntax error in a sudoers file locks out all sudo access; validate prevents this
Opening ports by number without specifying proto: tcp UFW defaults to both TCP and UDP; explicitly set TCP unless you need UDP

Key points

  • Run the hardening playbook first, before any application deployment.
  • become: true runs as root; become_user: deploy runs as the deploy user — use the right one for each task.
  • Handlers run only once at the end of the play, even if notified multiple times; SSH restarts only after all config changes.
  • Always validate sudoers files with visudo -cf %s to prevent lockout.
  • fail2ban protects SSH against brute-force; configure maxretry, bantime, and findtime for your risk tolerance.

Practice questions

Why should you add the SSH authorized key before disabling password authentication?

Answer

If you disable password authentication first and the key task fails, you will be locked out of the server with no way to log in. Always ensure key-based access works before removing password access.

What does the `validate` parameter on the sudoers copy task do?

Answer

It runs visudo -cf %s against the file before writing it. If the syntax is invalid, Ansible skips the write, preventing a broken sudoers file that would lock out all sudo access.

Why do handlers run at the end of the play rather than immediately after the notifying task?

Answer

This ensures that all configuration changes are applied before the service restarts. If sshd_config has three changes, SSH restarts once — not three times — reducing disruption and avoiding partially-applied configurations.

Open in the app to mark lessons complete, take notes and track your progress.

Last reviewed · By the ByteCamel team · How we write content

Was this page helpful?

Report a mistake