diff options
| author | Eugene Triguba <hello@eugenetriguba.com> | 2026-09-22 17:00:53 -0700 |
|---|---|---|
| committer | Eugene Triguba <hello@eugenetriguba.com> | 2026-10-11 18:33:35 -0700 |
| commit | c9cfdbf86f2bf620c986abb2f67dcaabf5b01047 (patch) | |
| tree | 23be01d9eb5cee38e1919e83d633ceff977f8f78 | |
| parent | Remove need for explicit memory var override (diff) | |
| download | site-server-images-c9cfdbf86f2bf620c986abb2f67dcaabf5b01047.zip | |
Add support for hcloud openbsd image snapshot
20 files changed, 372 insertions, 404 deletions
@@ -1,2 +1,2 @@ -/build -/edk2-arm-vars.fd +/openbsd-image/build +/openbsd-iamge/edk2-arm-vars.fd diff --git a/build-hcloud-snapshot.sh b/build-hcloud-snapshot.sh new file mode 100755 index 0000000..40f3dcb --- /dev/null +++ b/build-hcloud-snapshot.sh @@ -0,0 +1,69 @@ +#!/bin/sh +# +# DESCRIPTION: +# Create a OpenBSD snapshot in Hetzner Cloud. +# +# USAGE: +# ./build-openbsd-image.sh +# export HCLOUD_TOKEN="xxxxx-xxxxx" +# ./build-hcloud-snapshot.sh +# +set -o nounset +set -o errexit + +export PACKER_LOG=1 +SCRIPTDIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P) + +VERSION=7.9 +ARCH=amd64 +PUBLIC_SSH_KEY="$HOME/.ssh/id_rsa.pub" + +main() ( + parse_args "$@" + img_path="${SCRIPTDIR}/openbsd-image/build/openbsd-${VERSION}-${ARCH}.raw" + build_compressed_image "$img_path" + cd "$SCRIPTDIR/hcloud-snapshot/" + packer init . + packer build \ + -var "hcloud_token=${HCLOUD_TOKEN:?}" \ + -var "image_path=${img_path}.zst" \ + -var "version=$VERSION" \ + -var "arch=$ARCH" \ + -var "ssh_key=$(get_ssh_key_name "$PUBLIC_SSH_KEY")" \ + . +) + +parse_args() { + while [ $# -gt 0 ]; do + case "$1" in + --version) + VERSION="$2" + shift 2 + ;; + --arch) + ARCH="$2" + shift 2 + ;; + --public-ssh-key) + PUBLIC_SSH_KEY="$2" + shift 2 + ;; + *) + echo "Unknown option: $1" + shift + ;; + esac + done +} + +build_compressed_image() ( + if [ ! -e "$1.zst" ]; then + zstd -T0 "$1" -o "$1.zst" + fi +) + +get_ssh_key_name() { + awk '{print $3}' "$1" +} + +main "$@" diff --git a/build-openbsd-image.sh b/build-openbsd-image.sh new file mode 100755 index 0000000..b31ebfa --- /dev/null +++ b/build-openbsd-image.sh @@ -0,0 +1,58 @@ +#!/bin/sh +# +# DESCRIPTION: +# Create an OpenBSD image with Packer and QEMU. +# +# USAGE: +# ./build-openbsd-image.sh +set -o nounset +set -o errexit + +VERSION=7.9 +ARCH=amd64 +DISK_SIZE_GB=36 +PUBLIC_SSH_KEY="$HOME/.ssh/id_rsa.pub" + +export PACKER_LOG=1 + +main() ( + parse_args "$@" + cd openbsd-image/ + packer init . + packer build \ + -only "qemu.openbsd-$ARCH" \ + -var "arch=$ARCH" \ + -var "disk_size=$DISK_SIZE_GB" \ + -var "version=$VERSION" \ + -var "ssh_key=$(cat "$PUBLIC_SSH_KEY")" \ + . +) + +parse_args() { + while [ $# -gt 0 ]; do + case "$1" in + --version) + VERSION="$2" + shift 2 + ;; + --arch) + ARCH="$2" + shift 2 + ;; + --disk-size-gb) + DISK_SIZE_GB="$2" + shift 2 + ;; + --public-ssh-key) + PUBLIC_SSH_KEY="$2" + shift 2 + ;; + *) + echo "Unknown option: $1" + shift + ;; + esac + done +} + +main "$@" diff --git a/hcloud-snapshot/main.pkr.hcl b/hcloud-snapshot/main.pkr.hcl new file mode 100644 index 0000000..920eeae --- /dev/null +++ b/hcloud-snapshot/main.pkr.hcl @@ -0,0 +1,22 @@ +packer { + required_plugins { + hcloud = { source = "github.com/hetznercloud/hcloud", version = "~> 1" } + } +} + +build { + sources = ["source.hcloud.openbsd"] + + provisioner "file" { + source = var.image_path + destination = "/tmp/openbsd.raw.zst" + } + + provisioner "shell" { + inline = [ + "which zstd || apt-get install --assume-yes zstd", + "zstd --decompress --stdout /tmp/openbsd.raw.zst | dd of=/dev/sda bs=4M status=progress", + "sync", + ] + } +} diff --git a/hcloud-snapshot/snapshot.pkr.hcl b/hcloud-snapshot/snapshot.pkr.hcl new file mode 100644 index 0000000..d8834c8 --- /dev/null +++ b/hcloud-snapshot/snapshot.pkr.hcl @@ -0,0 +1,10 @@ +source "hcloud" "openbsd" { + token = var.hcloud_token + rescue = "linux64" + image = "debian-13" + server_type = "cx23" + location = "nbg1" + ssh_username = "root" + ssh_keys = [var.ssh_key] + snapshot_name = "openbsd-${var.version}-${var.arch}-golden" +} diff --git a/hcloud-snapshot/variables.pkr.hcl b/hcloud-snapshot/variables.pkr.hcl new file mode 100644 index 0000000..a02e433 --- /dev/null +++ b/hcloud-snapshot/variables.pkr.hcl @@ -0,0 +1,33 @@ +variable "hcloud_token" { + type = string + description = "Hetnzer API token" + sensitive = true +} + +variable "image_path" { + type = string + description = "Path to the built OpenBSD raw zstd compressed image" +} + +variable "version" { + type = string + description = "Version of OpenBSD to build" + validation { + condition = can(regex("^\\d\\.\\d$", var.version)) + error_message = "The version must be a single-digit followed by a period followed by another single digit." + } +} + +variable "arch" { + type = string + validation { + condition = contains(["amd64", "arm64"], var.arch) + error_message = "The arch must be one of: amd64, arm64." + } +} + +variable "ssh_key" { + type = string + description = "SSH key name in Hetzner to add to the image on launch" +} + diff --git a/Makefile b/openbsd-image/Makefile index c1343f9..0c3ae00 100644 --- a/Makefile +++ b/openbsd-image/Makefile @@ -1,3 +1,4 @@ +# TODO: Replace with run-openbsd-image.sh and add ARM support to build-openbsd-image.sh SHELL := /bin/sh ARCH ?= arm64 @@ -6,8 +7,8 @@ EDK2_DIR := /opt/homebrew/share/qemu SSH_PORT := 2222 SSH_USER := admin SSH_KEY := ~/.ssh/id_rsa -CPU := 1 -MEMORY := 4096M +CPU := 8 +MEMORY := 32768M PACKER_LOG := 1 VERSION := 7.9 diff --git a/configs/doas.conf b/openbsd-image/configs/doas.conf index 96cf24d..96cf24d 100644 --- a/configs/doas.conf +++ b/openbsd-image/configs/doas.conf diff --git a/openbsd-image/locals.pkr.hcl b/openbsd-image/locals.pkr.hcl new file mode 100644 index 0000000..f88100f --- /dev/null +++ b/openbsd-image/locals.pkr.hcl @@ -0,0 +1,4 @@ +locals { + version_short = replace(var.version, ".", "") + root_password = "temp" +} diff --git a/openbsd-image/main.pkr.hcl b/openbsd-image/main.pkr.hcl new file mode 100644 index 0000000..43d01dd --- /dev/null +++ b/openbsd-image/main.pkr.hcl @@ -0,0 +1,23 @@ +packer { + required_plugins { + qemu = { source = "github.com/hashicorp/qemu", version = ">= 1.1.0" } + } +} + +build { + sources = ["source.qemu.openbsd-amd64", "source.qemu.openbsd-arm64"] + + provisioner "file" { + source = "configs/doas.conf" + destination = "/etc/doas.conf" + } + + provisioner "shell" { + script = "scripts/setup.sh" + environment_vars = ["ADMIN_USER=${var.admin_user}"] + } + + provisioner "shell" { + script = "scripts/harden-root.sh" + } +} diff --git a/openbsd-image/openbsd-amd64.pkr.hcl b/openbsd-image/openbsd-amd64.pkr.hcl new file mode 100644 index 0000000..5d2c9f7 --- /dev/null +++ b/openbsd-image/openbsd-amd64.pkr.hcl @@ -0,0 +1,42 @@ +source "qemu" "openbsd-amd64" { + vm_name = "openbsd-${var.version}-amd64.raw" + iso_url = "${var.mirror}/pub/OpenBSD/${var.version}/${var.arch}/install${local.version_short}.iso" + iso_checksum = "file:${var.mirror}/pub/OpenBSD/${var.version}/${var.arch}/SHA256" + output_directory = "build" + qemu_binary = "qemu-system-x86_64" + machine_type = "q35" + cpu_model = "max" + accelerator = "tcg" + memory = var.memory + disk_interface = "virtio" + disk_size = "${var.disk_size}G" + disk_compression = true + format = "raw" + ssh_username = "root" + ssh_password = local.root_password + ssh_timeout = "30m" + + http_content = { + "/install.conf" = templatefile("${path.root}/templates/install.conf.pkrtpl.hcl", { + hostname = var.hostname + user = var.admin_user + ssh_key = var.ssh_public_key + root_password = local.root_password + mirror = var.mirror + version = var.version + version_short = local.version_short + arch = var.arch + }) + } + + boot_command = [ + "<wait>S<enter><wait>", + "set tty com0<enter><wait>", + "autoinstall<enter><wait>", + "http://{{ .HTTPIP }}:{{ .HTTPPort }}/install.conf<enter>", + ] + boot_wait = "20s" + shutdown_command = "shutdown -p now" + headless = false + qemuargs = [["-display", "cocoa"]] +} diff --git a/openbsd-image/openbsd-arm64.pkr.hcl b/openbsd-image/openbsd-arm64.pkr.hcl new file mode 100644 index 0000000..dbe5833 --- /dev/null +++ b/openbsd-image/openbsd-arm64.pkr.hcl @@ -0,0 +1,51 @@ +source "qemu" "openbsd-arm64" { + vm_name = "openbsd-${var.version}-aarch64.qcow2" + iso_url = "${var.mirror}/pub/OpenBSD/${var.version}/${var.arch}/install${local.version_short}.iso" + iso_checksum = "file:${var.mirror}/pub/OpenBSD/${var.version}/${var.arch}/SHA256" + output_directory = "build" + qemu_binary = "qemu-system-aarch64" + machine_type = "virt" + cpu_model = "host" + accelerator = "hvf" + memory = var.memory + disk_interface = "virtio" + disk_size = "${var.disk_size}G" + disk_compression = true + format = "qcow2" + ssh_username = "root" + ssh_password = local.root_password + ssh_timeout = "10m" + + http_content = { + "/install.conf" = templatefile("${path.root}/templates/install.conf.pkrtpl.hcl", { + hostname = var.hostname + user = var.admin_user + ssh_key = var.ssh_public_key + root_password = local.root_password + mirror = var.mirror + version = var.version + version_short = local.version_short + arch = var.arch + }) + } + + boot_command = [ + "<wait>S<enter><wait>", + "set tty com0<enter><wait>", + "autoinstall<enter><wait>", + "http://{{ .HTTPIP }}:{{ .HTTPPort }}/install.conf<enter>", + ] + boot_wait = "20s" + shutdown_command = "shutdown -p now" + use_default_display = true + headless = false + qemuargs = [ + ["-device", "qemu-xhci,id=xhci"], + ["-device", "usb-kbd,bus=xhci.0"], + ["-device", "virtio-gpu-pci"], + ["-display", "cocoa"], + ] + efi_firmware_code = "/opt/homebrew/share/qemu/edk2-aarch64-code.fd" + efi_firmware_vars = "./edk2-arm-vars.fd" +} + diff --git a/scripts/harden-root.sh b/openbsd-image/scripts/harden-root.sh index c8e267a..c8e267a 100755 --- a/scripts/harden-root.sh +++ b/openbsd-image/scripts/harden-root.sh diff --git a/scripts/setup.sh b/openbsd-image/scripts/setup.sh index 320d93d..320d93d 100755 --- a/scripts/setup.sh +++ b/openbsd-image/scripts/setup.sh diff --git a/templates/install.conf.pkrtpl.hcl b/openbsd-image/templates/install.conf.pkrtpl.hcl index 9df18ce..9df18ce 100644 --- a/templates/install.conf.pkrtpl.hcl +++ b/openbsd-image/templates/install.conf.pkrtpl.hcl diff --git a/openbsd-image/variables.pkr.hcl b/openbsd-image/variables.pkr.hcl new file mode 100644 index 0000000..4bc0860 --- /dev/null +++ b/openbsd-image/variables.pkr.hcl @@ -0,0 +1,55 @@ +variable "version" { + type = string + description = "Version of OpenBSD to build" + validation { + condition = can(regex("^\\d\\.\\d$", var.version)) + error_message = "The version must be a single-digit followed by a period followed by another single digit." + } +} + +variable "arch" { + type = string + validation { + condition = contains(["amd64", "arm64"], var.arch) + error_message = "The arch must be one of: amd64, arm64." + } +} + +variable "admin_user" { + type = string + description = "Username of the admin user on the VM" + default = "admin" +} + +variable "ssh_public_key" { + type = string + description = "Public SSH key to associate with the admin user for login" +} + +variable "mirror" { + type = string + description = "URL basename for where to download the OpenBSD ISO." + default = "https://cdn.openbsd.org" + validation { + condition = can(regex("^(https?)://", var.mirror)) && !endswith(var.mirror, "/") + error_message = "URL must start with http(s):// and must not have a trailing slash." + } +} + +variable "hostname" { + type = string + description = "Hostname for the VM" + default = "openbsd-vm" +} + +variable "memory" { + type = number + description = "Memory to allocate to the VM in MB while building the ISO" + default = 4096 +} + +variable "disk_size" { + type = number + description = "Size of the disk in GB while building the ISO" + default = 16 +} diff --git a/openbsd.pkr.hcl b/openbsd.pkr.hcl deleted file mode 100644 index bba0327..0000000 --- a/openbsd.pkr.hcl +++ /dev/null @@ -1,182 +0,0 @@ -packer { - required_plugins { - qemu = { source = "github.com/hashicorp/qemu", version = ">= 1.1.0" } - } -} - -variable "version" { - type = string - validation { - condition = can(regex("^\\d\\.\\d$", var.version)) - error_message = "The version must be a single-digit followed by a period followed by another single digit." - } -} - -variable "ssh_public_key" { - type = string - description = "Public SSH key to associate with the admin user for login" -} - -variable "ssh_private_key_file" { - type = string - description = "Private SSH key to associate with the admin user for login" -} - -variable "arch" { - type = string - validation { - condition = contains(["amd64", "arm64"], var.arch) - error_message = "The arch must be one of: amd64, arm64." - } -} - -variable "admin_user" { - type = string - description = "Username of the admin user on the VM" - default = "admin" -} - -variable "mirror" { - type = string - description = "URL basename for where to download the OpenBSD ISO." - default = "https://cdn.openbsd.org" - validation { - condition = can(regex("^(https?)://", var.mirror)) && !endswith(var.mirror, "/") - error_message = "URL must start with http(s):// and must not have a trailing slash." - } -} - -variable "hostname" { - type = string - description = "Hostname for the VM" - default = "openbsd-vm" -} - -variable "memory" { - type = number - description = "Memory to allocate to the VM in MB" - default = 4096 -} - -variable "disk_size" { - type = number - description = "Size of the disk in GB" - default = 16 -} - -locals { - version_short = replace(var.version, ".", "") - root_password = "temp" -} - -source "qemu" "openbsd-amd64" { - vm_name = "openbsd-${var.version}-amd64.qcow2" - iso_url = "${var.mirror}/pub/OpenBSD/${var.version}/${var.arch}/install${local.version_short}.iso" - iso_checksum = "file:${var.mirror}/pub/OpenBSD/${var.version}/${var.arch}/SHA256" - output_directory = "build" - qemu_binary = "qemu-system-x86_64" - machine_type = "q35" - cpu_model = "max" - accelerator = "tcg" - memory = var.memory - disk_interface = "virtio" - disk_size = "${var.disk_size}G" - disk_compression = true - format = "qcow2" - ssh_username = "root" - ssh_password = local.root_password - ssh_timeout = "30m" - - http_content = { - "/install.conf" = templatefile("${path.root}/templates/install.conf.pkrtpl.hcl", { - hostname = var.hostname - user = var.admin_user - ssh_key = var.ssh_public_key - root_password = local.root_password - mirror = var.mirror - version = var.version - version_short = local.version_short - arch = var.arch - }) - } - - boot_command = [ - "<wait>S<enter><wait>", - "set tty com0<enter><wait>", - "autoinstall<enter><wait>", - "http://{{ .HTTPIP }}:{{ .HTTPPort }}/install.conf<enter>", - ] - boot_wait = "20s" - shutdown_command = "shutdown -p now" - headless = false - qemuargs = [["-display", "cocoa"]] -} - -source "qemu" "openbsd-arm64" { - vm_name = "openbsd-${var.version}-aarch64.qcow2" - iso_url = "${var.mirror}/pub/OpenBSD/${var.version}/${var.arch}/install${local.version_short}.iso" - iso_checksum = "file:${var.mirror}/pub/OpenBSD/${var.version}/${var.arch}/SHA256" - output_directory = "build" - qemu_binary = "qemu-system-aarch64" - machine_type = "virt" - cpu_model = "host" - accelerator = "hvf" - memory = var.memory - disk_interface = "virtio" - disk_size = "${var.disk_size}G" - disk_compression = true - format = "qcow2" - ssh_username = "root" - ssh_password = local.root_password - ssh_timeout = "10m" - - http_content = { - "/install.conf" = templatefile("${path.root}/templates/install.conf.pkrtpl.hcl", { - hostname = var.hostname - user = var.admin_user - ssh_key = var.ssh_public_key - root_password = local.root_password - mirror = var.mirror - version = var.version - version_short = local.version_short - arch = var.arch - }) - } - - boot_command = [ - "<wait>S<enter><wait>", - "set tty com0<enter><wait>", - "autoinstall<enter><wait>", - "http://{{ .HTTPIP }}:{{ .HTTPPort }}/install.conf<enter>", - ] - boot_wait = "20s" - shutdown_command = "shutdown -p now" - use_default_display = true - headless = false - qemuargs = [ - ["-device", "qemu-xhci,id=xhci"], - ["-device", "usb-kbd,bus=xhci.0"], - ["-device", "virtio-gpu-pci"], - ["-display", "cocoa"], - ] - efi_firmware_code = "/opt/homebrew/share/qemu/edk2-aarch64-code.fd" - efi_firmware_vars = "./edk2-arm-vars.fd" -} - -build { - sources = ["source.qemu.openbsd-amd64", "source.qemu.openbsd-arm64"] - - provisioner "file" { - source = "configs/doas.conf" - destination = "/etc/doas.conf" - } - - provisioner "shell" { - script = "scripts/setup.sh" - environment_vars = ["ADMIN_USER=${var.admin_user}"] - } - - provisioner "shell" { - script = "scripts/harden-root.sh" - } -} diff --git a/openbsd79-amd64.pkvars.hcl b/openbsd79-amd64.pkvars.hcl deleted file mode 100644 index 7ed83a6..0000000 --- a/openbsd79-amd64.pkvars.hcl +++ /dev/null @@ -1,7 +0,0 @@ -version = "7.9" -arch = "amd64" -disk_size = 40 -ssh_public_key = <<-EOF -ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC31SiCeUZSJN3CueH6/+7UQvxwxkT/QkaDK6ZGdnkdpCWxRVp+0CTO4WG3u0PVEVd9DvSd81CEqrFaKxtKyiSh+4Va0A/mqY27tX7NZzEQLM/zLQrdESmaHY6EyQM0wlCtBKfNzuQqCa9QEw4TwkyMLOJzyI+bRsfeSHNCfxqnqGIMKKFiaF0ygakvQz57nWuKLOgqWsWkzFTuJKGI0OhefFBcZ4VzoCLV8i1zbB2AebhsmbyMza9OUF3px44atSM3o33Jto3gy7LTWtxU83NZU+wLEqY6IvcWx9BbSQZxAwEwXxUFmnzcX+FTkTiOs/Q2nXiLl2ggsGJffAq9Z1SGMCNGxT+Syyta5UtfBVVQdn6xtUxpppHwrdGC+TR8C5F9U12gsZRzvKkz0SSt5M4WHG2gna5rDgTisDbrEAsrqpmUqY9iSBzgAyk5xOi6fdI+r67gpjRSs+PNvDle3gImfIkPnEQg4eWJ54iKjfH+yd8vBk25T/ahu3J9rGgxp18= eugene@laptop -EOF -ssh_private_key_file = "~/.ssh/id_rsa" diff --git a/openbsd79-arm64.pkvars.hcl b/openbsd79-arm64.pkvars.hcl deleted file mode 100644 index 62e0e5e..0000000 --- a/openbsd79-arm64.pkvars.hcl +++ /dev/null @@ -1,7 +0,0 @@ -version = "7.9" -arch = "arm64" -disk_size = 16 -ssh_public_key = <<-EOF -ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC31SiCeUZSJN3CueH6/+7UQvxwxkT/QkaDK6ZGdnkdpCWxRVp+0CTO4WG3u0PVEVd9DvSd81CEqrFaKxtKyiSh+4Va0A/mqY27tX7NZzEQLM/zLQrdESmaHY6EyQM0wlCtBKfNzuQqCa9QEw4TwkyMLOJzyI+bRsfeSHNCfxqnqGIMKKFiaF0ygakvQz57nWuKLOgqWsWkzFTuJKGI0OhefFBcZ4VzoCLV8i1zbB2AebhsmbyMza9OUF3px44atSM3o33Jto3gy7LTWtxU83NZU+wLEqY6IvcWx9BbSQZxAwEwXxUFmnzcX+FTkTiOs/Q2nXiLl2ggsGJffAq9Z1SGMCNGxT+Syyta5UtfBVVQdn6xtUxpppHwrdGC+TR8C5F9U12gsZRzvKkz0SSt5M4WHG2gna5rDgTisDbrEAsrqpmUqY9iSBzgAyk5xOi6fdI+r67gpjRSs+PNvDle3gImfIkPnEQg4eWJ54iKjfH+yd8vBk25T/ahu3J9rGgxp18= eugene@laptop -EOF -ssh_private_key_file = "~/.ssh/id_rsa" diff --git a/tools/create_openbsd_hetzner_snapshot.py b/tools/create_openbsd_hetzner_snapshot.py deleted file mode 100644 index 613b9e6..0000000 --- a/tools/create_openbsd_hetzner_snapshot.py +++ /dev/null @@ -1,204 +0,0 @@ -#!/usr/bin/env -S uv run --script -# /// script -# dependencies = [ -# "hcloud==2.24.0", -# ] -# /// - -import abc -import argparse -import logging -import os -import pathlib -import re -import shlex -import subprocess -import sys -import time - -import hcloud -from hcloud.images import Image -from hcloud.locations import Location -from hcloud.server_types import ServerType -from hcloud.ssh_keys import SSHKey - -logging.basicConfig( - level=logging.DEBUG if os.getenv("DEBUG") == "true" else logging.INFO, - format="[%(levelname)s] %(message)s", - stream=sys.stderr, -) - -log = logging.getLogger(__name__) - -ROOT_PATH = pathlib.Path(__file__).parent.parent - - -def main(): - args = parse_args() - builder = OpenBsdBuilder(args.arch, args.version) - builder.build() - - -class ProgArgs(argparse.Namespace): - def __init__(self): - self.arch = "amd64" - self.version = "7.9" - - -def parse_args() -> ProgArgs: - def openbsd_version(v: str): - v = v.strip() - if not re.compile(r"^\d\.\d$").match(v): - raise argparse.ArgumentTypeError("must be a version in the form `X.X`") - return v - - parser = argparse.ArgumentParser() - parser.add_argument( - "--arch", - choices=["amd64", "arm64"], - help="Target architecture", - ) - parser.add_argument( - "--version", - type=openbsd_version, - help="OpenBSD Version number", - ) - return parser.parse_args(namespace=ProgArgs()) - - -class OpenBsdBuilder: - def __init__(self, arch: str, version: str): - self._arch = arch - self._version = version - - def build(self): - server_name = "openbsd-builder" - key_name = "eugene@laptop" - img_path = self._build_img() - # try: - ip = self._start_server(server_name, key_name) - self._write_img_to_build_drive(img_path, ip) - self._reboot_server(server_name) - # self._verify_server(ip) - # self._create_snapshot(server_name, f"openbsd-{self._version}-{self._arch}") - # finally: - # self._delete_server(server_name) - - def _build_img(self) -> pathlib.Path: - # run("make", env={"ARCH": self._arch}, cwd=ROOT_PATH) - return ROOT_PATH / "build" / f"openbsd-{self._version}-{self._arch}.qcow2" - - def _start_server(self, name: str, key_name: str) -> str: - run(f"""hcloud server create \ - --name {name} \ - --type cx23 \ - --location nbg1 \ - --image debian-13 \ - --ssh-key {key_name}""") - run(f"hcloud server enable-rescue {name} --ssh-key {key_name}") - run(f"hcloud server poweron {name}") - time.sleep(30) - return run(f"hcloud server ip {name}", capture_output=True).stdout.strip() - - def _write_img_to_build_drive(self, img_path: pathlib.Path, ip: str): - run( - f"qemu-img convert -O raw '{img_path}' - | zstd -T0 | " - + f"ssh -o StrictHostKeyChecking=no root@{ip} " - + "'zstd -d | dd of=/dev/sda bs=4M status=progress conv=fsync'", - shell=True, - ) - - def _reboot_server(self, name: str): - run(f"hcloud server poweroff {name}") - run(f"hcloud server poweron {name}") - - def _verify_server(self, ip: str): - run(f"ssh -o StrictHostKeyChecking=no 'uname -a' 'admin@{ip}'") - - def _create_snapshot(self, name: str, snapshot_name: str): - run( - f"hcloud server create-image {name} " - + f"--type snapshot --description {snapshot_name}", - shell=True, - ) - - def _delete_server(self, name: str): - run(f"hcloud server delete {name}") - - -class VPSProvider(abc.ABC): - @abc.abstractmethod - def create_server(self, name: str, key_name: str) -> str: - pass - - @abc.abstractmethod - def reboot_server(self, name: str): - pass - - -class HetznerProvider(VPSProvider): - def __init__(self): - self._client = hcloud.Client(token=os.environ["HETZNER_API_TOKEN"]) - - def create_server(self, name: str, key_name: str) -> str: - resp = self._client.servers.create( - name=name, - server_type=ServerType(name="cx23"), - location=Location(name="nbg1"), - image=Image(name="debian-13"), - ssh_keys=[SSHKey(name=key_name)], - ) - resp.action.wait_until_finished() - resp.server.enable_rescue(ssh_keys=[key_name]).action.wait_until_finished() - resp.action.wait_until_finished() - resp.server.power_on().wait_until_finished() - server = self._client.servers.get_by_name(name) - assert server is not None, f"Expected {name} server to exist" - assert ( - server.public_net is not None - ), f"Expect {name} server to have to public address" - assert ( - server.public_net.ipv4 is not None - ), f"Expect {name} server to have to public IPv4 address" - return server.public_net.ipv4.ip - - def _write_img_to_build_drive(self, img_path: pathlib.Path, ip: str): - run( - f"qemu-img convert -O raw '{img_path}' - | zstd -T0 | " - + f"ssh -o StrictHostKeyChecking=no root@{ip} " - + "'zstd -d | dd of=/dev/sda bs=4M status=progress conv=fsync'", - shell=True, - ) - - def reboot_server(self, name: str): - server = self._client.servers.get_by_name(name) - assert server is not None, f"Expect server with {server} to exist" - self._client.servers.power_off(server).wait_until_finished() - self._client.servers.power_on(server).wait_until_finished() - - -def run( - cmd: str, - shell: bool = False, - env: dict[str, str] = {}, - cwd: pathlib.Path | str | None = None, - capture_output: bool = False, -) -> subprocess.CompletedProcess[str]: - full_env = None - if env is not None: - full_env = os.environ.copy() - full_env.update(env) - - return subprocess.run( - cmd if shell else shlex.split(cmd), - check=True, - env=full_env, - cwd=cwd, - shell=shell, - text=True, - capture_output=capture_output, - ) - - -if __name__ == "__main__": - main() |