Flakes within a Flake

Is it possible to nest one flake within another in NixOS? I currently utilize flake for setting up NixOS, but I’ve noticed numerous flake configurations designed specifically for nix run .. Can I seamlessly integrate these flakes into my modules to avoid upgrading my flake and only configuring new modules?

nix run accepts a flake reference, so you can run something like nix run github:foo/bar#hello to run “hello” from the flake at the root of foo/bar github repo.

If you want to use other flakes’s outputs in your flake – you would need to add those flakes to your flake’s inputs and then reuse its packages/applications/modules in your flake. As an example:

{
  inputs.other-flake.url = "path:./subflake"; # Relative path to a directory with another flake.nix
  outputs =
    {
      self,
      nixpkgs,
      other-flake,
    }:
    let
      system = "x86_64-linux";
      pkgs = import nixpkgs { inherit system; };
    in
    {
      packages.${system} = {
        default = pkgs.writeShellScriptBin "hello" ''
          echo "Hello from this flake"
        '';
        other-flake-default = other-flake.packages.${system}.default;
      };
    };
}

Results in:

❯ nix run .                    
Hello from this flake

❯ nix run .#other-flake-default
Hello from the other flake

Modules would actually require you to add other flakes to your inputs as modules generally do not work outside of a NixOS environment (outside of calling them as functions or calling lib.evalModules but that’s beside the point).

2 Likes