Skip to content

Instantly share code, notes, and snippets.

@cmacrae
Last active January 9, 2020 14:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmacrae/cce363ffdefa7488a0ff577b40f62793 to your computer and use it in GitHub Desktop.
Save cmacrae/cce363ffdefa7488a0ff577b40f62793 to your computer and use it in GitHub Desktop.

About

I'm using the following expressions to generate some DHCP & DNS config.
These work, but I fear I'm perhaps missing out on the use of some other functions available in the stdlib that could do this a bit "nicer".

I could let slurp = a: b: builtins.toString (catAttrs "${a}" (singleton b)) to trim it down a bit.
But I was wondering if anyone had any advice on how to write these better?

{ config, pkgs, lib, ... }:
let
domain = "my.tld";
ipReservations = {
compute1.ip = "10.0.10.1";
compute1.mac = "b8:ae:ed:7d:1b:7e";
compute2.ip = "10.0.10.2";
compute2.mac = "b8:ae:ed:7d:19:06";
compute3.ip = "10.0.10.3";
compute3.mac = "b8:ae:ed:7d:1a:09";
ps4.ip = "10.0.1.3";
ps4.mac = "f8:46:1c:39:f4:97";
xbox.ip = "10.0.1.4";
xbox.mac = "98:5f:d3:f6:87:b1";
};
in with lib; {
/* This yeilds a list like this:
*
* [
* {
* hostName = "compute1.my.tld";
* ethernetAddress = "b8:ae:ed:7d:1b:7e";
* ipAddress = "10.0.10.1";
* }
* {
* hostName = "compute2.my.tld";
* ethernetAddress = "b8:ae:ed:7d:19:06";
* ipAddress = "10.0.10.2";
* }
* {
* hostName = "compute3.my.tld";
* ethernetAddress = "b8:ae:ed:7d:1a:09";
* ipAddress = "10.0.10.3";
* }
* {
* hostName = "ps4.my.tld";
* ethernetAddress = "f8:46:1c:39:f4:97";
* ipAddress = "10.0.1.3";
* }
*
* {
* hostName = "xbox.my.tld";
* ethernetAddress = "98:5f:d3:f6:87:b1";
* ipAddress = "10.0.1.4";
* }
* ]
*/
machines = mapAttrsToList (machine: attributes:
{
hostName = "${machine}.${domain}";
ethernetAddress = builtins.toString (catAttrs "mac" (singleton attributes));
ipAddress = builtins.toString (catAttrs "ip" (singleton attributes));
}
) ipReservations;
/* This yeilds a string like this:
*
* local-data: "compute1.my.tld. IN A 10.0.10.1"
* local-data: "compute2.my.tld. IN A 10.0.10.2"
* local-data: "compute3.my.tld. IN A 10.0.10.3"
* local-data: "ps4.my.tld. IN A 10.0.1.3"
* local-data: "xbox.my.tld. IN A 10.0.1.4"
*/
someDnsConfig = ''
${concatStringsSep "\n"
(mapAttrsToList (name: attributes:
''local-data: "${name}.${domain}. IN A ${builtins.toString (catAttrs "ip" (singleton attributes))}"''
) ipReservations)
}
'';
}
@cmacrae
Copy link
Author

cmacrae commented Jan 9, 2020

Some advice from tilpner on #nixos 🙏

<tilpner> cmacrae: Subjective style thing, but you could use a function to
	  construct the .ip, .mac attrsets			        [14:28]
<tilpner> cmacrae: machine = ip: mac: { inherit ip mac; }
<tilpner> And then ipReservations = { compute1 = machine "10.0.0.1"
	  "b8:ae:ed:7d:1b:7e"; };

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment