Copying the nixos-generate image somewhere at the end of the build

Given the following flake it outputs the generated image to result/nixos.qcow2. How can I tell it to copy that file out of the nix store and somewhere else upon completion?

{
  inputs = {
    nixpkgs.url = "github:nixos/nixpkgs/nixos-24.05";
    home-manager.url = "github:nix-community/home-manager/release-24.05";
    unstablepkgs.url = "github:nixos/nixpkgs/nixos-unstable";

    nixos-generators = {
      url = "github:nix-community/nixos-generators";
      inputs.nixpkgs.follows = "nixpkgs";
    };
  };
  outputs = { self, nixpkgs, unstablepkgs, home-manager, nixos-generators, ... }: let
    system = "x86_64-linux";

    unstable = import unstablepkgs {
      inherit system;
      config.allowUnfree = true;
    };

    pkgs = import nixpkgs {
      inherit system;
      config.allowUnfree = true;
    };
  in {
    packages.x86_64-darwin = {
      default = nixos-generators.nixosGenerate {
        inherit system;
        modules = [
          ./hardware-configuration.nix
          ./configuration.nix
        ];
        format = "qcow";
        specialArgs = {
          inherit pkgs unstable home-manager;
          diskSize = 100 * 1024;
        };
      };
    };
  };
}

If you just want the symlink in another place, you can use the --out-link option to nix build:

Unless --no-link is specified, after a successful build, it creates symlinks to the store paths of the installables. These symlinks have the prefix ./result by default; this can be overridden using the --out-link option.

(from https://nix.dev/manual/nix/2.22/command-ref/new-cli/nix3-buildhttps://nix.dev/manual/nix/2.22/command-ref/new-cli/nix3-build)

Otherwise you can capture the output path printed by nix build and use that as an argument to e.g. cp -l
You can also add another output to your flake (packages.buildcopy = writeShellScript ...) that does cp -l ${packages.x86_64-darwin.default} yourdestination and nix run it.

1 Like