Using options from the config of one nixosConfiguration in another in a flake-based setup?

I like to refer to an option’s value by name rather than hardcode a value in two places. For example,

services.foo = {
  enable = true;
  port = 9876;
};
networking.firewall.allowedTCPPorts = [ config.services.foo.port ];

I have a few different nixosConfigurations in a single flake.nix, and a few have services that talk to eachother. I was wondering if I could extend the idea of using config values by name across nixosConfigurations when host_b uses some of the services of host_a. For example, if services.foo is configured as above on host_a, then on host_b I might have something like:

services.bar.remote = "host_a:${nixosConfigurations.host_a.config.services.foo.port}";

I don’t have a really thorough understanding of how Nix actually builds the flake yet, or of things like recursive sets, but I can imagine this might not be feasible, or might not be possible at all. I guess the configs (or at least parts of them) of all the systems on which host_b depends would have to get built at the same time, and somehow this would need to be available to host_b’s configuration.nix.

Alternatively I could do a top-down approach and define foo’s port in a module that gets imported into both host_a and host_b, but I prefer the idea of setting the port number where the service originates and having that propagate elsewhere.

If you pass your inputs into your configurations as specialArgs, then you should be able to access the configurations of the other hosts through self if you like.

3 Likes