Passing Environment Variable to nixos-rebuild

I have a nixos system flake in some directory ${FLAKE_PATH}.
I have a file ${FLAKE_PATH}/mutable_file I mutably map to ${HOME}/mutable_file.
I do this using home-manager’s mkOutOfStoreSymlink.
This allows me to version it in my flake but also make changes to it without having to rebuild the system.

Currently, I have to hardcode ${FLAKE_PATH}.
But I want to pass it in as an environment variable.

This works:

FLAKE_PATH='...' nix flake check --impure

where flake.nix is

{
  outputs = _: assert builtins.getEnv "FLAKE_PATH" != ""; {};
}

But for invocations of nixos-rebuild, it does not.

What would be the best way to pass that env var to nixos-rebuild? Will it be necessary to manually do the steps in nixos-rebuild?

How are you setting the envvar, and what is the exact rebuild command you’re running after you set the envvar?

I tried

export FLAKE_PATH="$(realpath "$(dirname "${0}")")"                       
sudo nixos-rebuild switch --impure --verbose --show-trace --flake '.'

and

FLAKE_PATH="..." sudo nixos-rebuild switch --impure --verbose --show-trace --flake '.'

Instead of sudo, use either sudo -E to preserve envvars, or --use-remote-sudo which will only run sudo when needed.

1 Like

Perfect, that works:

sudo --preserve-env=FLAKE_PATH nixos-rebuild switch --impure ...

Thanks a lot!