This is not a problem but rather a nice question.
I am very new to Ansible and want to automate my parts of my online business.
I just developed this playbook (all variables are highly dynamic and get set via the cli).
It is used to open and close ports for firewalls at a digital hosting provider:
---
- name: Open/Close Port in Hetzner Cloud Firewall
hosts: localhost
gather_facts: no
vars:
HCLOUD_TOKEN: stored in ansible_vault
tasks:
- name: Obtain Existing Rules
hetzner.hcloud.firewall_info:
api_token: "{{ HCLOUD_TOKEN }}"
name: "{{ xserver | mandatory }}"
register: fw_info
failed_when: fw_info.hcloud_firewall_info == []
- name: Save New Rule
set_fact:
new_rule:
- "description": null
"destination_ips": []
"direction": "in"
"port": "{{ xport | mandatory }}" # port is a reserved variable
"protocol": "{{ xprotocol | mandatory }}" # could default to tcp but that will probably cause more errors
"source_ips": ["0.0.0.0/0","::/0"]
when: xaction is undefined or xaction == "add" # action is a reserved variable so we stick to the x<variable> scheme
- name: Merge to Final Ruleset (Add)
set_fact:
ruleset: "{{ fw_info.hcloud_firewall_info[0].rules + new_rule }}"
when: xaction is undefined or xaction == "add"
- name: Merge to Final Ruleset (Remove)
set_fact:
ruleset: "{{ fw_info.hcloud_firewall_info[0].rules | rejectattr('port', 'eq', xport) }}" # protocol will probably not matter
when: xaction == "remove"
- name: Apply Ruleset
hetzner.hcloud.firewall:
api_token: "{{ HCLOUD_TOKEN }}"
name: "{{ xserver | mandatory }}" # naming scheme for firewalls is important!
rules: "{{ ruleset | mandatory }}"
state: present
I tried my best with error handling but in the end the module catches everything anyway. What do you think? Is this production-ready or am I missing some best-practices or crucial techniques?
Thanks a lot in advance!