Generating keys on first boot

Can I have nixos to generate keys when they don’t exist/on first install? I can of course do it manually with ssh, but I’d prefer to have as much things done declaratively as possible.

I do not want to provide any keys to the machine. I want it to generate them itself and then I can either retrieve public keys with ssh or have it register its public key somewhere.

As I understand it something similar must be already happening as part of sshd installation, but I assume there is some general way to run commands to setup the system?

Right now I’m interseted mostly in ssh keys and wireguard, but if there is a general solution, I’d be more interested in that I guess.

This is how the openssh module does it:

I.e., it adds a script that does it to the systemd unit’s ExecStartPre.

This works well for ssh because it has a nice built-in way of distributing keys. I’m less sure how you’d go about distributing keys for wireguard, but you can add an ExecStartPre pretty easily.

A “generic solution” is tricky, because NixOS doesn’t manage secrets. You could add a module that runs a service on startup that generates keys, and then add something similar to what sops/agenix do that you can pass to passwordFile and secretFile options, but not all keys are in the same format, so it would probably not be much more ergonomic than writing ExecStartPres.