Create Firewalls for Hetzner Cloud using Ansible

Posted April 8, 2021 by Adrian Wyssmann ‐ 1 min read

Firewall for Hetzner Cloud is relatively new, but since I use ansible I really would like to create my firewalls the same way I to all my other stuff

It actually was announced in March this year and has been made available in the hcloud collection v.1.3.0, so ensure you have the latest ansible collection installed in your system. Unfortunately as of today, the official documentation does not mention firewalls yet, but as mentioned here you can run ansible-doc hetzner.hcloud.hcloud_firewall to get the documentation.

It’s pretty easy. In my case I want two firewalls firewall-ssh-only and hcloud_firewall_no_access. Latter shall not have any rules and thus isolate the server instance completely:

---
- hosts: localhost
  become: no
  gather_facts: false
  vars:
    hcloud_firewall_ssh_only: "firewall-ssh-only"
    hcloud_firewall_no_access: "firewall-no-access"

  pre_tasks:
  - name: Firewall for ssh only
    hetzner.hcloud.hcloud_firewall:
      api_token: "{{ hcloud_token }}"
      name: "{{ hcloud_firewall_ssh_only }}"
      state: present
      rules:
        - direction: "in"
          port: "22"
          protocol: "tcp"
          source_ips:
            - 0.0.0.0/0
            - ::/0
    delegate_to: localhost

  - name: Firewall to remove external access completely
    hetzner.hcloud.hcloud_firewall:
      api_token: "{{ hcloud_token }}"
      name: "{{ hcloud_firewall_no_access }}"
      state: present
    delegate_to: localhost

And this is the end-result, where I have my two firewalls

Hetzner cloud firewall
The recently creates firewalls in Hetzner Cloud

… and it’s corresponding rules

Hetzner cloud firewall rules
The rules for firewall 'hcloud_firewall_ssh_only'

That’s it, now you know how to create firewalls for Hetzner Cloud using Ansible.