How to set environment variables with sops-nix?

Hello, I’ve recently managed to set up sops-nix for storing secrets and using it to set the user password.
However, I’m not sure how to set up environment variables with secrets.
For example, if I want to set my github token, do I just do
environment.variables.GITHUB_TOKEN = builtins.readFile /run/secrets/github-token?
In this case, there is an error “access to absolute path ‘/run/secrets/github-token’ is forbidden in pure eval mode (use ‘–impure’ to override)”
Is there a better way to do this?

Doing that would defy the purpose of using sops-nix. builtins.readFile-ing will take the file and place it in your nix store, publicly readable and unencrypted. Luckily pure mode has saved you from leaking your secret here.

One way to fix this is to simply read the file in your shell init:

{ config, ... }: {
  programs.bash.shellInit = ''
    export GITHUB_TOKEN="$(cat ${config.sops.secrets.github-token.path})"

Generally it’s preferred to use whatever mechanism the application you’re trying to give the secret has to read it from a file. gh seems to prefer you using gh auth login.

Also alternatively you could use something like keepassxc and the secret service to provide these secrets to your applications when you use them, instead of setting them at boot with sops-nix. I generally prefer this for things that do not need to have access to the secret at boot (such as gh), because then you can keep the secrets encrypted at rest and don’t need to expose them to your configuration at all.

On personal computers, sops-nix is more useful for wifi or VPN passwords or such.

As a side note, in general when using sops secrets, access their location using the .path attribute of the config option. That way if anything changes on the sops config end you don’t need to propagate that everywhere.

1 Like

Thank you so much for the detailed explanation! I will look into keepassxc