๐Ÿ“— Ansible playbooks and roles for building an idempotent, interconnected and scalable infrastructure
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
ansible-playbooks/roles/iptables/templates/iptables.j2

69 lines
2.7 KiB

2 years ago
{%- macro iptables_param(name, value, ns) -%}
{% set has_not_operator = name.startswith('not_') -%}
{% set filtered_name = name[4:] if name.startswith('not_') else name -%}
{% if iptables_mappings[filtered_name] is not mapping -%}
{%- include 'no iptables mapping for "' ~ filtered_name ~ '"' -%}
{% elif iptables_mappings[filtered_name].param is not string -%}
{%- include 'no param in iptables mapping for "' ~ filtered_name ~ '"' -%}
{% else -%}
{% set mapping = iptables_mappings[filtered_name] -%}
{% if mapping.module is string and ns.module != mapping.module -%}-m {{ mapping.module }} {% endif -%}
{% if has_not_operator == true -%}! {% endif -%}
{% if mapping.param | length == 1 -%}-{{ mapping.param }} {% else -%}--{{ mapping.param }} {% endif -%}
{%- set new_value = (value | join(mapping.join | d(','))) if value | type_debug == 'list' else value -%}
{%- set new_value = (new_value | upper) if mapping.upper | d(false) == true else (new_value | lower) if mapping.lower | d(false) == true else new_value -%}
{%- set new_value = mapping.if_true if value is boolean and value == true and mapping.if_true is string else new_value -%}
{%- set new_value = mapping.if_false if value is boolean and value == false and mapping.if_false is string else new_value -%}
{{- new_value -}}
{%- if mapping.module is string -%}
{%- set ns.module = mapping.module -%}
{%- endif -%}
{%- endif -%}
{%- endmacro -%}
{% macro iptables_rule(chain, rule) -%}
{%- set ns = namespace(module='') -%}
-A {{ chain | upper -}}
{%- for param in rule | d({}) | dict2items -%}
{{- ' ' -}}
{{- iptables_param(param.key, param.value, ns) -}}
{%- endfor -%}
{% endmacro -%}
{% macro iptables_table(name, params) -%}
{% if params is mapping and (params | dict2items | length > 0) -%}
*{{ name }}
{% for policy in params.default_policy | d({}) | dict2items -%}
:{{ policy.key | upper }} {{ policy.value | upper }}
{% endfor -%}
{% for section in params | dict2items -%}
{% if section.key != 'default_policy' -%}
{% if section.value | type_debug == 'list' -%}
{% for rule in section.value -%}
{{ iptables_rule(section.key, rule) }}
{% endfor -%}
{% elif section.value is mapping -%}
{{ iptables_rule(section.key, section.value) }}
{% endif -%}
{% endif -%}
{% endfor -%}
COMMIT
{% endif -%}
{%- endmacro -%}
{{- iptables_table('filter', firewall_cfg.filter | d({})) }}
{{ iptables_table('nat', firewall_cfg.nat | d({})) }}
{{ iptables_table('mangle', firewall_cfg.mangle | d({})) }}
{{ iptables_table('raw', firewall_cfg.raw | d({})) -}}