populate ip address based on hostname and populate the hostfile with other vm ips

This commit is contained in:
Dennis Frieberg 2025-03-31 02:28:53 +02:00
parent a6db8ef50f
commit cfec4e9f32
Signed by: nerf
SSH key fingerprint: SHA256:zvrU0EwwaNK65M+AqL9IOTRawFq0JZ8QXBASxxGpxmg
7 changed files with 52 additions and 8 deletions

30
nixos/roles/vmNetwork.nix Normal file
View file

@ -0,0 +1,30 @@
# This module assumes that every hostName of a machine in this repo only appears in one of the ip addresses,
# to derive the ip adress based on the hostname this will need patching if we will ever have a vm with multiple
# outward facing network interfaces.
# (other hostnames can appear multiple times)
{
lib,
config,
...
}: let
inherit (lib) lists;
inherit (builtins) elem;
# taken from aza /etc/hosts
hostmap = import ./hostmap.nix;
myhostName = config.networking.hostName;
# We replace our own ip with 127.0.0.1 in /etc/hosts
myhosts = lib.attrsets.concatMapAttrs (ip: hosts:
if (elem myhostName hosts)
# nixos maps the hostname to the loopback 127.0.0.2 by default, so we exclude it here.
# there is also a default localhost to 127.0.0.1 in place
then {"127.0.0.1" = lists.filter (x: x != myhostName) hosts;}
else {${ip} = hosts;})
hostmap;
myIp = (lists.findSingle (x: elem myhostName x.value) (throw "The machine has no ip address in nixos/roles/hostmap.nix") (throw "The ip for this machine is not unique in nixos/roles/hostmap.nix") (lib.attrsToList hostmap)).name;
in {
imports = [
../modules/vmNetwork.nix
];
networking.hosts = myhosts;
vmNetwork.ipv4 = myIp;
}