Reading env vars into configuration.nix

Is there a way to reference an env var in configuration.nix and home manager?

Let’s say I had something like:

networking.hostName = [env var read happens here];

This is obviously real use, but just an example.

Thanks.

Or am I overthinking this? Is it just something like $HOME or ${HOME}?

I’ll have to try later when I’m at a computer.

I use a secrets manager that will inject env vars for other automation projects. I wanted to use it for my rebuilds. And I need a way around the settings that don’t support file inputs (so no sops, etc will work here).

My system is a single user setup. So this isn’t about secrets in store, etc. it’s secrets in repo, etc.

nix-repl> builtins.getEnv "HOME"
"/home/artturin"

So something like this could work?

networking.hostName = builtins.getEnv "MY_HOST"

Thanks!

Yes, remember that it returns a "" if the env var doesn’t exist or you’re using flakes and don’t pass --impure, so remember to handle that with conditionals and throw.

https://nixos.org/manual/nix/stable/language/builtins.html?highlight=getEnv#built-in-functions

2 Likes