Set environment variables for nix build

I have a nix flakes project that uses flake.parts that fails nix build because the app expects certain environment variables to be set. I added these to the nix shell using shellHook, so building the app works after doing nix develop.

What’s the standard way of setting these env vars? Is there a better way of setting env vars within the shellHook?

You can add them to env like this in your derivation

Functions like mkDerivation usually set all their arguments as environment variables for the build. This is what you’re supposed to do; you’re supposed to have the derivation include the environment variable, not set it in shellHook. It’s impossible to say what specifically you should do without seeing your nix expressions.

I’m not entirely sure which function from flake-parts calls mkDerivation. Unfortunately, it seems working with nix libraries makes things harder to follow. For example, I stopped using https://devenv.sh/ because I couldn’t debug an error message that came up during nix flake check even though devenv was convenient for provisioning services.

I’d expect adding

flake = {
  MY_ARG = "foo";
};

within the call to flake-parts.lib.mkFlake would work. However, the build still fails for the same reason as before. The app can’t read the environment variable during nix build.

I’ve been following examples from repos on github that export their environment variables using shellHook like https://github.com/srid/flake-root/blob/f1c0b93d05bdbea6c011136ba1a135c80c5b326c/flake-module.nix#L27-L33

The flake I’m working on is at https://github.com/newton-migosi/mdn-local-library-tutorial/blob/747a605a69b6bb41775954a1e9f8f02e356af02b/flake.nix … there’s nothing project specific that’s failing atm, everything works locally but I’d like nix build to work as well.

You would probably need to change something in haskellPackages.default:

maybe overrides, though I’m not familiar enough with haskell-flake to know what exactly to do here

haskell-flake defines its options at https://github.com/srid/haskell-flake/blob/a72d4c3a4e9656766f5a5315ac5358417d21b78e/nix/modules/project.nix … couldn’t make out what option to use from the source code though

haskell-flake has an overrides option that allows you to override any Haskell package (dependency or local package). Specifically you want overrideAttrs. You might also want to put the env var in the shellHook so the language server knows about it as well.

I’ve provided an example here,

1 Like