How to avoid mistakes when nixos-rebuild switch'ing on multi-machine flake configuration

My system configuration has grown to encompass several laptops, desktops and servers.

I do this with a flake.nix that contains multiple nixosConfigurations like so:

{
  ...
    nixosConfigurations = {
      p330 = nixpkgs.lib.nixosSystem { ... };
      t14 = nixpkgs.lib.nixosSystem { ... };
      cpx11 = nixpkgs.lib.nixosSystem { ... };
      ...
    };
  ...
}

When I run sudo nixos-rebuild switch .#..., I have a concern that my muscle memory will betray me one day, and accidentally switch to the wrong configuration. Is there a common way to remedy this?

In my case, my configurations are named after the machine’s model, and the hostname is unique to the machine itself. So I cannot check if the nixosConfiguration name matches networking.hostname, since they’re not the same. But I could maintain a mapping.

I just wonder if there’s already a tool for this.

The easy way here is to have a configuration for each hostname (which can be an alias of one of the machine-model configurations), and then have nixos-rebuild switch simply pick the configuration with the matching hostname.

Consider, e.g.:

{
  ...
    nixosConfigurations = rec {
      p330 = nixpkgs.lib.nixosSystem { ... };
      t14 = nixpkgs.lib.nixosSystem { ... };
      cpx11 = nixpkgs.lib.nixosSystem { ... };
      ...
      host-foo = p330;
      host-bar = t14;
    };
  ...
}
3 Likes

fishshell fixed this issue for me and caused others, ces’t la vie…

Adding to @mmarx response, there are also nixosModules."<name>" (docs),

{
  outputs = { self, nixpkgs }: rec {
    nixosModules.conf.imports  = [ ./common ];  # when is a directory and it has a default.nix
    nixosModules.p330.imports  = [ nixosModules.conf ./p330.nix  ];
    nixosModules.t14.imports   = [ nixosModules.conf ./t14.nix   ];
    nixosModules.cpx11.imports = [ nixosModules.conf ./cpx11.nix ];

    nixosConfigurations.maserati = lib.os nixosModules.p330;
    nixosConfigurations.lancia   = lib.os nixosModules.t14;
    nixosConfigurations.lambreta = lib.os nixosModules.cpx11;

    lib.os = cfg: nixpkgs.lib.nixosSystem {
      modules = [ cfg ];
      system  = "x86_64-linux";
      specialArgs.inputs = inputs;
    };
  };
}
1 Like