vmix.nix/lib/images/linux/customizeImage.nix
Git Sagar f586fa8b6a use pre-built guestfs appliance via libguestfs-with-appliance
Set LIBGUESTFS_PATH so virt-customize uses the nixpkgs pre-built
appliance instead of building one at runtime.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-06-15 10:25:58 -03:00

60 lines
2.4 KiB
Nix

# wrapper function around virt-customize to create custom Linux image from an original OS image
{ pkgs, lib, ... }:
originalImage: {
name ? "",
hostname ? "",
nameToHostname ? true,
diskSize ? "",
smp ? 2,
memSize ? 1024,
install ? [],
run ? "",
commands ? "",
debug ? false,
impure ? true,
# Linux-only: script to run on first boot (via systemd --firstboot)
firstboot ? ""
}:
let
originalImageName = lib.strings.removeSuffix "-vmix" (lib.strings.removeSuffix ".qcow2" originalImage.name);
customImageName = (if name != "" then name else "custom") + "-${originalImageName}-vmix.qcow2";
resultImg = "./disk.qcow2";
setHostname = if hostname != "" then hostname else if nameToHostname then name else "";
virtCustomizeArgsHostname = if setHostname != "" then "--hostname '${setHostname}'" else "";
virtCustomizeArgsInstall = if install != [] then "--install '${lib.strings.concatStringsSep "," install }'" else "";
virtCustomizeArgsCommandsFile = if commands != "" then ("--commands-from-file " + pkgs.writeText "${name}-virt-customize-commands-file" commands) else "";
virtCustomizeArgsRun = if run != "" then ("--run " + pkgs.writeScript "${name}-virt-customize-run-script" "${run}") else "";
virtCustomizeArgsFirstboot = lib.optionalString (firstboot != "")
("--firstboot " + pkgs.writeScript "${name}-firstboot" firstboot);
builderCommand = ''
export PATH="${pkgs.qemu}/bin:${pkgs.curl}/bin:$PATH"
# create resulting image backed by original image
qemu-img create -f qcow2 -b ${originalImage} -F qcow2 ${resultImg}
[ -n "${diskSize}" ] && qemu-img resize ${resultImg} ${diskSize}
# run script inside image using virt-customize
export LIBGUESTFS_PATH="${pkgs.libguestfs-with-appliance}/lib/guestfs"
export LIBGUESTFS_APPEND="ipv6.disable=1"
${pkgs.guestfs-tools}/bin/virt-customize \
${lib.optionalString debug "-v"} \
-a ${resultImg} \
--smp ${builtins.toString smp} \
--memsize ${builtins.toString memSize} \
${virtCustomizeArgsHostname} \
${virtCustomizeArgsInstall} \
${virtCustomizeArgsFirstboot} \
${virtCustomizeArgsCommandsFile} \
${virtCustomizeArgsRun}
mv ${resultImg} $out
'';
builtImage = pkgs.runCommand customImageName (lib.optionalAttrs impure { __noChroot = true; }) builderCommand;
in
builtImage // { _vmixOsType = "linux"; }