Setting Up a Firewall with Ansible and UFW



This content originally appeared on DEV Community and was authored by Athreya aka Maneshwar

Hi there! I’m Maneshwar. Right now, I’m building LiveAPI, a first-of-its-kind tool that helps you automatically index API endpoints across all your repositories. LiveAPI makes it easier to discover, understand, and interact with APIs in large infrastructures.

Managing firewall rules manually on each server is boring and error-prone. Instead, automate it once with Ansible and let it run every time you provision a box.

This post shows how to configure UFW using Ansible in a way that is repeatable, version-controlled, and easy to extend.

Prerequisites

  • Ansible installed on your control machine
  • Target servers accessible via SSH
  • Python installed on the target (Ansible needs it)
  • The community.general collection installed:
  ansible-galaxy collection install community.general

Inventory: hosts.ini

[web]
webserver1 ansible_host=192.168.1.10
webserver2 ansible_host=192.168.1.11

Directory Structure

firewall-setup/
├── hosts.ini
├── playbook.yml
└── roles/
    └── ufw/
        ├── tasks/
        │   └── main.yml

Role Task File: roles/ufw/tasks/main.yml

# tasks file for setting up firewall

- name: Install ufw
  ansible.builtin.apt:
    name: ufw
    state: present
    update_cache: yes
  become: true

- name: UFW - Allow SSH connections
  community.general.ufw:
    rule: allow
    name: OpenSSH
  become: true

- name: UFW - Allow HTTP connections
  community.general.ufw:
    rule: allow
    port: "80"
    proto: tcp
  become: true

- name: UFW - Allow HTTPS connections
  community.general.ufw:
    rule: allow
    port: "443"
    proto: tcp
  become: true

- name: UFW - Enable and deny by default
  community.general.ufw:
    state: enabled
    default: deny
  become: true

- name: UFW - Reload firewall
  ansible.builtin.command: ufw reload
  become: true

Playbook: playbook.yml

- name: Setup firewall using UFW
  hosts: web
  become: true
  roles:
    - ufw

Run the Playbook

ansible-playbook -i hosts.ini playbook.yml

What This Does

  1. Installs ufw on the target machine (in case it’s not there).
  2. Allows only SSH, HTTP, and HTTPS.
  3. Enables the firewall and sets the default policy to deny.
  4. Reloads the firewall to apply the rules.

Add More Rules?

Want to open port 5432 for PostgreSQL or some other service? Just add a task like:

- name: UFW - Allow PostgreSQL
  community.general.ufw:
    rule: allow
    port: "5432"
    proto: tcp

LiveAPI helps you get all your backend APIs documented in a few minutes.

With LiveAPI, you can generate interactive API docs that allow users to search and execute endpoints directly from the browser.

LiveAPI Demo

If you’re tired of updating Swagger manually or syncing Postman collections, give it a shot.


This content originally appeared on DEV Community and was authored by Athreya aka Maneshwar