Hostname variable in flake.nix

I want to use this this flake for different hosts in the directory ./hosts/hostname with different configuration files for each host. So I can copy this flake for every host without needing to change it. I want to get the hostname of the machine and make the correct configuration.nix. If possible I also want to make home-manager, that in the homeConfiguration it uses a user variable from the active user like the hostname.

{
	description = "My NixOS configuration";

	inputs = {
		nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.11";
		home-manager = {
			url = "github:nix-community/home-manager/release-24.11";
			inputs.nixpkgs.follows = "nixpkgs";
		};
	};

	outputs = { self, nixpkgs, home-manager, ... } @ inputs:
		let
			pkgs = import nixpkgs { system = "x86_64-linux"; };
			hostname = builtins.getEnv "HOSTNAME";
		in {
			nixosConfigurations = {
				${hostname} = nixpkgs.lib.nixosSystem {
					modules = [ ./hosts/${hostname}/configuration.nix ];
				};
			};

			homeConfigurations = {
				maxe = home-manager.lib.homeManagerConfiguration {
					pkgs = import nixpkgs { system = "x86_64-linux"; };
					modules = [ ./hosts/${hostname}/home.nix ];
				};
			};

			packages.x86_64-linux.default = pkgs.writeShellScriptBin "show-hostname" ''
        			echo "Hostname is ${hostname}"
      			'';
		};
}

If I try to rebuild the system I get the following error:

error: flake 'path:/home/maxe/nix' does not provide attribute 'packages.x86_64
linux.nixosConfigurations."thinkpad".config.system.build.nixos-rebuild', 'legacyPackages.x86_64
linux.nixosConfigurations."thinkpad".config.system.build.nixos-rebuild' or
'nixosConfigurations."thinkpad".config.system.build.nixos-rebuild'

I asked ChatGPT and did the following:

export HOSTNAME=$(hostname)

and

sudo nix build .

but it still doesn’t work
thanks for every help

Stop doing this. Just set the hostnames explicitly. getEnv and other impure commands aren’t supported with flakes anyway, and it’s a bad design to rely on the environment you happen to be running in.

LLMs are also clueless about nix, so that’s not too surprising.

1 Like