From bf4fd2c82d8697618d7bcb6148704d142701a7aa Mon Sep 17 00:00:00 2001 From: Timotej Lazar Date: Thu, 15 May 2025 14:55:43 +0200 Subject: [PATCH] alpine: support non-VM hosts in interfaces template Ignore OOB management interface, allow configuring loopback interface with NetBox data, and setting MTU. --- filter_plugins/util.py | 21 +++++++++++++++++++++ roles/alpine/templates/interfaces.j2 | 20 +++++++++++++++++--- 2 files changed, 38 insertions(+), 3 deletions(-) create mode 100644 filter_plugins/util.py diff --git a/filter_plugins/util.py b/filter_plugins/util.py new file mode 100644 index 0000000..af5d1b7 --- /dev/null +++ b/filter_plugins/util.py @@ -0,0 +1,21 @@ +#!/usr/bin/python + +class FilterModule(object): + '''Helper filters to make Ansible less unpleasant''' + def filters(self): + return { + 'defaultattr': self.defaultattr, + 'list2dict': self.list2dict, + } + + def defaultattr(self, objects, attr, val=None): + ''' + Set a default value if the given attribute is not defined for an object. + ''' + yield from (obj | { attr: obj.get(attr, val) } for obj in objects) + + def list2dict(self, items, key): + ''' + Like items2dict but keep entire dictionaries as values. + ''' + return {item[key]: item for item in items} diff --git a/roles/alpine/templates/interfaces.j2 b/roles/alpine/templates/interfaces.j2 index 2c883ed..021e564 100644 --- a/roles/alpine/templates/interfaces.j2 +++ b/roles/alpine/templates/interfaces.j2 @@ -1,9 +1,21 @@ +{# Loopback interface must be present so define it here if none exists. #} +{% if interfaces | rejectattr("name", "==", "lo") %} auto lo iface lo inet loopback -{% for iface in interfaces | selectattr('enabled') %} +{% endif -%} + +{# Skip disabled and OOB management interfaces. #} +{# For VMs we have to set the attribute manually (to false) so rejectattr works. #} +{% for iface in interfaces + | defaultattr('mgmt_only') + | rejectattr('mgmt_only') + | selectattr('enabled') %} auto {{ iface.name }} -iface {{ iface.name }} inet static +iface {{ iface.name }} inet {% if iface.name == "lo" %}loopback{% else %}static{% endif +%} +{% if iface.mtu %} + mtu {{ iface.mtu }} +{% endif %} {% for address in iface.ip_addresses %} address {{ address.address }} {% if address.family.value == 4 %} @@ -21,4 +33,6 @@ iface {{ iface.name }} inet static pre-up echo 0 > /proc/sys/net/ipv6/conf/$IFACE/autoconf {% endif %} -{% endfor %} +{% endfor -%} + +source-directory /etc/network/interfaces.d