nixos-rebuild and SSH keysIn my homelab I now have a few machines that run NixOS. This came to be because I wanted the ability to quickly rebuild machines from scratch without having to fiddle with individual settings. Thanks to NixOS I now have a repository that holds a flake that can build bootable images and perform remote nixos-rebuild switch.
Having the ability to remotely perform nixos-rebuild switch is great. All changes are tracked in git, I can standardize certain aspects via Nix modules and it covers all aspects of a system, something I never really got to work reliably in Ansible. Remote nixos-rebuild switch works by specifying --target-host user@host which will use ssh to perform switch on the other machine. If pubkeys are set up authentication will be automatic. However, if the remote user is not root, and it shouldn’t be, sudo is required via --sudo and that will require password and with -S nixos-rebuild will ask you for the password. Not ideal.
But there’s a cool thing I didn’t know about: PAM (Pluggable authentication Modules) and sudo support authentication via SSH keys! That means when a ssh client connects and forwards the SSH agent, sudo can use that to authenticate, sidestepping the need for a password!
To enable a ssh key and some configuration is required. The key has to be registered as an authorized key for the remote user:
users.users.myuser = {
isNormalUser = true;
openssh.authorizedKeys.keys = [ "ssh-ed25519..." ];
};
PAM and sudo need to be configured to use rssh. Note: If you use ed25519 keys you must use ssh, if not, you can could use sshAgentAuth.
security.pam = {
rssh.enable = true;
services.sudo.rssh = true;
};
All that’s left is to provide the correct configuration settings to nixos-rebuild --switch:
NIX_SSHOPTS=-A nixos-rebuild switch --target-host myuser@server --sudo ...
NIX_SSHOPTS=-A passes the -A flag to ssh and enables agent forwarding--sudo requests sudo for privilege escalation on the remote machineJakob Külzer’s personal blog