Hello, I'm Maneshwar. I'm working on FreeDevTools online currently building **one place for all dev tools, cheat codes, and TLDRs* — a free, open-source hub where developers can quickly find and use tools without any hassle of searching all over the internet.
Managing firewall rules manually on each server i
s 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
- Installs
ufw
on the target machine (in case it's not there). - Allows only SSH, HTTP, and HTTPS.
- Enables the firewall and sets the default policy to deny.
- 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
I’ve been building FreeDevTools.
A collection of UI/UX-focused tools crafted to simplify workflows, save time, and reduce friction in searching tools/materials.
Any feedback or contributors are welcome!
It’s online, open-source, and ready for anyone to use.
👉 Check it out: FreeDevTools
⭐ Star it on GitHub: freedevtools
Let’s make it even better together.
Top comments (0)