How to open firewall ports in Debian-like systems with Ansible?

I'm going to show you a live Playbook and some simple Ansible code.

I'm Luca Berton and welcome to today's episode of Ansible Pilot.

Ansible open firewall ports in Debian-like systems

Today we're talking about the Ansible module UFW.

The full name is community.general.ufw, which means that is part of the collection supported by the Ansible community. This module requires Ansible 2.9+.

It works in Debian-like systems so distributions like Debian, Ubuntu, and Mint with ufw firewall, the Uncomplicated Firewall.

This module manages the firewall with UFW.

Parameters

The parameter list is pretty wide but this are the most important options for our use case to open firewall ports.

The first set of parameters controls UFW program and the second the single rules.

UFW program parameters

  • default _string_ (policy) - allow / deny / reject
  • logging _string_ - on / off / low / medium / high /full
  • state _string_ - enabled / present / absent / disabled

Let's start with three UFW program parameters.

The "default" parameter, also called as "policy", change the default policy for incoming or outgoing traffic.

The "logging" parameter toggles UFW logging. Logged packets use the LOG_KERN syslog facility.

The "state" parameter specify to enable or disable firewall. Four options are possible:

  • "enabled" reloads firewall and enables firewall on boot,
  • "disabled" unloads firewall and disables firewall on boot,
  • "reloaded" reloads firewall,
  • "reset" disables and resets firewall to installation defaults.

rule-specific parameters

  • rule _string_ - allow / deny / limit / reject
  • name _string_ (app) - /etc/ufw/applications.d
  • port _string_ (to_port) - destination port
  • proto _string_ - any / tcp / udp / ipv6 / esp / ah/ gre /igmp

Now let's move to four rule-specific parameters.

The "rule" parameter adds a firewall rule with four options available: "allow" / "deny" / "limit" / "reject".

The "name" parameter, also called "app", uses a profile located in /etc/ufw/applications.d.

The "to_port" parameter, also called "port", specifies the destination port. It could be a single port or a range for example (60000:61000).

The "proto" parameter specifies the destination protocol.

Playbook

Let's jump in a real-life Playbook about how to

open firewall ports in Debian-like systems with Ansible Playbook.

  • verify-firewall.sh

``bash

apt list nginx

sudo ufw status

sudo ufw status verbose

`

  • ufw.yml

``yaml

---

  • name: ufw module Playbook

hosts: all

become: true

tasks:

  • name: nginx installed

ansible.builtin.apt:

name: "nginx"

state: "present"

update_cache: true

  • name: ufw enabled

community.general.ufw:

state: "enabled"

policy: "deny"

logging: "on"

  • name: ufw rules

community.general.ufw:

rule: "allow"

port: "{{ item }}"

proto: "tcp"

with_items:

- "22"