Custom SSH config for `builtins.fetchGit`?

I run nixos-rebuild as root, but the root user does not have the SSH keys to fetch some private Git repositories, so builtins.fetchGit does not work. How to specify SSH config for builtins.fetchGit to use?

You should be able to use the NIX_SSHOPTS environment variable to add any arguments you want to the ssh command.

I am using multi-user Nix 2.31.2, and it does not seem to work as I tried this:

NIX_SSHOPTS="-o UserKnownHostsFile=/somewhere/known_hosts -i /somewhere/id_ed25519" nix-instantiate --eval --expr 'builtins.fetchGit "git@github.com:some/private-repo"'

Is NIX_SSHOPTS supposed to work like this, or do I need to start the Nix daemon with the env var?

Huh, I guess fetchGit doesn’t respect that.

Does GIT_SSH_COMMAND work instead? Something like this?

GIT_SSH_COMMAND="$(which ssh) -o UserKnownHostsFile=..." nix-instantiate ...
1 Like

NIX_SSH_OPTS only really works for when nix itself is shelling out to ssh. This is not the case for git.

GIT_SSH_COMMAND works. Thank you.

1 Like

In case you are running nixos-rebuild via sudo, the best way is to make sure sudo preserve your user’s SSH_AUTH_SOCK environment variable.

It is possible to do one shot:

$ sudo --preserve-env=SSH_AUTH_SOCK my-cmd

or permanently via:

{
  security.sudo.extraConfig = ''
    Defaults env_keep+=SSH_AUTH_SOCK
  '';
  security.sudo-rs.extraConfig = ''
    Defaults env_keep+=SSH_AUTH_SOCK
  '';
}

In case you are running you command via SSH, it is also possible to forward you SSH agent so that it is made available to the remote host.

It is possible to do one shot:

$ ssh -A user@remote-host my-cmd
# ..

or permanently by editing your ~/.ssh/config:

Host myserver
    HostName remote-host.example.com
    User user
    ForwardAgent yes

IMPORTANT: only do that on trusted remote hosts.

Use --sudo instead of running it as root. That sidesteps all these hacks.