Install NixOS on the volume using a custom configuration.nix
Unmount the volume
Create an AMI from the volume
Terminate the instance
After much Googling, the only thing I’ve found that does something like this is the script for generating AMIs for a NixOS release. It doesn’t really generalize to other use cases though.
This seems like a really obvious thing to want to do if you use NixOS on AWS. Is there some gotcha that makes this a bad idea? If not, how are peopling handing it?
I had to do this recently, and the way I did it was:
Spin up a stock NixOS instance
Configure it as I want (not forgetting to add imports = [ <nixpkgs/nixos/maintainers/scripts/ec2/amazon-image.nix> ]; to the config)
Create /etc/NIXOS_LUSTRATE (to wipe all the mutable state on the instance at next reboot, see NixOS - NixOS 21.05 manual)
Create the AMI from the instance (I did it from the web interface, but I assume it’s possible to do from the cli too).
The NIXOS_LUSTRATE part is important because the ec2 module includes some scripts to configure the instance at startup (like getting the ssh key from AWS if you specified one), but does it only at the first boot, so we have to remove all mutable state to be sure that this configuration will be done again next time we start an instance with this AMI.
It should be easy to adapt this to a custom NixOS configuration. The line in the script that does the image building is nixpkgs/create-amis.sh at master · NixOS/nixpkgs · GitHub . You should be able to just reference your configuration in the imports list there.