Skip to content

Instantly share code, notes, and snippets.

@DrPsychick
Last active November 13, 2022 00:08
Show Gist options
  • Save DrPsychick/1db0e7baba2faec78f19490c805a8eb4 to your computer and use it in GitHub Desktop.
Save DrPsychick/1db0e7baba2faec78f19490c805a8eb4 to your computer and use it in GitHub Desktop.
Packer build for Ubuntu Server ISO
variables {
iso_url = ""
iso_checksum = "sha256:"
build_dir = "/data/images/build"
build_name = "ubuntu2204"
output_dir = "/data/images/output"
image_name = "ubuntu2204-base"
http_dir = "packer/linux/base/cloudinit/ubuntu2204-autoinstall"
}
source "qemu" "ubuntu-server" {
accelerator = "kvm"
# q35 does not create a floppy by default
machine_type = "q35"
boot_key_interval = "50ms"
boot_command = ["<esc><wait>c", "linux /casper/vmlinuz ", "--- ", "autoinstall ", "ds='nocloud-net;s=http://{{ .HTTPIP }}:{{ .HTTPPort }}/'", "<enter><wait>", "initrd /casper/initrd", "<enter>", "boot<enter>"]
boot_wait = "5s"
disk_compression = false
disk_discard = "unmap"
disk_interface = "virtio"
disk_size = 10000
firmware = "/usr/share/ovmf/OVMF.fd"
format = "qcow2"
headless = true
host_port_max = 2209
host_port_min = 2201
http_directory = "${var.http_dir}"
http_port_max = 10089
http_port_min = 10081
iso_checksum = "${var.iso_checksum}"
iso_url = "${var.iso_url}"
net_device = "virtio-net"
output_directory = "${var.build_dir}/${var.build_name}"
qemuargs = [["-m", "2048M"], ["-smp", "cores=2,threads=2"]]
skip_compaction = true
shutdown_command = "echo 'packer' | sudo -S shutdown -P now"
ssh_password = "packer"
ssh_port = 22
ssh_username = "ubuntu"
ssh_wait_timeout = "20m"
vm_name = "${var.image_name}"
vnc_bind_address = "0.0.0.0"
vnc_port_max = 5901
vnc_port_min = 5901
}
build {
name = "${var.build_name}"
sources = ["source.qemu.ubuntu-server"]
# cleanup within the image
provisioner "shell" {
inline = [
"echo 'packer' | sudo apt upgrade -y",
"echo 'packer' | sudo apt auto-remove -y",
"echo 'packer' | sudo apt clean -y",
"echo 'packer' | sudo rm -rf /var/lib/apt/lists/*",
"echo 'packer' | sudo cloud-init clean",
]
}
# cleanup and compress the image
post-processor "shell-local" {
inline = [
"sudo virt-sysprep -a ${var.build_dir}/${var.build_name}/${var.image_name}",
"qemu-img convert -W -c -O qcow2 ${var.build_dir}/${var.build_name}/${var.image_name} ${var.output_dir}/${var.image_name}.qcow2",
"sudo rm -rf ${var.build_dir}/${var.build_name}",
# generate pkrvars for a build referencing this image (url + checksum)
"checksum=$(sha256sum ${var.output_dir}/${var.image_name}.qcow2 | awk '{print $1}')",
"echo 'iso_url = \"${var.output_dir}/${var.image_name}.qcow2\"\niso_checksum = \"'sha256:$checksum'\"' > packer/linux/${var.image_name}.pkrvars.hcl"
]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment