Skip to content

Instantly share code, notes, and snippets.

@noflcl
Created June 21, 2025 02:34
Show Gist options
  • Select an option

  • Save noflcl/349e31bfecfc2b0b7725cbe3cae4ea3a to your computer and use it in GitHub Desktop.

Select an option

Save noflcl/349e31bfecfc2b0b7725cbe3cae4ea3a to your computer and use it in GitHub Desktop.
Two ways you can have optional nix code apply to a system based on the hostname

Hostname based nix code

You will use hostname = config.networking.hostName; to gather the hostname of the device you are running the nixos-rebuild switch command on

{ config, pkgs, ... }:

let
  hostname = config.networking.hostName;
in {

  # Common configuration for all hosts
  imports = [
    ./common.nix
  ];

  # Host-specific configuration
  config = {
    # Users
    users.users = {
      foouser = {
        isNormalUser = true;
        extraGroups = [
          "wheel"
        ];

      };
      caretaker = {
        isSystemUser = true;
      }
    };

    # Enable foouser based on hostname for both desktop and laptop, not server1
    # Enable caretaker system user if hostname is server1
    users.users = {
        foouser.enable = hostname == "desktop" || hostname == "laptop";
        caretaker.enable = hostname == "server1";
    };

    # Packages will install on all hosts
    environment.systemPackages = with pkgs; [
      vim
      git
    ];

    # Enable packages based on hostname
    environment.systemPackages = if hostname == "desktop" then [
      pkgs.code
      pkgs.firefox
    ] else if hostname == "laptop" then [
      pkgs.nmap
    ] else [
        # this else block can be empty, or if you added pkgs here they would install on any system defined that isn't desktop of laptop
    ];

    # Enable services based on hostname
    services.tor.enable = hostname == "laptop";

    services.httpd.enable = hostname == "server1";
  };
}

AttrSets based nix code

You can define attrsets for each host and use them to configure systems as well

{ config, pkgs, ... }:

let
  hostname = config.networking.hostName;

  server1 = {
    services.httpd.enable = true;
    services.ssh.enable = true;
    users.users.caretaker.enable = true;
  };

  desktop = {
    environment.systemPackages = [ pkgs.code pkgs.firefox ];
    users.users.foouser.enable = true;
  };

  laptop = {
    environment.systemPackages = [ pkgs.nmap ];
    users.users.foouser.enable = true;
    services.tor.enable = true;
  };

  hostConfig = {
    server1 = server1;
    desktop = desktop;
    laptop = laptop;
  };

in {

  imports = [
    ./common.nix
  ];

  config = (hostConfig.${hostname} or {});

  # Common configuration
  users.users = {
    foouser = {
      isNormalUser = true;
    };
    caretaker = {
      isSystemUser = true;
    };
  };

  # Install across all systems
  environment.systemPackages = with pkgs; [
    vim
    git
  ];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment