Add country-based IP blocking for Caddy via Ansible
Some checks failed
Ansible Lint Check / check-ansible (push) Failing after 37s
Nix Format Check / check-format (push) Failing after 1m39s
Python Lint Check / check-python (push) Failing after 23s

- Introduce generate_country_blocks.py to fetch IP ranges by country
- Update group_vars/servers.yml with country blocking settings
- Add country_block snippet to Caddyfile and apply to all sites
- Create Ansible tasks for automated IP range generation and integration
- Add documentation for configuring and managing country blocking
This commit is contained in:
2025-06-15 01:30:42 +02:00
parent 020c32e8fe
commit 0f35a7b9e2
7 changed files with 487 additions and 3 deletions

View File

@@ -0,0 +1,52 @@
---
- name: Country blocking setup for Caddy
block:
- name: Ensure Python requests module is installed
ansible.builtin.pip:
name: requests
state: present
when: enable_country_blocking | default(false)
- name: Copy country blocking script
ansible.builtin.copy:
src: generate_country_blocks.py
dest: "{{ caddy_service_dir }}/generate_country_blocks.py"
mode: '0755'
when: enable_country_blocking | default(false)
- name: Generate country IP ranges
ansible.builtin.command:
cmd: "python3 {{ caddy_service_dir }}/generate_country_blocks.py {{ blocked_countries_codes | join(' ') }} --format=list"
register: country_ranges_result
when:
- enable_country_blocking | default(false)
- blocked_countries_codes | default([]) | length > 0
changed_when: false
- name: Set country IP ranges fact
ansible.builtin.set_fact:
blocked_countries: "{{ country_ranges_result.stdout.split('\n') | select('match', '^[0-9]') | list }}"
when:
- enable_country_blocking | default(false)
- country_ranges_result is defined
- country_ranges_result.stdout is defined
- name: Display blocked countries info
ansible.builtin.debug:
msg:
- "Country blocking enabled: {{ enable_country_blocking | default(false) }}"
- "Countries to block: {{ blocked_countries_codes | default([]) | join(', ') }}"
- "IP ranges found: {{ blocked_countries | default([]) | length }}"
when: enable_country_blocking | default(false)
- name: Fallback to empty list if no ranges generated
ansible.builtin.set_fact:
blocked_countries: []
when:
- enable_country_blocking | default(false)
- blocked_countries is not defined
tags:
- caddy
- security
- country-blocking