Published on

Different Ways to Set Up Environment Variables in Nix/NixOS

Authors

This post is part of a series about NixOS. The series is done in support of my upcoming Opus Magnum, "Practical NixOS: the Book", and you can read the detailed post here.

In the configuration.nix

If you're managing your system's configuration declaratively (e.g. already using NixOS), you can use the environment.sessionVariables attribute in configuration.nix. This attribute allows you to define environment variables that will be available to all users in the system.

Here's an example of how you can set environment variables in configuration.nix:

{ config, pkgs, ... }:

{
  environment.sessionVariables = {
    MY_VARIABLE = "my-value";
    ANOTHER_VARIABLE = "another-value";
  };
}

Via ShellHook

You may also want to set up the env vars for the nix-shell:

let
  pkgs = import <nixpkgs> {};

in pkgs.mkShell rec {
  name = "my-shell";

  buildInputs = with pkgs; [
    # Add your packages here
  ];

  shellHook = ''
    export MY_VARIABLE="my-value"
    export ANOTHER_VARIABLE="another-value"
  '';
}

Directly in the mkDerivation

This one is less obvious and may bring some confusion when reading someone else's sources, unless you already know the trick. If you're building some package using mkDerivation, you can pass the variables directly as attributes.

with import <nixpkgs> {};

buildPythonPackage {
  name = "test";

  buildInputs = [ pkgs.python pkgs.libxml2 ];

  src = null;

  MY_VARIABLE = "my-value";
  ANOTHER_VARIABLE = "another-value";
}
Made it this far? Enjoying the read?
Sign up for the newsletter to never miss a post