Define declarative certificate generation

I need to generate self-signed certificate with OpenSSL, which will act as CA certificate. Usual imperative process looks like this:

  1. openssl genrsa -des3 -out ca.key 4096
  2. openssl req -new -x509 -days 365 -key ca.key -out ca.crt

Is there any way to define certificate generation and signature with NixOS language(in other words - declaratively)?

It depends a bit on what you really want to do.
Technically, you can generate a certificate in a derivation, but that’s usually A Bad Idea™, as the results of a derivation - which would include the private key for the certificate - are world-readable.
You also have an issue with reproducability, the certificate could be regenerated pretty much at a random time… or never, even when you need to recreate it.

The common thing to do is to have a derivation that outputs a simple script that generates the certificate if it does not exist on the system.
Just call that script before you start whatever needs the certificate.
That’s basically what the SSH module for NixOS does. before starting sshd it checks if the key already exists. If not, it generates a new ssh key for the host.
The interesting part is around line 417:

I had the same problem (maybe in a different context). Here is my answer: Add FQDN and TLS trust management (example extension) by blaggacao · Pull Request #28 · numtide/devshell · GitHub