How to pass variables between modules

Hello

I am trying to figure out how to pass variables between submodules of my configuration.nix… been struggling a long time but no luck. In this case it is the hostname and I first tried with config.networing.hostName but not found. I’ve tried to make it more general but still no good. How could I make this work? And how would I do it if I didn’t have a dedicated variable hostname but just used config.networking.hostName?

configuration.nix

{ pkgs, ... }:

let
  hostname = "thinkpad";

in
{
  imports =
    [
      ../home.nix { inherit hostname; }
];

  networking.hostName = hostname;
}

home.nix

{ hostname, config, lib, pkgs, ...}:
{
  #
  # Home Manager
  #

  home-manager.users.spirou = { hostname, config, lib, pkgs, ... }: {
    home.stateVersion = "22.05";
    home.username = "spirou";

    imports = [
      ./x11/i3.nix { inherit hostname; }
];
};
}

i3.nix

{ hostname, config, lib, pkgs, ... }:

{
  xsession.windowManager.i3 = with pkgs; {
    enable = true;
    package = i3-gaps;

    config = rec {
       startup = [
        {
          # Restore resolution
          command = lib.mkMerge [
            (lib.mkIf (hostname == "thinkpad")
              "exec --no-startup-id xrandr --output eDP-1 --mode 1920x1200" )
            (lib.mkIf (hostname == "mainframe")
              "exec --no-startup-id xrandr --output HDMI-0 --mode 1920x1200" )
          ];

          always = false;
          notification = false;
        }
            
      ];
    };
  };
}

Output:

error: The option `hostname' does not exist. Definition values:
       - In `/.../configuration.nix': "thinkpad-nixos"
(use '--show-trace' to show detailed location information)

I am using the latest nixos.

1 Like

You can’t.

Though home manager specifically also provides osConfig or systemConfig, I never remember the exact name, to be able to access the systems configuration.

Thanks. It’s osConfig.


{ lib, pkgs, osConfig, ... }:

Using osConfig in your home-manager modules makes it difficult to use them in a pure home-manager, outside of NixOS, situation though.

I’d rather pass the specific value in from NixOS using home-manager.extraSpecialArgs.

Which doesn’t make it any easier to use that module standalone.

passthru might be what you want

1 Like

Another option although not quite as clean is to have a different file per machine that just sets a HOSTNAME variable and then use that to refer to the hostname via config.home.sessionVariables.HOSTNAME.

1 Like

I think it does, because you can then just pass the equivalent value in extraSpecialArgs in your flake for standalone HM hosts.

1 Like

If you assume flakes, yes. Though I have not seen flakes being mentioned anywhere and ssumed a channel based configuration.