I wrote an article “Block device file-system auto-creation on NixOS”.
It explains in some detail and with links to the code how declarative block-device initialisation in NixOS / NixOps works.
Quoting the summary here:
NixOS already contains all the functionality needed to auto-format and auto-mount block devices upon attachment.
For example, to do it with an AWS EBS volume, you only need:
{ fileSystems."/data" = { autoFormat = true; fsType = "ext4"; device = "/dev/xvdb"; }; services.udev.extraRules = '' ACTION=="add", SUBSYSTEM=="block", KERNEL=="xvdb", ENV{SYSTEMD_WANTS}+="${utils.escapeSystemdPath "/data"}.mount" ''; }
Read the full article, or suggest improvements, here:
https://github.com/nh2/nixos-blockdevice-attachment-explanations