Ansible Use Case: UFW Firewall Configuration with Conditionals Overview
This lab demonstrates how to use Ansible to configure UFW (Uncomplicated Firewall) on a local Ubuntu system. The role conditionally allows or denies SSH and HTTP access based on a variable, installs UFW, resets its configuration, sets default policies, and ensures the firewall is enabled.
Project Structure firewall-project/ ├── playbook.yml └── roles/ └── firewall_setup/ ├── defaults/ │ └── main.yml └── tasks/ └── main.yml Implementation Steps
- Create Role ansible-galaxy init firewall_setup
Creates a role directory structure with defaults, tasks, and other standard folders.
- Define Default Variable
File: roles/firewall_setup/defaults/main.yml
service_allowed: false service_allowed controls whether SSH and HTTP are allowed or denied. Default is false (deny both services). 3. Define Role Tasks
File: roles/firewall_setup/tasks/main.yml
-
name: Update APT package cache apt: update_cache: yes cache_valid_time: 3600 become: true
-
name: Install UFW apt: name: ufw state: present become: true
-
name: Reset UFW to default command: ufw --force reset become: true
-
name: Set default incoming policy to deny ufw: direction: incoming policy: deny become: true
-
name: Set default outgoing policy to allow ufw: direction: outgoing policy: allow become: true
-
name: Allow or Deny SSH (IPv4 only) ufw: rule: "{{ 'allow' if service_allowed else 'deny' }}" port: ssh proto: tcp direction: in become: true
-
name: Allow or Deny HTTP (IPv4 only) ufw: rule: "{{ 'allow' if service_allowed else 'deny' }}" port: 80 proto: tcp direction: in become: true
-
name: Enable UFW ufw: state: enabled become: true
- Create Playbook (playbook.yml)
- name: Configure UFW firewall
hosts: localhost
connection: local
gather_facts: yes
become: true
vars:
service_allowed: true # Set to false to deny SSH/HTTP
roles:
- firewall_setup Targets localhost with local connection. Overrides the default variable to allow SSH and HTTP.
- Pre-Playbook Setup
Execute manually to disable IPv6 and reset UFW:
sudo sed -i 's/^IPV6=yes/IPV6=no/' /etc/default/ufw && sudo ufw --force reset 6. Run Playbook ansible-playbook playbook.yml --ask-become-pass Enter the sudo password when prompted: user@123! 7. Validation Check UFW status: sudo ufw status Should show rules for SSH and HTTP as ALLOW (if service_allowed: true). Confirm default policies: sudo ufw status verbose Incoming: deny, Outgoing: allow Key Concepts Using Ansible roles for reusable automation Conditional tasks with variables (service_allowed) Installing and configuring UFW Setting default firewall policies Using become for privilege escalation Local execution with connection: local Summary
This lab demonstrates how Ansible can automate firewall configuration with conditionals, enabling or restricting SSH and HTTP traffic based on variable input. Using roles makes the setup reusable, idempotent, and maintainable.