Query prefixes once for all hosts

And group them into vrf_prefixes for VLAN networks and bgp_prefixes for
servers plugged directly into fabric.

This should reduce the number of queries to NetBox when configuring
firewalls and exit switches. Not sure but I think set_fact helps to
avoid queries (as opposed to setting group_vars).
This commit is contained in:
Timotej Lazar 2024-04-28 10:59:32 +02:00
parent 1c0709a6a6
commit 457ab7d3b7
10 changed files with 52 additions and 50 deletions

View file

@ -82,16 +82,13 @@ ipv6 prefix-list default permit ::/0
ip prefix-list fabric permit 10.34.0.0/24 ge 32
{% for vlan in vlans %}
{% for prefix in query('netbox.netbox.nb_lookup', 'prefixes', api_filter='vlan_id='~vlan.id, raw_data=true) %}
{% if prefix.vrf and prefix.vrf.name != 'outside' %}
{% for prefix in vrf_prefixes | rejectattr('vrf.name', '==', 'outside')
| sort(attribute='family.value') %}
{% if prefix.family.value == 4 %}
ip prefix-list office permit {{ prefix.prefix }} ge 24
{% elif prefix.family.value == 6 %}
ipv6 prefix-list office permit {{ prefix.prefix }} ge 64
{% endif %}
{% endif %}
{% endfor %}
{% endfor %}
{% if wg_net is defined %}

View file

@ -1,18 +1,9 @@
{% for vlan in vlans %}
{% set prefixes = query('netbox.netbox.nb_lookup', 'prefixes', api_filter='vlan_id='~vlan.id, raw_data=true) %}
{% set prefixes4 = prefixes | selectattr('family.value', '==', 4) | map(attribute='prefix') %}
{% set prefixes6 = prefixes | selectattr('family.value', '==', 6) | map(attribute='prefix') %}
set {{ vlan.name }} {
type ipv4_addr; flags interval
{% if prefixes4 %}
elements = { {{ prefixes4 | join(', ') }} }
{% endif %}
}
set {{ vlan.name }}/6 {
type ipv6_addr; flags interval
{% if prefixes6 %}
elements = { {{ prefixes6 | join(', ') }} }
{% endif %}
{% for family, family_prefixes in vrf_prefixes | groupby('family.value') %}
{% for vlan, vlan_prefixes in family_prefixes | groupby('vlan.vid') %}
set {{ vlan_prefixes[0].vlan.name }}{% if family == 6 %}/6{% endif %} {
type ipv{{ family }}_addr; flags interval
elements = { {{ vlan_prefixes | map(attribute='prefix') | join(',') }} }
}
{% endfor %}
{% endfor %}

View file

@ -81,13 +81,13 @@ table inet filter {
comment "Forward DNAT traffic for servers and suchlike"
# Forward IPv4 to/from VPN users in the same network.
{% for vlan in vlans %}
iif @inside ip saddr @{{ vlan.name }} ip daddr @{{ vlan.name }} accept
{% for vlan in vrf_prefixes | selectattr('family.value', '==', 4) | map(attribute='vlan.name') | unique %}
iif @inside ip saddr @{{ vlan }} ip daddr @{{ vlan }} accept
{% endfor %}
# Forward IPv6 to/from VPN users in the same network.
{% for vlan in vlans %}
iif @inside ip6 saddr @{{ vlan.name }}/6 ip6 daddr @{{ vlan.name }}/6 accept
{% for vlan in vrf_prefixes | selectattr('family.value', '==', 6) | map(attribute='vlan.name') | unique %}
iif @inside ip6 saddr @{{ vlan }}/6 ip6 daddr @{{ vlan }}/6 accept
{% endfor %}
include "/etc/nftables.d/forward.nft*"