Skip to content

eBPF-based security platform

infra: Add Packer builds for Shirudo AWS AMIs

Michi Mutsuzaki43f28c535839
diff --git a/.gitignore b/.gitignore
index 923b6fbb..2fe0cbda 100644
--- a/.gitignore
+++ b/.gitignore
@@ -21,6 +21,9 @@
# Local bpf-next kernel and userspace dependency artifacts
/artifacts
+/infra/aws/packer/packer-manifest.json
+/infra/aws/packer/.shirudo-image-assets.tar.gz
+/infra/aws/packer/.shirudo-image-assets.lock/
# Generated headers
/vmlinux.h
diff --git a/infra/aws/packer/README.md b/infra/aws/packer/README.md
new file mode 100644
index 00000000..fdf0eca0
--- /dev/null
+++ b/infra/aws/packer/README.md
@@ -0,0 +1,78 @@
+# Build the Shirudo AWS AMI
+
+Use the Packer wrapper in this directory to build an Ubuntu AMI with the
+bpf-next kernel. Target images are the default; choose `image_role=dev` for a
+development AMI without Shirudo provisioning.
+
+## Requirements
+
+- Packer
+- AWS credentials with permission to create the temporary builder role and
+ instance profile, launch and configure EC2 instances, and register and tag
+ AMIs
+- The AWS Session Manager plugin
+- GitHub CLI (`gh`), authenticated to GitHub with Actions read access to
+ `shirudo-dev/kernel` and `shirudo-dev/shirudo`
+
+The wrapper and Packer use the AWS credentials in your environment. Set
+`AWS_PROFILE` to choose a profile, and check the selected account with
+`aws sts get-caller-identity` before building.
+
+The wrapper uses the latest successful kernel package run from
+`shirudo-dev/kernel:main`. Target builds also use the latest successful package
+and image-assets runs from `shirudo-dev/shirudo:main`. Start those workflows
+before building if you need them to publish new artifacts.
+
+## Build
+
+From the Shirudo repository root:
+
+```bash
+cd infra/aws/packer
+./scripts/build-with-temporary-instance-profile.sh .
+```
+
+Build a dev AMI by setting `image_role`:
+
+```bash
+./scripts/build-with-temporary-instance-profile.sh \
+ -var 'image_role=dev' \
+ .
+```
+
+The wrapper creates and removes a temporary IAM role and instance profile for
+the builder. Optional environment variables:
+
+- `SSM_AUDIT_BUCKET`: existing S3 bucket for Session Manager session logs; the
+ wrapper grants the temporary builder role access to it.
+
+Use `additional_build_tags` for tags on the temporary builder instance and its
+root volume, including `owner` and `expiry` if needed:
+
+```bash
+SSM_AUDIT_BUCKET=bucket-name \
+./scripts/build-with-temporary-instance-profile.sh \
+ -var 'additional_build_tags={owner="your-user", expiry="YYYY-MM-DD", custom_tag="value"}' \
+ .
+```
+
+`additional_build_tags` applies to the temporary builder instance and its root
+volume. The output AMI, snapshot, and temporary IAM role and profile do not
+receive these tags.
+
+## Select artifacts
+
+The wrapper selects the latest successful artifacts by default. Pin specific
+workflow runs with these options:
+
+```bash
+./scripts/build-with-temporary-instance-profile.sh \
+ -var 'kernel_github_run_id=KERNEL_RUN_ID' \
+ -var 'shirudo_github_run_id=SHIRUDO_PACKAGES_RUN_ID' \
+ --shirudo-image-assets-run-id IMAGE_ASSETS_RUN_ID \
+ .
+```
+
+Other Packer options can be passed as `-var` arguments, including `region`,
+`instance_type` and `root_volume_size`. The wrapper initializes Packer and
+builds the AMI.
diff --git a/infra/aws/packer/bpf-next-ubuntu.pkr.hcl b/infra/aws/packer/bpf-next-ubuntu.pkr.hcl
new file mode 100644
index 00000000..455d6110
--- /dev/null
+++ b/infra/aws/packer/bpf-next-ubuntu.pkr.hcl
@@ -0,0 +1,274 @@
+packer {
+ required_plugins {
+ amazon = {
+ version = ">= 1.8.2"
+ source = "github.com/hashicorp/amazon"
+ }
+ }
+}
+
+variable "region" {
+ type = string
+ default = "us-west-2"
+}
+
+variable "instance_type" {
+ type = string
+ default = "t3.large"
+}
+
+variable "root_volume_size" {
+ type = number
+ default = 30
+}
+
+variable "ubuntu_version" {
+ type = string
+ default = "26.04"
+}
+
+variable "image_role" {
+ type = string
+ default = "target"
+ description = "Image role: target initializes Shirudo at boot; dev leaves it uninstalled."
+
+ validation {
+ condition = contains(["dev", "target"], var.image_role)
+ error_message = "The image_role must be dev or target."
+ }
+}
+
+variable "kernel_github_run_id" {
+ type = string
+ default = ""
+ description = "Optional exact GitHub Actions run id to use instead of the latest successful kernel main branch run."
+}
+
+variable "iam_instance_profile" {
+ type = string
+ description = "IAM instance profile for the temporary builder instance. The wrapper script creates and passes one."
+}
+
+variable "github_token" {
+ type = string
+ default = env("GH_TOKEN")
+ sensitive = true
+ description = "GitHub token supplied automatically through GH_TOKEN by the wrapper."
+}
+
+variable "shirudo_github_run_id" {
+ type = string
+ default = ""
+ description = "Optional exact GitHub Actions run id to use instead of the latest successful main branch run."
+}
+
+variable "additional_build_tags" {
+ type = map(string)
+ default = {}
+ description = "Additional tags for the temporary EC2 builder instance and its root volume."
+}
+
+locals {
+ ami_prefix = var.image_role == "dev" ? "shirudo-dev-ubuntu" : "shirudo-target-ubuntu"
+ ami_name = "${local.ami_prefix}-${var.ubuntu_version}-{{timestamp}}"
+ shirudo_cert_path = "${path.root}/../../certs/shirudo.der"
+ shirudo_image_assets_path = "${path.root}/.shirudo-image-assets.tar.gz"
+ target_provisioner_except = var.image_role == "dev" ? ["amazon-ebs.bpf_next_ubuntu"] : []
+ packer_run_tags = merge(var.additional_build_tags, {
+ Name = "packer-${local.ami_prefix}"
+ env = "build"
+ role = "packer"
+ })
+ packer_run_volume_tags = merge(var.additional_build_tags, {
+ Name = "packer-${local.ami_prefix}-root"
+ })
+}
+
+source "amazon-ebs" "bpf_next_ubuntu" {
+ region = var.region
+ instance_type = var.instance_type
+ ssh_username = "ubuntu"
+ ami_name = local.ami_name
+
+ ami_description = "Ubuntu ${var.ubuntu_version} ${var.image_role} AMI running a bpf-next kernel installed from deb packages"
+ ena_support = true
+ communicator = "ssh"
+ ssh_interface = "session_manager"
+ iam_instance_profile = var.iam_instance_profile
+ pause_before_ssm = "45s"
+ ssh_timeout = "15m"
+
+ metadata_options {
+ http_endpoint = "enabled"
+ http_tokens = "required"
+ http_put_response_hop_limit = 1
+ instance_metadata_tags = "enabled"
+ }
+
+ user_data = <<-EOF
+ #!/usr/bin/env bash
+ set -eux
+
+ ssm_tmp="$(mktemp -d)"
+ trap 'rm -rf "$ssm_tmp"' EXIT
+ if systemctl cat snap.amazon-ssm-agent.amazon-ssm-agent.service >/dev/null 2>&1; then
+ snap remove amazon-ssm-agent || true
+ fi
+ curl -fsSL https://s3.amazonaws.com/ec2-downloads-windows/SSMAgent/latest/debian_amd64/amazon-ssm-agent.deb \
+ -o "$ssm_tmp/amazon-ssm-agent.deb"
+ dpkg -i "$ssm_tmp/amazon-ssm-agent.deb"
+ systemctl enable --now amazon-ssm-agent.service
+ systemctl is-active --quiet amazon-ssm-agent.service
+ EOF
+
+ source_ami_filter {
+ filters = {
+ architecture = "x86_64"
+ name = "ubuntu/images/hvm-ssd-gp3/ubuntu-*-${var.ubuntu_version}-amd64-server-*"
+ root-device-type = "ebs"
+ virtualization-type = "hvm"
+ }
+ owners = ["099720109477"]
+ most_recent = true
+ }
+
+ launch_block_device_mappings {
+ device_name = "/dev/sda1"
+ volume_size = var.root_volume_size
+ volume_type = "gp3"
+ delete_on_termination = true
+ }
+
+ run_tags = local.packer_run_tags
+ run_volume_tags = local.packer_run_volume_tags
+
+ snapshot_tags = {
+ Name = "${local.ami_name}-root"
+ }
+
+ tags = {
+ Name = local.ami_name
+ BaseOS = "ubuntu-${var.ubuntu_version}"
+ KernelFlavor = "bpf-next"
+ KernelDebs = "kernel-packages-x86-64-full"
+ ShirudoRole = var.image_role
+ }
+}
+
+build {
+ name = "bpf-next-ubuntu"
+ sources = ["source.amazon-ebs.bpf_next_ubuntu"]
+
+ provisioner "shell-local" {
+ except = local.target_provisioner_except
+ inline = [
+ "set -eu",
+ "test -s '${local.shirudo_cert_path}'",
+ ]
+ }
+
+ provisioner "shell-local" {
+ except = local.target_provisioner_except
+ environment_vars = [
+ "SHIRUDO_IMAGE_ASSETS_TARBALL=${local.shirudo_image_assets_path}",
+ ]
+ inline = [
+ "set -eu",
+ "test -n \"$SHIRUDO_IMAGE_ASSETS_TARBALL\"",
+ "test -s \"$SHIRUDO_IMAGE_ASSETS_TARBALL\"",
+ "assets_dir=$(mktemp -d)",
+ "trap 'rm -rf \"$assets_dir\"' EXIT",
+ "tar -xzf \"$SHIRUDO_IMAGE_ASSETS_TARBALL\" -C \"$assets_dir\"",
+ "for file in shirudo-target initial.img initial.verity initial.roothash initial.p7s runtime.img runtime.verity runtime.roothash runtime.p7s runtime-service.conf initrd-bootstrap.conf; do test -s \"$assets_dir/$file\"; done",
+ "test -x \"$assets_dir/shirudo-target\"",
+ "runtime_root_hash=$(cat \"$assets_dir/runtime.roothash\")",
+ "printf '%s\\n' \"$runtime_root_hash\" | grep -Eq '^[0-9a-f]{64}$'",
+ "grep -Fqx 'runtime.image = /var/lib/shirudo/images/runtime' \"$assets_dir/initrd-bootstrap.conf\"",
+ "grep -Fqx \"runtime.root_hash = $runtime_root_hash\" \"$assets_dir/initrd-bootstrap.conf\"",
+ ]
+ }
+
+ provisioner "shell" {
+ environment_vars = [
+ "GITHUB_TOKEN=${var.github_token}",
+ "KERNEL_GITHUB_RUN_ID=${var.kernel_github_run_id}",
+ ]
+ script = "${path.root}/scripts/install-bpf-next-kernel.sh"
+ timeout = "45m"
+ }
+
+ provisioner "shell" {
+ script = "${path.root}/scripts/pre-reboot-diagnostics.sh"
+ }
+
+ provisioner "shell" {
+ inline = ["sudo reboot"]
+ expect_disconnect = true
+ skip_clean = true
+ }
+
+ provisioner "shell" {
+ pause_before = "180s"
+ inline = [
+ "set -eu",
+ "expected_kernel=$(cat /etc/bpf-next-kernel-release)",
+ "running_kernel=$(uname -r)",
+ "test \"$running_kernel\" = \"$expected_kernel\"",
+ "cat /etc/bpf-next-kernel-build",
+ ]
+ }
+
+ provisioner "shell" {
+ except = local.target_provisioner_except
+ environment_vars = [
+ "GITHUB_TOKEN=${var.github_token}",
+ "SHIRUDO_GITHUB_RUN_ID=${var.shirudo_github_run_id}",
+ ]
+ script = "${path.root}/scripts/install-shirudo-target-from-github-artifact.sh"
+ timeout = "20m"
+ }
+
+ provisioner "file" {
+ except = local.target_provisioner_except
+ source = local.shirudo_cert_path
+ destination = "/tmp/shirudo-cert.der"
+ }
+
+ provisioner "shell" {
+ except = local.target_provisioner_except
+ inline = [
+ "set -eu",
+ "sudo install -d -o root -g root -m 0755 /var/lib/shirudo/keys",
+ "sudo install -o root -g root -m 0644 /tmp/shirudo-cert.der /var/lib/shirudo/keys/cert.der",
+ "rm -f /tmp/shirudo-cert.der",
+ ]
+ }
+
+ provisioner "file" {
+ except = local.target_provisioner_except
+ source = local.shirudo_image_assets_path
+ destination = "/tmp/shirudo-image-assets.tar.gz"
+ }
+
+ provisioner "shell" {
+ except = local.target_provisioner_except
+ script = "${path.root}/scripts/configure-shirudo-initrd.sh"
+ timeout = "20m"
+ }
+
+ post-processor "manifest" {
+ output = "${path.root}/packer-manifest.json"
+ strip_path = true
+ }
+
+ post-processor "shell-local" {
+ environment_vars = [
+ "AWS_REGION=${var.region}",
+ "PACKER_MANIFEST_PATH=${path.root}/packer-manifest.json",
+ "UBUNTU_VERSION=${var.ubuntu_version}",
+ "KERNEL_ARTIFACT_NAME=kernel-packages-x86-64-full",
+ "SHIRUDO_IMAGE_ROLE=${var.image_role}",
+ ]
+ script = "${path.root}/scripts/register-nitrotpm-ami.sh"
+ }
+}
diff --git a/infra/aws/packer/scripts/build-with-temporary-instance-profile.sh b/infra/aws/packer/scripts/build-with-temporary-instance-profile.sh
new file mode 100755
index 00000000..b8032334
--- /dev/null
+++ b/infra/aws/packer/scripts/build-with-temporary-instance-profile.sh
@@ -0,0 +1,332 @@
+#!/usr/bin/env bash
+# SPDX-License-Identifier: BSD-2-Clause
+# Copyright (c) 2026 Authors of shirudo
+
+set -euo pipefail
+
+script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
+packer_dir=$(cd "$script_dir/.." && pwd)
+profile_name="packer-shirudo-$(date -u +%Y%m%d%H%M%S)-$$"
+role_name="$profile_name"
+policy_name="$profile_name"
+ssm_audit_bucket=${SSM_AUDIT_BUCKET:-}
+
+image_assets_run_id=${SHIRUDO_IMAGE_ASSETS_RUN_ID:-}
+packer_args=()
+
+while [ "$#" -gt 0 ]; do
+ case "$1" in
+ --shirudo-image-assets-run-id)
+ if [ "$#" -lt 2 ]; then
+ echo "Missing run id after --shirudo-image-assets-run-id" >&2
+ exit 2
+ fi
+ image_assets_run_id=$2
+ shift 2
+ ;;
+ --shirudo-image-assets-run-id=*)
+ image_assets_run_id=${1#*=}
+ shift
+ ;;
+ *)
+ packer_args+=("$1")
+ shift
+ ;;
+ esac
+done
+
+if [ "${#packer_args[@]}" -eq 0 ]; then
+ packer_args=(.)
+fi
+
+needs_image_assets=true
+if [ "${PKR_VAR_image_role:-target}" = dev ]; then
+ needs_image_assets=false
+fi
+for ((i = 0; i < ${#packer_args[@]}; i++)); do
+ arg="${packer_args[i]}"
+ case "$arg" in
+ -var)
+ if [ "$((i + 1))" -lt "${#packer_args[@]}" ]; then
+ next_arg="${packer_args[i + 1]}"
+ case "$next_arg" in
+ image_role=dev)
+ needs_image_assets=false
+ ;;
+ esac
+ fi
+ ;;
+ image_role=dev|-var=image_role=dev)
+ needs_image_assets=false
+ ;;
+ esac
+done
+
+if ! GH_TOKEN=$(gh auth token --hostname github.com); then
+ echo "GitHub token unavailable: run 'gh auth login --hostname github.com'." >&2
+ exit 1
+fi
+export GH_TOKEN
+
+latest_successful_image_assets_run()
+{
+ local page=1 selection count run_id run_number run_attempt created_at head_sha
+
+ while true; do
+ selection="$(gh api --method GET \
+ "repos/shirudo-dev/shirudo/actions/workflows/packages.yml/runs" \
+ -f per_page=100 \
+ -f "page=${page}" \
+ --jq '[.workflow_runs[] | select(.head_branch == "main" and .event == "push" and
+ .status == "completed" and .conclusion == "success")][0] |
+ [.id // 0, .run_number // 0, .run_attempt // 0,
+ .created_at // "-", .head_sha // "-"] | @tsv')" || return 1
+ IFS=$'\t' read -r run_id run_number run_attempt created_at head_sha <<< "$selection"
+ if [ "$run_id" != 0 ]; then
+ echo "Selected image-assets run ${run_id}: created ${created_at}, commit ${head_sha}" >&2
+ printf '%s\t%s\t%s\n' "$run_id" "$run_number" "$run_attempt"
+ return 0
+ fi
+ count="$(gh api --method GET \
+ "repos/shirudo-dev/shirudo/actions/workflows/packages.yml/runs" \
+ -f per_page=100 -f "page=${page}" --jq '.workflow_runs | length')" || return 1
+ if [ "$count" -lt 100 ]; then
+ echo "No successful packages workflow run with image assets found on shirudo-dev/shirudo:main" >&2
+ return 1
+ fi
+ page=$((page + 1))
+ done
+}
+
+image_assets_run_by_id()
+{
+ local run_id=$1 selection selected_id run_number run_attempt status conclusion created_at head_sha
+
+ case "$run_id" in
+ ''|*[!0-9]*)
+ echo "Invalid image-assets run id: ${run_id}" >&2
+ return 1
+ ;;
+ esac
+ selection="$(gh api --method GET \
+ "repos/shirudo-dev/shirudo/actions/runs/${run_id}" \
+ --jq '[.id // 0, .run_number // 0, .run_attempt // 0, .status // "", .conclusion // "", .created_at // "-", .head_sha // "-"] | @tsv')" || return 1
+ IFS=$'\t' read -r selected_id run_number run_attempt status conclusion created_at head_sha <<< "$selection"
+ if [ "$selected_id" != "$run_id" ] || [ ! "$run_number" -gt 0 ] ||
+ [ ! "$run_attempt" -gt 0 ] || [ "$status" != completed ] ||
+ [ "$conclusion" != success ]; then
+ echo "Image-assets run ${run_id} is not a successful completed workflow run" >&2
+ return 1
+ fi
+ echo "Selected image-assets run ${run_id}: created ${created_at}, commit ${head_sha}" >&2
+ printf '%s\t%s\t%s\n' "$selected_id" "$run_number" "$run_attempt"
+}
+
+image_assets_dir=
+image_assets_lock="$packer_dir/.shirudo-image-assets.lock"
+image_assets_path="$packer_dir/.shirudo-image-assets.tar.gz"
+image_assets_lock_acquired=false
+cleanup_image_assets()
+{
+ if [ -n "$image_assets_dir" ]; then
+ rm -rf "$image_assets_dir"
+ fi
+ if [ "$image_assets_lock_acquired" = true ]; then
+ rm -f "$image_assets_path"
+ rmdir "$image_assets_lock" 2>/dev/null || true
+ fi
+}
+trap cleanup_image_assets EXIT
+
+if [ "$needs_image_assets" = true ]; then
+ if ! mkdir "$image_assets_lock"; then
+ echo "Image-assets staging lock exists: ${image_assets_lock}" >&2
+ exit 1
+ fi
+ image_assets_lock_acquired=true
+ rm -f "$image_assets_path"
+ image_assets_dir="$(mktemp -d "${TMPDIR:-/tmp}/shirudo-image-assets.XXXXXX")"
+ if [ -n "$image_assets_run_id" ]; then
+ run_fields="$(image_assets_run_by_id "$image_assets_run_id")"
+ else
+ run_fields="$(latest_successful_image_assets_run)"
+ fi
+ IFS=$'\t' read -r run_id run_number run_attempt <<< "$run_fields"
+ if [ ! "$run_id" -gt 0 ] || [ ! "$run_number" -gt 0 ] || [ ! "$run_attempt" -gt 0 ]; then
+ echo "Invalid image-assets workflow run metadata" >&2
+ exit 1
+ fi
+ artifact_name="shirudo-image-assets-${run_number}-${run_attempt}"
+ echo "Downloading ${artifact_name} from shirudo-dev/shirudo run ${run_id}"
+ gh run download "$run_id" \
+ --repo shirudo-dev/shirudo \
+ --name "$artifact_name" \
+ --dir "$image_assets_dir"
+ if [ ! -s "$image_assets_dir/shirudo-image-assets.tar.gz" ] ||
+ [ ! -s "$image_assets_dir/shirudo-image-assets.tar.gz.sha256" ]; then
+ echo "Image-assets artifact is missing its tarball or checksum" >&2
+ exit 1
+ fi
+ (cd "$image_assets_dir" && sha256sum -c shirudo-image-assets.tar.gz.sha256)
+ cp "$image_assets_dir/shirudo-image-assets.tar.gz" "$image_assets_path"
+fi
+
+trust_doc=$(mktemp)
+policy_doc=$(mktemp)
+
+cleanup()
+{
+ local i
+
+ set +e
+ aws iam delete-role-policy \
+ --role-name "$role_name" \
+ --policy-name "$policy_name" >/dev/null 2>&1
+ aws iam remove-role-from-instance-profile \
+ --instance-profile-name "$profile_name" \
+ --role-name "$role_name" >/dev/null 2>&1
+ for i in $(seq 1 12); do
+ aws iam delete-instance-profile \
+ --instance-profile-name "$profile_name" >/dev/null 2>&1 && break
+ sleep 5
+ done
+ for i in $(seq 1 12); do
+ aws iam delete-role --role-name "$role_name" >/dev/null 2>&1 && break
+ sleep 5
+ done
+ rm -f "$trust_doc" "$policy_doc"
+ cleanup_image_assets
+}
+
+trap cleanup EXIT
+
+cat >"$trust_doc" <<'JSON'
+{
+ "Version": "2012-10-17",
+ "Statement": [
+ {
+ "Effect": "Allow",
+ "Principal": {
+ "Service": "ec2.amazonaws.com"
+ },
+ "Action": "sts:AssumeRole"
+ }
+ ]
+}
+JSON
+
+bucket_policy_statements=
+if [ -n "$ssm_audit_bucket" ]; then
+ bucket_policy_statements=$(cat <<JSON
+,
+ {
+ "Effect": "Allow",
+ "Action": [
+ "s3:GetBucketLocation",
+ "s3:GetEncryptionConfiguration"
+ ],
+ "Resource": "arn:aws:s3:::${ssm_audit_bucket}"
+ },
+ {
+ "Effect": "Allow",
+ "Action": [
+ "s3:PutObject",
+ "s3:PutObjectAcl",
+ "s3:PutObjectTagging"
+ ],
+ "Resource": "arn:aws:s3:::${ssm_audit_bucket}/*"
+ }
+JSON
+)
+fi
+
+cat >"$policy_doc" <<JSON
+{
+ "Version": "2012-10-17",
+ "Statement": [
+ {
+ "Effect": "Allow",
+ "Action": [
+ "ssm:DescribeAssociation",
+ "ssm:DescribeDocument",
+ "ssm:GetDeployablePatchSnapshotForInstance",
+ "ssm:GetDocument",
+ "ssm:GetManifest",
+ "ssm:GetParameter",
+ "ssm:GetParameters",
+ "ssm:ListAssociations",
+ "ssm:ListInstanceAssociations",
+ "ssm:PutComplianceItems",
+ "ssm:PutConfigurePackageResult",
+ "ssm:PutInventory",
+ "ssm:UpdateAssociationStatus",
+ "ssm:UpdateInstanceAssociationStatus",
+ "ssm:UpdateInstanceInformation"
+ ],
+ "Resource": "*"
+ },
+ {
+ "Effect": "Allow",
+ "Action": [
+ "ssmmessages:CreateControlChannel",
+ "ssmmessages:CreateDataChannel",
+ "ssmmessages:OpenControlChannel",
+ "ssmmessages:OpenDataChannel"
+ ],
+ "Resource": "*"
+ },
+ {
+ "Effect": "Allow",
+ "Action": [
+ "ec2messages:AcknowledgeMessage",
+ "ec2messages:DeleteMessage",
+ "ec2messages:FailMessage",
+ "ec2messages:GetEndpoint",
+ "ec2messages:GetMessages",
+ "ec2messages:SendReply"
+ ],
+ "Resource": "*"
+ }${bucket_policy_statements}
+ ]
+}
+JSON
+
+iam_tags=("Key=Name,Value=$profile_name")
+
+echo "Creating temporary instance profile: $profile_name"
+aws iam create-instance-profile \
+ --instance-profile-name "$profile_name" \
+ --tags "${iam_tags[@]}" >/dev/null
+aws iam create-role \
+ --role-name "$role_name" \
+ --description "Temporary role for Packer" \
+ --assume-role-policy-document "file://$trust_doc" \
+ --tags "${iam_tags[@]}" >/dev/null
+aws iam wait instance-profile-exists --instance-profile-name "$profile_name"
+aws iam wait role-exists --role-name "$role_name"
+aws iam put-role-policy \
+ --role-name "$role_name" \
+ --policy-name "$policy_name" \
+ --policy-document "file://$policy_doc"
+aws iam add-role-to-instance-profile \
+ --instance-profile-name "$profile_name" \
+ --role-name "$role_name"
+
+for _ in $(seq 1 60); do
+ if [ "$(aws iam get-instance-profile \
+ --instance-profile-name "$profile_name" \
+ --query "InstanceProfile.Roles[?RoleName=='$role_name'].RoleName | [0]" \
+ --output text)" = "$role_name" ]; then
+ break
+ fi
+ sleep 5
+done
+
+echo "Waiting 120s for IAM propagation"
+sleep 120
+
+cd "$packer_dir"
+packer init .
+packer build \
+ -var "iam_instance_profile=$profile_name" \
+ "${packer_args[@]}"
diff --git a/infra/aws/packer/scripts/configure-shirudo-initrd.sh b/infra/aws/packer/scripts/configure-shirudo-initrd.sh
new file mode 100755
index 00000000..f0d629f4
--- /dev/null
+++ b/infra/aws/packer/scripts/configure-shirudo-initrd.sh
@@ -0,0 +1,150 @@
+#!/usr/bin/env bash
+# SPDX-License-Identifier: BSD-2-Clause
+# Copyright (c) 2026 Authors of shirudo
+
+set -euo pipefail
+
+kernel_release="$(cat /etc/bpf-next-kernel-release)"
+if [[ "$(uname -r)" != "$kernel_release" ]]; then
+ echo "Running kernel $(uname -r) does not match ${kernel_release}" >&2
+ exit 1
+fi
+
+if ! grep -q -w 'bpf.keyring_unsealed=1' /proc/cmdline; then
+ echo "Running kernel command line lacks bpf.keyring_unsealed=1" >&2
+ exit 1
+fi
+if ! grep -q -w 'dm_verity.keyring_unsealed=1' /proc/cmdline; then
+ echo "Running kernel command line lacks dm_verity.keyring_unsealed=1" >&2
+ exit 1
+fi
+
+export DEBIAN_FRONTEND=noninteractive
+sudo apt-get update
+sudo apt-get install -y dracut systemd-boot-efi systemd-ukify
+
+command -v dracut >/dev/null
+command -v shirudo-gen-initrd >/dev/null
+command -v ukify >/dev/null
+
+assets_dir="$(mktemp -d)"
+trap 'rm -rf "$assets_dir"' EXIT
+sudo tar -xzf /tmp/shirudo-image-assets.tar.gz -C "$assets_dir"
+for file in \
+ shirudo-target \
+ initial.img initial.verity initial.roothash initial.p7s \
+ runtime.img runtime.verity runtime.roothash runtime.p7s \
+ runtime-service.conf initrd-bootstrap.conf; do
+ if [[ ! -s "$assets_dir/$file" ]]; then
+ echo "Missing Shirudo image asset: $file" >&2
+ exit 1
+ fi
+done
+if [[ ! -x "$assets_dir/shirudo-target" ]]; then
+ echo "Branch-built shirudo-target is not executable" >&2
+ exit 1
+fi
+
+runtime_root_hash="$(cat "$assets_dir/runtime.roothash")"
+if ! grep -Fxq "runtime.root_hash = $runtime_root_hash" \
+ "$assets_dir/initrd-bootstrap.conf"; then
+ echo "Initrd bootstrap root hash does not match runtime.roothash" >&2
+ exit 1
+fi
+if ! grep -Fxq 'runtime.image = /var/lib/shirudo/images/runtime' \
+ "$assets_dir/initrd-bootstrap.conf"; then
+ echo "Initrd bootstrap must name /var/lib/shirudo/images/runtime" >&2
+ exit 1
+fi
+
+# shirudo rejects bootstrap settings writable by group or other users. The
+# asset tarball may have been created under a permissive umask.
+sudo chown root:root "$assets_dir/initrd-bootstrap.conf"
+sudo chmod 0644 "$assets_dir/initrd-bootstrap.conf"
+
+sudo install -d -o root -g root -m 0755 /var/lib/shirudo/images
+for prefix in initial runtime; do
+ for suffix in img verity roothash p7s; do
+ sudo install -o root -g root -m 0644 \
+ "$assets_dir/$prefix.$suffix" \
+ "/var/lib/shirudo/images/$prefix.$suffix"
+ done
+done
+sudo install -D -o root -g root -m 0644 \
+ "$assets_dir/runtime-service.conf" \
+ /etc/systemd/system/shirudo.service.d/verity.conf
+
+tcti_device="$(ldconfig -p | awk '$1 == "libtss2-tcti-device.so.0" { print $NF; exit }')"
+if [[ -z "$tcti_device" || ! -r "$tcti_device" ]]; then
+ echo "libtss2-tcti-device.so.0 is required to initialize the TPM in the initrd" >&2
+ exit 1
+fi
+
+sudo shirudo-gen-initrd --kver "$kernel_release" \
+ --binary "$assets_dir/shirudo-target" \
+ --binary-path /usr/bin/shirudo \
+ --bootstrap-conf "$assets_dir/initrd-bootstrap.conf" \
+ -- --install "$tcti_device"
+initrd="/boot/initrd.img-${kernel_release}"
+sudo shirudo-gen-initrd --check "$initrd"
+initrd_listing="$(sudo lsinitrd "$initrd")"
+if ! grep -q -- 'libtss2-tcti-device\.so\.0' <<<"$initrd_listing"; then
+ echo "libtss2-tcti-device.so.0 is missing from $initrd" >&2
+ exit 1
+fi
+
+esp="$(findmnt -n -o TARGET /boot/efi || true)"
+if [[ "$esp" != "/boot/efi" ]]; then
+ echo "Expected the EFI system partition mounted at /boot/efi" >&2
+ exit 1
+fi
+
+esp_uuid="$(sudo grub-probe --target=fs_uuid /boot/efi)"
+uki_dir="${esp}/EFI/Linux"
+uki_path="${uki_dir}/shirudo-${kernel_release}.efi"
+sudo install -d -o root -g root -m 0755 "$uki_dir"
+
+kernel_cmdline="$(sed -E 's/(^|[[:space:]])BOOT_IMAGE=[^[:space:]]+//g; s/^[[:space:]]+//; s/[[:space:]]+$//' /proc/cmdline)"
+for parameter in bpf.keyring_unsealed=1 dm_verity.keyring_unsealed=1; do
+ case " $kernel_cmdline " in
+ *" $parameter "*) ;;
+ *) kernel_cmdline="$kernel_cmdline $parameter" ;;
+ esac
+done
+
+sudo ukify build \
+ --linux="/boot/vmlinuz-${kernel_release}" \
+ --initrd="$initrd" \
+ --cmdline="$kernel_cmdline" \
+ --output="$uki_path"
+sudo ukify inspect "$uki_path" >/dev/null
+
+sudo tee /etc/grub.d/41_shirudo_uki >/dev/null <<EOF
+#!/bin/sh
+cat <<'GRUB_EOF'
+menuentry 'Shirudo UKI (${kernel_release})' {
+ insmod part_gpt
+ insmod fat
+ search --no-floppy --fs-uuid --set=root ${esp_uuid}
+ chainloader /EFI/Linux/shirudo-${kernel_release}.efi
+}
+GRUB_EOF
+EOF
+sudo chmod 0755 /etc/grub.d/41_shirudo_uki
+sudo sed -i 's/^GRUB_DEFAULT=.*/GRUB_DEFAULT=saved/' \
+ /etc/default/grub.d/99-bpf-next.cfg
+if grep -q '^GRUB_SAVEDEFAULT=' /etc/default/grub.d/99-bpf-next.cfg; then
+ sudo sed -i 's/^GRUB_SAVEDEFAULT=.*/GRUB_SAVEDEFAULT=true/' \
+ /etc/default/grub.d/99-bpf-next.cfg
+else
+ echo 'GRUB_SAVEDEFAULT=true' | \
+ sudo tee -a /etc/default/grub.d/99-bpf-next.cfg >/dev/null
+fi
+sudo update-grub
+sudo grub-set-default "Shirudo UKI (${kernel_release})"
+sudo update-grub
+
+sudo ln -sf /run/shirudo/runtime/usr/bin/shirudo /usr/local/bin/shirudo
+
+printf 'Shirudo UKI: %s\n' "$uki_path"
+printf 'GRUB default: %s\n' "Shirudo UKI (${kernel_release})"
diff --git a/infra/aws/packer/scripts/install-bpf-next-kernel.sh b/infra/aws/packer/scripts/install-bpf-next-kernel.sh
new file mode 100755
index 00000000..cac34386
--- /dev/null
+++ b/infra/aws/packer/scripts/install-bpf-next-kernel.sh
@@ -0,0 +1,456 @@
+#!/usr/bin/env bash
+# SPDX-License-Identifier: BSD-2-Clause
+# Copyright (c) 2026 Authors of shirudo
+
+set -euo pipefail
+
+export DEBIAN_FRONTEND=noninteractive
+
+KERNEL_PACKAGE_PATH="${KERNEL_PACKAGE_PATH:-}"
+KERNEL_PACKAGE_SHA256="${KERNEL_PACKAGE_SHA256:-}"
+KERNEL_GITHUB_REPO="shirudo-dev/kernel"
+KERNEL_GITHUB_WORKFLOW="build-kernel-packages.yml"
+KERNEL_GITHUB_ARTIFACT="kernel-packages-x86-64-full"
+KERNEL_GITHUB_RUN_ID="${KERNEL_GITHUB_RUN_ID:-}"
+OTELCOL_INSTALL_PATH="/usr/local/bin/otelcol-contrib"
+SSM_AGENT_DEB_URL="${SSM_AGENT_DEB_URL:-https://s3.amazonaws.com/ec2-downloads-windows/SSMAgent/latest/debian_amd64/amazon-ssm-agent.deb}"
+WORK_DIR="/usr/src/bpf-next"
+PACKAGE_DIR="${WORK_DIR}/packages"
+APT_GET=(
+ sudo
+ env
+ DEBIAN_FRONTEND=noninteractive
+ NEEDRESTART_MODE=l
+ apt-get
+ -o
+ DPkg::Lock::Timeout=600
+ -o
+ Dpkg::Options::=--force-confdef
+ -o
+ Dpkg::Options::=--force-confold
+)
+
+cleanup_apt_policy() {
+ sudo rm -f /usr/sbin/policy-rc.d
+}
+
+latest_successful_kernel_run() {
+ local page=1 selection count run_id created_at head_sha
+
+ # Filter locally: GitHub's server-side filters can omit recent runs.
+ # Include workflow_dispatch runs, not just pushes.
+ while true; do
+ selection="$(gh api --method GET \
+ "repos/${KERNEL_GITHUB_REPO}/actions/workflows/${KERNEL_GITHUB_WORKFLOW}/runs" \
+ -f per_page=100 \
+ -f "page=${page}" \
+ --jq '.workflow_runs as $runs |
+ ([$runs[] | select(.head_branch == "main" and
+ .status == "completed" and .conclusion == "success")][0]) as $run |
+ [($runs | length), ($run.id // 0), ($run.created_at // "-"),
+ ($run.head_sha // "-")] | @tsv')" || return 1
+ IFS=$'\t' read -r count run_id created_at head_sha <<< "$selection"
+ if [[ "$run_id" != 0 ]]; then
+ echo "Selected kernel Actions run ${run_id}: created ${created_at}, commit ${head_sha}" >&2
+ printf '%s\n' "$run_id"
+ return 0
+ fi
+ if [[ "$count" -lt 100 ]]; then
+ echo "No successful ${KERNEL_GITHUB_WORKFLOW} run found on ${KERNEL_GITHUB_REPO}:main" >&2
+ return 1
+ fi
+ page=$((page + 1))
+ done
+}
+
+download_kernel_artifact() {
+ local artifact_dir="$1"
+ local run_id="$KERNEL_GITHUB_RUN_ID"
+
+ if [[ -z "$run_id" ]]; then
+ echo "Selecting the latest successful ${KERNEL_GITHUB_WORKFLOW} run on ${KERNEL_GITHUB_REPO}:main"
+ run_id="$(latest_successful_kernel_run)" || return 1
+ fi
+
+ echo "Downloading ${KERNEL_GITHUB_ARTIFACT} from ${KERNEL_GITHUB_REPO} Actions run ${run_id}"
+ gh run download "$run_id" \
+ --repo "$KERNEL_GITHUB_REPO" \
+ --name "$KERNEL_GITHUB_ARTIFACT" \
+ --dir "$artifact_dir"
+}
+
+aws_cli_arch() {
+ case "$(uname -m)" in
+ x86_64)
+ echo "x86_64"
+ ;;
+ aarch64 | arm64)
+ echo "aarch64"
+ ;;
+ *)
+ echo "Unsupported machine architecture for awscli: $(uname -m)" >&2
+ exit 1
+ ;;
+ esac
+}
+
+ensure_aws_cli() (
+ local arch tmp_dir
+
+ if command -v aws >/dev/null 2>&1; then
+ return
+ fi
+
+ arch="$(aws_cli_arch)"
+ tmp_dir="$(mktemp -d)"
+ trap 'rm -rf "$tmp_dir"' EXIT
+
+ echo "Installing AWS CLI v2 for ${arch}"
+ curl -fsSL "https://awscli.amazonaws.com/awscli-exe-linux-${arch}.zip" -o "${tmp_dir}/awscliv2.zip"
+ unzip -q "${tmp_dir}/awscliv2.zip" -d "$tmp_dir"
+ sudo "${tmp_dir}/aws/install" --bin-dir /usr/local/bin --install-dir /usr/local/aws-cli --update
+ aws --version
+)
+
+otel_collector_arch() {
+ case "$(uname -m)" in
+ x86_64)
+ echo "amd64"
+ ;;
+ aarch64 | arm64)
+ echo "arm64"
+ ;;
+ *)
+ echo "Unsupported machine architecture for otelcol-contrib: $(uname -m)" >&2
+ exit 1
+ ;;
+ esac
+}
+
+latest_otel_collector_package_url() {
+ local arch="$1"
+
+ curl -fsSL "https://api.github.com/repos/open-telemetry/opentelemetry-collector-releases/releases/latest" |
+ python3 -c '
+import json
+import sys
+
+suffix = f"_linux_{sys.argv[1]}.deb"
+for asset in json.load(sys.stdin)["assets"]:
+ name = asset["name"]
+ if name.startswith("otelcol-contrib_") and name.endswith(suffix):
+ print(asset["browser_download_url"])
+ break
+' "$arch"
+}
+
+# Isolate temporary-file cleanup from the kernel installation's EXIT trap.
+install_otel_collector() (
+ local arch package_url tmp_dir package_path binary_path
+
+ arch="$(otel_collector_arch)"
+ package_url="$(latest_otel_collector_package_url "$arch")"
+ if [[ -z "$package_url" ]]; then
+ echo "No otelcol-contrib deb/${arch} package found in latest release" >&2
+ exit 1
+ fi
+
+ tmp_dir="$(mktemp -d)"
+ trap 'rm -rf "$tmp_dir"' EXIT
+
+ package_path="${tmp_dir}/otelcol-contrib.deb"
+ echo "Installing otelcol-contrib from ${package_url}"
+ curl -fsSL "$package_url" -o "$package_path"
+ "${APT_GET[@]}" install -y --no-install-recommends "$package_path"
+
+ binary_path="$(command -v otelcol-contrib || true)"
+ if [[ -z "$binary_path" ]]; then
+ echo "otelcol-contrib package did not install an otelcol-contrib binary" >&2
+ exit 1
+ fi
+ if [[ "$binary_path" != "$OTELCOL_INSTALL_PATH" ]]; then
+ sudo ln -sf "$binary_path" "$OTELCOL_INSTALL_PATH"
+ fi
+
+ sudo systemctl disable --now otelcol-contrib.service >/dev/null 2>&1 || true
+)
+
+kernel_config_has() {
+ local kernel_release="$1"
+ local symbol="$2"
+
+ grep -Eq "^${symbol}=[ym]$" "/boot/config-${kernel_release}"
+}
+
+require_kernel_config() {
+ local kernel_release="$1"
+ local symbol="$2"
+ local description="$3"
+
+ if kernel_config_has "$kernel_release" "$symbol"; then
+ return
+ fi
+
+ echo "Expected kernel lacks ${description} (${symbol})." >&2
+ echo "Rebuild the kernel artifact with ${symbol} enabled." >&2
+ grep -E "^${symbol}=|^# ${symbol} is not set" "/boot/config-${kernel_release}" >&2 || true
+ exit 1
+}
+
+require_kernel_config_value() {
+ local kernel_release="$1"
+ local symbol="$2"
+ local expected="$3"
+ local description="$4"
+
+ if grep -Fqx "${symbol}=${expected}" "/boot/config-${kernel_release}"; then
+ return
+ fi
+
+ echo "Expected kernel ${description} (${symbol}=${expected})." >&2
+ grep -E "^${symbol}=|^# ${symbol} is not set" "/boot/config-${kernel_release}" >&2 || true
+ exit 1
+}
+
+install_ssm_deb_agent() {
+ local ssm_tmp
+
+ if systemctl cat snap.amazon-ssm-agent.amazon-ssm-agent.service >/dev/null 2>&1; then
+ sudo snap remove amazon-ssm-agent || true
+ fi
+
+ ssm_tmp="$(mktemp -d)"
+ curl -fsSL "$SSM_AGENT_DEB_URL" -o "${ssm_tmp}/amazon-ssm-agent.deb"
+ sudo dpkg -i "${ssm_tmp}/amazon-ssm-agent.deb"
+ sudo systemctl enable amazon-ssm-agent.service
+ rm -rf "$ssm_tmp"
+}
+
+ensure_ssm_agent_for_next_boot() {
+ install_ssm_deb_agent
+}
+
+write_grub_defaults() {
+ sudo tee /etc/default/grub.d/99-bpf-next.cfg >/dev/null <<'EOF'
+GRUB_DEFAULT=0
+unset GRUB_FORCE_PARTUUID
+GRUB_CMDLINE_LINUX_DEFAULT="${GRUB_CMDLINE_LINUX_DEFAULT} lsm=landlock,lockdown,yama,integrity,apparmor,bpf bpf.keyring_unsealed=1 dm_verity.keyring_unsealed=1"
+EOF
+}
+
+if [[ -n "$KERNEL_PACKAGE_PATH" && ! -f "$KERNEL_PACKAGE_PATH" && ! -d "$KERNEL_PACKAGE_PATH" ]]; then
+ echo "Kernel package artifact not found: ${KERNEL_PACKAGE_PATH}" >&2
+ exit 1
+fi
+
+if command -v cloud-init >/dev/null 2>&1; then
+ cloud_init_status=0
+ sudo cloud-init status --wait || cloud_init_status=$?
+ case "$cloud_init_status" in
+ 0)
+ ;;
+ 2)
+ echo "cloud-init completed with recoverable errors; continuing with details:" >&2
+ sudo cloud-init status --long || true
+ ;;
+ *)
+ echo "cloud-init failed with status ${cloud_init_status}" >&2
+ exit "$cloud_init_status"
+ ;;
+ esac
+fi
+
+sudo tee /usr/sbin/policy-rc.d >/dev/null <<'EOF'
+#!/bin/sh
+exit 101
+EOF
+sudo chmod +x /usr/sbin/policy-rc.d
+trap cleanup_apt_policy EXIT
+
+"${APT_GET[@]}" update
+"${APT_GET[@]}" install -y --no-install-recommends \
+ ca-certificates \
+ coreutils \
+ curl \
+ gh \
+ initramfs-tools \
+ kmod \
+ python3 \
+ tar \
+ tpm2-tools \
+ unzip
+
+ensure_aws_cli
+install_otel_collector
+
+sudo install -d -o "$USER" -g "$USER" "$WORK_DIR" "$PACKAGE_DIR"
+
+if [[ -z "$KERNEL_PACKAGE_PATH" ]]; then
+ KERNEL_PACKAGE_PATH="$(mktemp -d "${WORK_DIR}/artifact.XXXXXX")"
+ download_kernel_artifact "$KERNEL_PACKAGE_PATH"
+fi
+
+if [[ -d "$KERNEL_PACKAGE_PATH" ]]; then
+ package_file="$(find "$KERNEL_PACKAGE_PATH" -type f \
+ \( -name 'bpf-next-kernel-debs-amd64.zip' -o -name 'bpf-next-kernel-debs.tar.gz' \) |
+ sort | head -n 1)"
+
+ if [[ -n "$package_file" ]]; then
+ if [[ -n "$KERNEL_PACKAGE_SHA256" ]]; then
+ printf '%s %s\n' "$KERNEL_PACKAGE_SHA256" "$package_file" | sha256sum -c -
+ elif [[ -f "${package_file}.sha256sum" ]]; then
+ (cd "$(dirname "$package_file")" && sha256sum -c "$(basename "$package_file").sha256sum")
+ fi
+
+ case "$package_file" in
+ *.zip)
+ unzip -q "$package_file" -d "$PACKAGE_DIR"
+ ;;
+ *)
+ tar -xzf "$package_file" -C "$PACKAGE_DIR"
+ ;;
+ esac
+ else
+ image_deb="$(find "$KERNEL_PACKAGE_PATH" -type f -name 'linux-image-[0-9]*.deb' ! -name '*-dbg*' | sort | head -n 1)"
+ if [[ -z "$image_deb" ]]; then
+ echo "No kernel package file found in ${KERNEL_PACKAGE_PATH}" >&2
+ exit 1
+ fi
+
+ artifact_dir="$(dirname "$image_deb")"
+ if [[ -f "${artifact_dir}/SHA256SUMS" ]]; then
+ (cd "$artifact_dir" && sha256sum -c SHA256SUMS)
+ fi
+ find "$artifact_dir" -maxdepth 1 -type f -name '*.deb' -exec cp {} "$PACKAGE_DIR/" \;
+ find "$artifact_dir" -maxdepth 1 -type f \( -name 'BUILD-INFO' -o -name 'bpf-next-kernel-build' -o -name 'config-*' \) -exec cp {} "$PACKAGE_DIR/" \;
+ fi
+elif [[ -f "$KERNEL_PACKAGE_PATH" ]]; then
+ package_file="$KERNEL_PACKAGE_PATH"
+ if [[ -n "$KERNEL_PACKAGE_SHA256" ]]; then
+ printf '%s %s\n' "$KERNEL_PACKAGE_SHA256" "$package_file" | sha256sum -c -
+ elif [[ -f "${package_file}.sha256sum" ]]; then
+ (cd "$(dirname "$package_file")" && sha256sum -c "$(basename "$package_file").sha256sum")
+ fi
+
+ case "$package_file" in
+ *.deb)
+ cp "$package_file" "$PACKAGE_DIR/"
+ ;;
+ *.zip)
+ unzip -q "$package_file" -d "$PACKAGE_DIR"
+ ;;
+ *)
+ tar -xzf "$package_file" -C "$PACKAGE_DIR"
+ ;;
+ esac
+else
+ echo "No kernel package file found in ${KERNEL_PACKAGE_PATH}" >&2
+ exit 1
+fi
+
+bundle_file="$(find "$PACKAGE_DIR" -type f -name 'bpf-next-kernel-debs.tar.gz' | sort | head -n 1)"
+if [[ -n "$bundle_file" ]]; then
+ if [[ -f "${bundle_file}.sha256sum" ]]; then
+ (cd "$(dirname "$bundle_file")" && sha256sum -c "$(basename "$bundle_file").sha256sum")
+ fi
+ tar -xzf "$bundle_file" -C "$PACKAGE_DIR"
+fi
+
+if [[ -f "${PACKAGE_DIR}/SHA256SUMS" ]]; then
+ (cd "$PACKAGE_DIR" && sha256sum -c SHA256SUMS)
+fi
+
+mapfile -t debs < <(
+ find "$PACKAGE_DIR" -type f \
+ \( -name 'linux-image-[0-9]*.deb' -o -name 'linux-headers-[0-9]*.deb' \) \
+ ! -name '*-dbg*' |
+ sort
+)
+
+if [[ "${#debs[@]}" -eq 0 ]]; then
+ echo "No linux-image or linux-headers deb packages found in ${KERNEL_PACKAGE_PATH}" >&2
+ exit 1
+fi
+
+image_deb="$(find "$PACKAGE_DIR" -type f -name 'linux-image-[0-9]*.deb' ! -name '*-dbg*' | sort | head -n 1)"
+if [[ -z "$image_deb" ]]; then
+ echo "No linux-image kernel package found in ${KERNEL_PACKAGE_PATH}" >&2
+ exit 1
+fi
+image_package="$(dpkg-deb -f "$image_deb" Package)"
+kernel_release="${image_package#linux-image-}"
+
+write_grub_defaults
+"${APT_GET[@]}" install -y --no-install-recommends "${debs[@]}"
+artifact_config="${PACKAGE_DIR}/config-${kernel_release}"
+if [[ ! -f "$artifact_config" && -f "${PACKAGE_DIR}/kernel.config" ]]; then
+ artifact_config="${PACKAGE_DIR}/kernel.config"
+fi
+boot_config="/boot/config-${kernel_release}"
+if [[ ! -f "$artifact_config" ]]; then
+ echo "Kernel artifact is missing config-${kernel_release} and kernel.config; refusing an unverified AMI kernel" >&2
+ exit 1
+fi
+if ! cmp -s "$artifact_config" "$boot_config"; then
+ echo "Installed kernel config differs from config-${kernel_release} in the kernel artifact" >&2
+ diff -u "$artifact_config" "$boot_config" | sed -n '1,120p' >&2 || true
+ exit 1
+fi
+
+require_kernel_config "$kernel_release" CONFIG_BPF_SYSCALL "BPF syscall support"
+require_kernel_config "$kernel_release" CONFIG_BPF_LSM "BPF LSM support"
+require_kernel_config "$kernel_release" CONFIG_DEBUG_INFO_BTF "BTF support for Shirudo's CO-RE programs"
+require_kernel_config "$kernel_release" CONFIG_KEYS "kernel keyrings"
+require_kernel_config "$kernel_release" CONFIG_MODULES "loadable kernel modules"
+require_kernel_config "$kernel_release" CONFIG_TCG_TPM "TPM support"
+require_kernel_config "$kernel_release" CONFIG_TCG_CRB "NitroTPM CRB driver"
+require_kernel_config "$kernel_release" CONFIG_DEVTMPFS "device filesystem support"
+require_kernel_config "$kernel_release" CONFIG_EXT4_FS "ext4 root filesystem support"
+require_kernel_config "$kernel_release" CONFIG_EXT4_FS_SECURITY "ext4 security xattrs for Shirudo seals"
+require_kernel_config "$kernel_release" CONFIG_NAMESPACES "namespace support for systemd services"
+require_kernel_config "$kernel_release" CONFIG_UTS_NS "UTS namespaces for systemd services"
+require_kernel_config "$kernel_release" CONFIG_SECCOMP "seccomp support for systemd services"
+require_kernel_config "$kernel_release" CONFIG_SECCOMP_FILTER "seccomp filter support for systemd services"
+require_kernel_config "$kernel_release" CONFIG_TMPFS_XATTR "tmpfs xattrs for Shirudo bpffs pins"
+require_kernel_config "$kernel_release" CONFIG_DM_VERITY "dm-verity support for authenticated images"
+require_kernel_config "$kernel_release" CONFIG_BLK_DEV_LOOP "loop devices for authenticated images"
+require_kernel_config "$kernel_release" CONFIG_BLK_DEV_NVME "NVMe root disk support"
+require_kernel_config "$kernel_release" CONFIG_ENA_ETHERNET "ENA network driver"
+require_kernel_config_value "$kernel_release" CONFIG_BLK_DEV_DM y "built-in device mapper support"
+ensure_ssm_agent_for_next_boot
+
+cleanup_apt_policy
+trap - EXIT
+
+metadata_file="$(find "$PACKAGE_DIR" -type f \( -name bpf-next-kernel-build -o -name BUILD-INFO \) | sort | head -n 1)"
+if [[ -n "$metadata_file" ]]; then
+ metadata_kernel_release="$(awk -F= '$1 == "kernel_release" || $1 == "kernelrelease" { print $2; exit }' "$metadata_file")"
+ if [[ -n "$metadata_kernel_release" && "$metadata_kernel_release" != "$kernel_release" ]]; then
+ echo "Kernel metadata release ${metadata_kernel_release} does not match image package ${kernel_release}; using image package" >&2
+ fi
+fi
+
+write_grub_defaults
+sudo depmod -a "$kernel_release"
+sudo sed -i '/^ena$/d; /^nvme$/d; /^nvme_core$/d' /etc/initramfs-tools/modules
+printf 'ena\nnvme\nnvme_core\n' | sudo tee -a /etc/initramfs-tools/modules >/dev/null
+sudo update-initramfs -u -k "$kernel_release"
+sudo update-grub
+
+sudo tee /etc/bpf-next-kernel-release >/dev/null <<<"$kernel_release"
+if [[ -n "$metadata_file" ]]; then
+ sudo install -m 0644 "$metadata_file" /etc/bpf-next-kernel-build
+else
+ sudo tee /etc/bpf-next-kernel-build >/dev/null <<EOF
+commit=unknown
+kernel_release=${kernel_release}
+installed_at=$(date -u +%Y-%m-%dT%H:%M:%SZ)
+EOF
+fi
+
+test -f "/boot/vmlinuz-${kernel_release}"
+test -d "/lib/modules/${kernel_release}"
+
+sudo rm -rf "$WORK_DIR"
+sudo apt-get clean
+sudo rm -rf /var/lib/apt/lists/*
diff --git a/infra/aws/packer/scripts/install-shirudo-target-from-github-artifact.sh b/infra/aws/packer/scripts/install-shirudo-target-from-github-artifact.sh
new file mode 100755
index 00000000..deb13b0b
--- /dev/null
+++ b/infra/aws/packer/scripts/install-shirudo-target-from-github-artifact.sh
@@ -0,0 +1,125 @@
+#!/usr/bin/env bash
+# SPDX-License-Identifier: BSD-2-Clause
+# Copyright (c) 2026 Authors of shirudo
+
+set -euo pipefail
+
+SHIRUDO_GITHUB_REPO="shirudo-dev/shirudo"
+SHIRUDO_GITHUB_WORKFLOW="packages.yml"
+SHIRUDO_GITHUB_ARTIFACT="shirudo-deb"
+SHIRUDO_GITHUB_RUN_ID="${SHIRUDO_GITHUB_RUN_ID:-}"
+SHIRUDO_INSTALL_PATH="${SHIRUDO_INSTALL_PATH:-/usr/local/bin/shirudo}"
+
+APT_GET=(
+ sudo
+ env
+ DEBIAN_FRONTEND=noninteractive
+ NEEDRESTART_MODE=l
+ apt-get
+ -o
+ DPkg::Lock::Timeout=600
+ -o
+ Dpkg::Options::=--force-confdef
+ -o
+ Dpkg::Options::=--force-confold
+)
+
+package_arch() {
+ case "$(uname -m)" in
+ x86_64)
+ echo "amd64"
+ ;;
+ aarch64 | arm64)
+ echo "arm64"
+ ;;
+ *)
+ echo "Unsupported machine architecture: $(uname -m)" >&2
+ exit 1
+ ;;
+ esac
+}
+
+latest_successful_run() {
+ local page=1 selection count run_id created_at head_sha
+
+ # Server-side branch/status filters can omit recent runs. Filter all metadata
+ # locally and paginate until a matching run is found.
+ while true; do
+ selection="$(gh api --method GET \
+ "repos/${SHIRUDO_GITHUB_REPO}/actions/workflows/${SHIRUDO_GITHUB_WORKFLOW}/runs" \
+ -f per_page=100 \
+ -f "page=${page}" \
+ --jq '.workflow_runs as $runs |
+ ([$runs[] | select(.head_branch == "main" and
+ .event == "push" and .status == "completed" and
+ .conclusion == "success")][0]) as $run |
+ [($runs | length), ($run.id // 0), ($run.created_at // "-"),
+ ($run.head_sha // "-")] | @tsv')" || return 1
+ IFS=$'\t' read -r count run_id created_at head_sha <<< "$selection"
+ if [[ "$run_id" != 0 ]]; then
+ echo "Selected Actions run ${run_id}: created ${created_at}, commit ${head_sha}" >&2
+ printf '%s\n' "$run_id"
+ return 0
+ fi
+ if [[ "$count" -lt 100 ]]; then
+ echo "No successful ${SHIRUDO_GITHUB_WORKFLOW} push run found on ${SHIRUDO_GITHUB_REPO}:main" >&2
+ return 1
+ fi
+ page=$((page + 1))
+ done
+}
+
+install_shirudo_deb() {
+ local artifact_dir="$1"
+ local arch="$2"
+ local package_path
+ local binary_path
+
+ package_path="$(find "$artifact_dir" -type f -name "shirudo-target_*_${arch}.deb" | sort | tail -n 1)"
+ if [[ -z "$package_path" ]]; then
+ package_path="$(find "$artifact_dir" -type f -name "shirudo-target_*.deb" | sort | tail -n 1)"
+ fi
+ if [[ -z "$package_path" ]]; then
+ echo "No shirudo-target deb package found in ${artifact_dir}" >&2
+ exit 1
+ fi
+
+ echo "Installing shirudo-target from ${package_path}"
+ "${APT_GET[@]}" install -y --no-install-recommends "$package_path"
+
+ binary_path="$(command -v shirudo || true)"
+ if [[ -z "$binary_path" ]]; then
+ echo "shirudo-target package did not install a shirudo binary" >&2
+ exit 1
+ fi
+ if [[ "$binary_path" != "$SHIRUDO_INSTALL_PATH" ]]; then
+ sudo ln -sf "$binary_path" "$SHIRUDO_INSTALL_PATH"
+ fi
+}
+
+"${APT_GET[@]}" update
+"${APT_GET[@]}" install -y --no-install-recommends \
+ ca-certificates \
+ coreutils \
+ gh \
+ libtss2-tctildr0
+
+arch="$(package_arch)"
+tmp_dir="$(mktemp -d)"
+trap 'rm -rf "$tmp_dir"' EXIT
+
+if [[ -z "$SHIRUDO_GITHUB_RUN_ID" ]]; then
+ echo "Selecting the latest successful ${SHIRUDO_GITHUB_WORKFLOW} push run on ${SHIRUDO_GITHUB_REPO}:main"
+ SHIRUDO_GITHUB_RUN_ID="$(latest_successful_run)"
+fi
+
+echo "Downloading ${SHIRUDO_GITHUB_ARTIFACT} from ${SHIRUDO_GITHUB_REPO} Actions run ${SHIRUDO_GITHUB_RUN_ID}"
+gh run download "$SHIRUDO_GITHUB_RUN_ID" \
+ --repo "$SHIRUDO_GITHUB_REPO" \
+ --name "$SHIRUDO_GITHUB_ARTIFACT" \
+ --dir "${tmp_dir}/shirudo-deb"
+
+install_shirudo_deb "${tmp_dir}/shirudo-deb" "$arch"
+
+"$SHIRUDO_INSTALL_PATH" --help >/dev/null || true
+ls -l "$SHIRUDO_INSTALL_PATH"
diff --git a/infra/aws/packer/scripts/pre-reboot-diagnostics.sh b/infra/aws/packer/scripts/pre-reboot-diagnostics.sh
new file mode 100755
index 00000000..7e7cd7aa
--- /dev/null
+++ b/infra/aws/packer/scripts/pre-reboot-diagnostics.sh
@@ -0,0 +1,118 @@
+#!/usr/bin/env bash
+# SPDX-License-Identifier: BSD-2-Clause
+# Copyright (c) 2026 Authors of shirudo
+
+set -uo pipefail
+
+section() {
+ printf '\n===== %s =====\n' "$1"
+}
+
+run() {
+ printf '+ %s\n' "$*"
+ "$@" 2>&1 || printf 'command failed with exit %s: %s\n' "$?" "$*"
+}
+
+run_shell() {
+ printf '+ %s\n' "$*"
+ bash -c "$*" 2>&1 || printf 'command failed with exit %s: %s\n' "$?" "$*"
+}
+
+expected_kernel=""
+if [[ -r /etc/bpf-next-kernel-release ]]; then
+ expected_kernel="$(cat /etc/bpf-next-kernel-release)"
+fi
+
+section "Kernel Metadata"
+run uname -a
+run cat /etc/os-release
+if [[ -n "$expected_kernel" ]]; then
+ printf 'expected_kernel=%s\n' "$expected_kernel"
+else
+ printf 'expected_kernel=<missing /etc/bpf-next-kernel-release>\n'
+fi
+if [[ -r /etc/bpf-next-kernel-build ]]; then
+ run cat /etc/bpf-next-kernel-build
+fi
+
+section "Boot Files"
+run ls -lh /boot
+if [[ -n "$expected_kernel" ]]; then
+ run ls -lh "/boot/vmlinuz-${expected_kernel}" "/boot/initrd.img-${expected_kernel}" "/boot/config-${expected_kernel}"
+fi
+
+section "Installed Kernel Packages"
+run_shell "dpkg -l 'linux-image*' 'linux-headers*' 'linux-libc-dev*' 2>/dev/null | sed -n '1,160p'"
+
+section "GRUB Defaults"
+if [[ -r /etc/default/grub ]]; then
+ run sed -n '1,220p' /etc/default/grub
+fi
+for grub_default in /etc/default/grub.d/*.cfg; do
+ [[ -e "$grub_default" ]] || continue
+ printf '\n--- %s ---\n' "$grub_default"
+ sed -n '1,220p' "$grub_default" 2>&1 || true
+done
+
+section "GRUB Entries For Expected Kernel"
+if [[ -n "$expected_kernel" && -r /boot/grub/grub.cfg ]]; then
+ printf '+ grep -F -n -A 12 -B 3 %q /boot/grub/grub.cfg\n' "$expected_kernel"
+ grep -F -n -A 12 -B 3 "$expected_kernel" /boot/grub/grub.cfg 2>&1 |
+ sed -n '1,240p' || true
+elif [[ ! -r /boot/grub/grub.cfg ]]; then
+ printf '/boot/grub/grub.cfg is not readable\n'
+ run ls -lh /boot/grub
+fi
+
+section "GRUB linux/initrd Lines"
+if [[ -r /boot/grub/grub.cfg ]]; then
+ run_shell "grep -nE '^[[:space:]]*(menuentry|linux|linuxefi|initrd|initrdefi)[[:space:]]' /boot/grub/grub.cfg | sed -n '1,240p'"
+fi
+
+section "Expected Kernel Config"
+if [[ -n "$expected_kernel" && -r "/boot/config-${expected_kernel}" ]]; then
+ for symbol in \
+ CONFIG_BPF_LSM \
+ CONFIG_DEBUG_INFO_BTF \
+ CONFIG_PCI \
+ CONFIG_PCI_MSI \
+ CONFIG_NETDEVICES \
+ CONFIG_ETHERNET \
+ CONFIG_NET_VENDOR_AMAZON \
+ CONFIG_ENA_ETHERNET \
+ CONFIG_NVME_CORE \
+ CONFIG_BLK_DEV_NVME \
+ CONFIG_NVME_MULTIPATH \
+ CONFIG_DEVTMPFS \
+ CONFIG_TCG_TPM \
+ CONFIG_TCG_TIS_CORE \
+ CONFIG_TCG_TIS \
+ CONFIG_TCG_CRB \
+ CONFIG_BLK_DEV_LOOP \
+ CONFIG_SQUASHFS \
+ CONFIG_EXT4_FS \
+ CONFIG_XFS_FS; do
+ grep -E "^${symbol}=|^# ${symbol} is not set" "/boot/config-${expected_kernel}" || true
+ done
+fi
+
+section "Expected Initramfs Driver Hints"
+if [[ -n "$expected_kernel" && -r "/boot/initrd.img-${expected_kernel}" ]]; then
+ if command -v lsinitramfs >/dev/null 2>&1; then
+ printf '+ lsinitramfs /boot/initrd.img-%s | grep -E "(^|/)(ena|nvme|ext4|xfs|virtio)[^/]*$"\n' "$expected_kernel"
+ lsinitramfs "/boot/initrd.img-${expected_kernel}" 2>&1 |
+ grep -E '(^|/)(ena|nvme|ext4|xfs|virtio)[^/]*$' |
+ sed -n '1,200p' || true
+ else
+ printf 'lsinitramfs is not installed\n'
+ fi
+fi
+
+section "Current Root And Network"
+run findmnt /
+run lsblk -f
+run ip addr
+run ip route
+
+section "SSM Agent State"
+run_shell "systemctl --no-pager status amazon-ssm-agent snap.amazon-ssm-agent.amazon-ssm-agent 2>&1 | sed -n '1,180p'"
diff --git a/infra/aws/packer/scripts/register-nitrotpm-ami.sh b/infra/aws/packer/scripts/register-nitrotpm-ami.sh
new file mode 100755
index 00000000..0740b4c7
--- /dev/null
+++ b/infra/aws/packer/scripts/register-nitrotpm-ami.sh
@@ -0,0 +1,149 @@
+#!/usr/bin/env bash
+# SPDX-License-Identifier: BSD-2-Clause
+# Copyright (c) 2026 Authors of shirudo
+
+set -euo pipefail
+
+: "${AWS_REGION:?AWS_REGION is required}"
+: "${PACKER_MANIFEST_PATH:?PACKER_MANIFEST_PATH is required}"
+: "${UBUNTU_VERSION:?UBUNTU_VERSION is required}"
+: "${KERNEL_ARTIFACT_NAME:?KERNEL_ARTIFACT_NAME is required}"
+
+SHIRUDO_IMAGE_ROLE="${SHIRUDO_IMAGE_ROLE:-target}"
+case "$SHIRUDO_IMAGE_ROLE" in
+ dev | target) ;;
+ *)
+ echo "SHIRUDO_IMAGE_ROLE must be dev or target" >&2
+ exit 1
+ ;;
+esac
+
+require_command() {
+ local command_name="$1"
+
+ command -v "$command_name" >/dev/null 2>&1 || {
+ echo "${command_name} is required" >&2
+ exit 1
+ }
+}
+
+image_field() {
+ local image_id="$1"
+ local query="$2"
+
+ aws ec2 describe-images \
+ --region "$AWS_REGION" \
+ --image-ids "$image_id" \
+ --query "$query" \
+ --output text
+}
+
+require_command aws
+
+if [[ ! -r "$PACKER_MANIFEST_PATH" ]]; then
+ echo "Packer manifest not found: ${PACKER_MANIFEST_PATH}" >&2
+ exit 1
+fi
+
+artifact_id="$(
+ sed -n 's/.*"artifact_id"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$PACKER_MANIFEST_PATH" |
+ tail -n 1
+)"
+
+if [[ -z "$artifact_id" || "$artifact_id" == "null" ]]; then
+ echo "Could not find artifact_id in ${PACKER_MANIFEST_PATH}" >&2
+ exit 1
+fi
+
+artifact_region="${artifact_id%%:*}"
+source_ami_id="${artifact_id##*:}"
+
+if [[ -n "$artifact_region" && "$artifact_region" != "$source_ami_id" ]]; then
+ AWS_REGION="$artifact_region"
+fi
+
+source_name="$(image_field "$source_ami_id" 'Images[0].Name')"
+architecture="$(image_field "$source_ami_id" 'Images[0].Architecture')"
+root_device_name="$(image_field "$source_ami_id" 'Images[0].RootDeviceName')"
+virtualization_type="$(image_field "$source_ami_id" 'Images[0].VirtualizationType')"
+ena_support="$(image_field "$source_ami_id" 'Images[0].EnaSupport')"
+snapshot_id="$(image_field "$source_ami_id" "Images[0].BlockDeviceMappings[?DeviceName=='${root_device_name}'].Ebs.SnapshotId | [0]")"
+volume_size="$(image_field "$source_ami_id" "Images[0].BlockDeviceMappings[?DeviceName=='${root_device_name}'].Ebs.VolumeSize | [0]")"
+volume_type="$(image_field "$source_ami_id" "Images[0].BlockDeviceMappings[?DeviceName=='${root_device_name}'].Ebs.VolumeType | [0]")"
+delete_on_termination="$(image_field "$source_ami_id" "Images[0].BlockDeviceMappings[?DeviceName=='${root_device_name}'].Ebs.DeleteOnTermination | [0]")"
+iops="$(image_field "$source_ami_id" "Images[0].BlockDeviceMappings[?DeviceName=='${root_device_name}'].Ebs.Iops | [0]")"
+throughput="$(image_field "$source_ami_id" "Images[0].BlockDeviceMappings[?DeviceName=='${root_device_name}'].Ebs.Throughput | [0]")"
+
+if [[ -z "$source_name" || "$source_name" == "None" || -z "$snapshot_id" || "$snapshot_id" == "None" ]]; then
+ echo "Could not derive source AMI metadata from ${source_ami_id}" >&2
+ exit 1
+fi
+
+tpm_ami_name="${source_name}-nitrotpm-v2"
+existing_tpm_ami_id="$(
+ aws ec2 describe-images \
+ --region "$AWS_REGION" \
+ --owners self \
+ --filters "Name=name,Values=${tpm_ami_name}" "Name=tpm-support,Values=v2.0" \
+ --query 'Images | sort_by(@, &CreationDate)[-1].ImageId' \
+ --output text
+)"
+
+if [[ -n "$existing_tpm_ami_id" && "$existing_tpm_ami_id" != "None" ]]; then
+ aws ec2 create-tags \
+ --region "$AWS_REGION" \
+ --resources "$existing_tpm_ami_id" \
+ --tags "Key=ShirudoRole,Value=${SHIRUDO_IMAGE_ROLE}"
+ echo "NitroTPM AMI already exists: ${existing_tpm_ami_id} (${tpm_ami_name})"
+ exit 0
+fi
+
+block_device_mapping="DeviceName=${root_device_name},Ebs={SnapshotId=${snapshot_id},DeleteOnTermination=${delete_on_termination},VolumeType=${volume_type},VolumeSize=${volume_size}"
+if [[ -n "$iops" && "$iops" != "None" ]]; then
+ block_device_mapping="${block_device_mapping},Iops=${iops}"
+fi
+if [[ -n "$throughput" && "$throughput" != "None" ]]; then
+ block_device_mapping="${block_device_mapping},Throughput=${throughput}"
+fi
+block_device_mapping="${block_device_mapping}}"
+
+register_args=(
+ ec2
+ register-image
+ --region "$AWS_REGION"
+ --name "$tpm_ami_name"
+ --description "NitroTPM-enabled ${source_name}"
+ --architecture "$architecture"
+ --root-device-name "$root_device_name"
+ --virtualization-type "$virtualization_type"
+ --boot-mode uefi
+ --tpm-support v2.0
+ --block-device-mappings "$block_device_mapping"
+ --tag-specifications "ResourceType=image,Tags=[{Key=Name,Value=${tpm_ami_name}},{Key=BaseOS,Value=ubuntu-${UBUNTU_VERSION}},{Key=KernelFlavor,Value=bpf-next},{Key=ShirudoRole,Value=${SHIRUDO_IMAGE_ROLE}},{Key=TpmSupport,Value=v2.0}]"
+ --query ImageId
+ --output text
+)
+
+if [[ "$ena_support" == "True" || "$ena_support" == "true" ]]; then
+ register_args+=(--ena-support)
+fi
+
+echo "Registering NitroTPM AMI from ${source_ami_id} (${source_name})..."
+tpm_ami_id="$(aws "${register_args[@]}")"
+
+aws ec2 create-tags \
+ --region "$AWS_REGION" \
+ --resources "$tpm_ami_id" \
+ --tags \
+ "Key=KernelDebs,Value=${KERNEL_ARTIFACT_NAME}" \
+ "Key=SourceAmi,Value=${source_ami_id}"
+
+aws ec2 wait image-available \
+ --region "$AWS_REGION" \
+ --image-ids "$tpm_ami_id"
+
+aws ec2 describe-images \
+ --region "$AWS_REGION" \
+ --image-ids "$tpm_ami_id" \
+ --query 'Images[0].{ImageId:ImageId,Name:Name,BootMode:BootMode,TpmSupport:TpmSupport}' \
+ --output table
diff --git a/infra/aws/packer/tests/test-image-roles.sh b/infra/aws/packer/tests/test-image-roles.sh
new file mode 100644
index 00000000..08c9dafe
--- /dev/null
+++ b/infra/aws/packer/tests/test-image-roles.sh
@@ -0,0 +1,177 @@
+#!/usr/bin/env bash
+# SPDX-License-Identifier: BSD-2-Clause
+# Copyright (c) 2026 Authors of shirudo
+
+set -euo pipefail
+
+script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
+packer_dir=$(cd "$script_dir/.." && pwd)
+registrar="$packer_dir/scripts/register-nitrotpm-ami.sh"
+tmp_dir=$(mktemp -d)
+trap 'rm -rf "$tmp_dir"' EXIT
+
+command -v packer >/dev/null
+command -v jq >/dev/null
+
+selection() {
+ printf 'jsonencode({prefix=local.ami_prefix, except=local.target_provisioner_except, run_tags=local.packer_run_tags, volume_tags=local.packer_run_volume_tags})\n' |
+ packer console \
+ -var 'iam_instance_profile=validation-only' \
+ "$@" "$packer_dir"
+}
+
+assert_contains() {
+ grep -Fq -- "$1" "$2" || {
+ echo "Expected '$1' in $2" >&2
+ exit 1
+ }
+}
+
+validate() {
+ packer validate \
+ -var 'iam_instance_profile=validation-only' \
+ "$@" "$packer_dir" > "$tmp_dir/validate.log" 2>&1 || {
+ cat "$tmp_dir/validate.log" >&2
+ return 1
+ }
+}
+
+selection | jq -e '.prefix == "shirudo-target-ubuntu" and .except == [] and (.run_tags | has("expiry") | not) and (.volume_tags | has("expiry") | not)' >/dev/null
+echo 'ok: target is the default role and expiry tags are omitted by default'
+
+selection -var 'additional_build_tags={owner="test", expiry="2099-12-31"}' |
+ jq -e '.run_tags.owner == "test" and .volume_tags.owner == "test" and .run_tags.expiry == "2099-12-31" and .volume_tags.expiry == "2099-12-31"' >/dev/null
+echo 'ok: owner and expiry tags reach the builder and root volume'
+
+selection -var 'additional_build_tags={svic_osquery_supported="no"}' |
+ jq -e '.run_tags.svic_osquery_supported == "no" and .volume_tags.svic_osquery_supported == "no"' >/dev/null
+echo 'ok: additional build tags reach the builder and root volume'
+
+selection -var 'image_role=dev' |
+ jq -e '.prefix == "shirudo-dev-ubuntu" and .except == ["amazon-ebs.bpf_next_ubuntu"]' >/dev/null
+validate -var 'image_role=dev'
+echo 'ok: dev uses a separate name prefix and excludes target provisioning'
+
+selection -var 'image_role=target' |
+ jq -e '.prefix == "shirudo-target-ubuntu" and .except == []' >/dev/null
+validate
+echo 'ok: target preserves all provisioning steps'
+
+if packer validate \
+ -var 'iam_instance_profile=validation-only' \
+ -var 'image_role=invalid' "$packer_dir" > "$tmp_dir/error.log" 2>&1; then
+ echo 'Expected invalid image role to fail validation' >&2
+ exit 1
+fi
+assert_contains 'The image_role must be dev or target.' "$tmp_dir/error.log"
+echo 'ok: Packer rejects invalid image roles'
+
+awk '
+ /^ provisioner / { block = $0; next }
+ block != "" {
+ block = block "\n" $0
+ if ($0 == " }") {
+ if (block ~ /install-shirudo-target|configure-shirudo-initrd|local.shirudo_cert_path|\/var\/lib\/shirudo\/keys/) {
+ if (block ~ /configure-shirudo-initrd/) {
+ if (block !~ /except[[:space:]]*=[[:space:]]*local[.]target_provisioner_except/)
+ failed = 1
+ } else if (block !~ /except[[:space:]]*=[[:space:]]*local[.]target_provisioner_except/) {
+ failed = 1
+ }
+ checked++
+ }
+ block = ""
+ }
+ }
+ END { exit failed || checked != 5 }
+' "$packer_dir/bpf-next-ubuntu.pkr.hcl"
+echo 'ok: package, certificate and initrd provisioners are all role-gated'
+
+export AWS_REGION=us-west-2
+export PACKER_MANIFEST_PATH="$tmp_dir/manifest.json"
+export UBUNTU_VERSION=26.04
+export KERNEL_ARTIFACT_NAME=kernel-packages-x86-64-full
+export TEST_AWS_LOG="$tmp_dir/aws.log"
+export MOCK_AMI_PREFIX=shirudo-target-ubuntu
+export MOCK_EXISTING_AMI=None
+printf '{"builds":[{"artifact_id":"us-west-2:ami-source"}]}\n' > "$PACKER_MANIFEST_PATH"
+
+aws() {
+ local operation="$1 $2" query= image_id=
+
+ printf '%s\n' "$*" >> "$TEST_AWS_LOG"
+ shift 2
+ while [[ "$#" -gt 0 ]]; do
+ case "$1" in
+ --query) query="$2"; shift ;;
+ --image-ids) image_id="$2"; shift ;;
+ esac
+ shift
+ done
+ case "$operation" in
+ 'ec2 describe-images')
+ if [[ -z "$image_id" ]]; then
+ printf '%s\n' "$MOCK_EXISTING_AMI"
+ return
+ fi
+ case "$query" in
+ 'Images[0].Name') echo "$MOCK_AMI_PREFIX-26.04-123" ;;
+ 'Images[0].Architecture') echo x86_64 ;;
+ 'Images[0].RootDeviceName') echo /dev/sda1 ;;
+ 'Images[0].VirtualizationType') echo hvm ;;
+ 'Images[0].EnaSupport') echo True ;;
+ *Ebs.SnapshotId*) echo snap-test ;;
+ *Ebs.VolumeSize*) echo 30 ;;
+ *Ebs.VolumeType*) echo gp3 ;;
+ *Ebs.DeleteOnTermination*) echo True ;;
+ *Ebs.Iops*) echo 3000 ;;
+ *Ebs.Throughput*) echo 125 ;;
+ *ImageId*) echo '{}' ;;
+ *) echo "Unexpected image query: $query" >&2; return 1 ;;
+ esac
+ ;;
+ 'ec2 register-image') echo ami-registered ;;
+ 'ec2 create-tags' | 'ec2 wait') ;;
+ *) echo "Unexpected AWS operation: $operation" >&2; return 1 ;;
+ esac
+}
+export -f aws
+
+for role in dev target; do
+ if [[ "$role" == dev ]]; then
+ MOCK_AMI_PREFIX=shirudo-dev-ubuntu
+ else
+ MOCK_AMI_PREFIX=shirudo-target-ubuntu
+ fi
+ : > "$TEST_AWS_LOG"
+ SHIRUDO_IMAGE_ROLE="$role" bash "$registrar" > "$tmp_dir/register.log"
+ assert_contains "--name $MOCK_AMI_PREFIX-26.04-123-nitrotpm-v2" "$TEST_AWS_LOG"
+ assert_contains "{Key=ShirudoRole,Value=$role}" "$TEST_AWS_LOG"
+ assert_contains '--boot-mode uefi --tpm-support v2.0' "$TEST_AWS_LOG"
+ if grep -Eq 'Key=(owner|expiry)' "$TEST_AWS_LOG"; then
+ echo 'NitroTPM AMI must not receive owner or expiry tags' >&2
+ exit 1
+ fi
+ echo "ok: $role NitroTPM AMI is registered with its role tag"
+
+ MOCK_EXISTING_AMI=ami-existing
+ : > "$TEST_AWS_LOG"
+ SHIRUDO_IMAGE_ROLE="$role" bash "$registrar" > "$tmp_dir/register.log"
+ assert_contains "--resources ami-existing --tags Key=ShirudoRole,Value=$role" "$TEST_AWS_LOG"
+ if grep -q '^ec2 register-image ' "$TEST_AWS_LOG"; then
+ echo 'An existing NitroTPM AMI must not be registered again' >&2
+ exit 1
+ fi
+ MOCK_EXISTING_AMI=None
+ echo "ok: rerunning registration tags the existing $role AMI"
+
+done
+
+: > "$TEST_AWS_LOG"
+if SHIRUDO_IMAGE_ROLE=invalid bash "$registrar" > "$tmp_dir/error.log" 2>&1; then
+ echo 'Expected registration to reject an invalid image role' >&2
+ exit 1
+fi
+[[ ! -s "$TEST_AWS_LOG" ]]
+assert_contains 'SHIRUDO_IMAGE_ROLE must be dev or target' "$tmp_dir/error.log"
+echo 'ok: invalid registration role fails before any AWS calls'
diff --git a/infra/aws/packer/tests/test-kernel-artifact.sh b/infra/aws/packer/tests/test-kernel-artifact.sh
new file mode 100644
index 00000000..059946f2
--- /dev/null
+++ b/infra/aws/packer/tests/test-kernel-artifact.sh
@@ -0,0 +1,130 @@
+#!/usr/bin/env bash
+# SPDX-License-Identifier: BSD-2-Clause
+# Copyright (c) 2026 Authors of shirudo
+
+set -euo pipefail
+
+script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
+installer="$script_dir/../scripts/install-bpf-next-kernel.sh"
+tmp_dir=$(mktemp -d)
+trap 'rm -rf "$tmp_dir"' EXIT
+
+command -v jq >/dev/null
+eval "$(sed -n \
+ '/^latest_successful_kernel_run() {/,/^}/p; /^download_kernel_artifact() {/,/^}/p' \
+ "$installer")"
+
+KERNEL_GITHUB_REPO=shirudo-dev/kernel
+KERNEL_GITHUB_WORKFLOW=build-kernel-packages.yml
+KERNEL_GITHUB_ARTIFACT=kernel-packages-x86-64-full
+KERNEL_GITHUB_RUN_ID=
+scenario=success
+
+# Exercise the actual jq selection against mock GitHub API responses.
+gh() {
+ printf '%s\n' "$*" >> "$tmp_dir/gh.log"
+ if [[ "$1" == api ]]; then
+ local page query response arg
+ [[ "$scenario" != api_failure ]] || return 1
+ [[ "$*" == *"repos/$KERNEL_GITHUB_REPO/actions/workflows/$KERNEL_GITHUB_WORKFLOW/runs"* ]]
+ page=1
+ query=
+ while [[ "$#" -gt 0 ]]; do
+ arg="$1"
+ shift
+ case "$arg" in
+ page=*) page="${arg#page=}" ;;
+ branch=* | status=* | event=* | exclude_pull_requests=*)
+ echo "Unexpected server-side filter: $arg" >&2
+ return 1
+ ;;
+ --jq) query="$1"; shift ;;
+ esac
+ done
+ if [[ "$scenario" == no_match || "$page" == 1 && "$scenario" == paginated ]]; then
+ response=$(jq -n --argjson count "$([[ "$scenario" == paginated ]] && echo 100 || echo 1)" \
+ '{workflow_runs: [range($count) | {id: 999, head_branch: "feature", status: "completed", conclusion: "success"}]}')
+ else
+ response='{"workflow_runs":[
+ {"id":104,"head_branch":"main","status":"in_progress","conclusion":null},
+ {"id":103,"head_branch":"main","status":"completed","conclusion":"failure"},
+ {"id":102,"head_branch":"feature","status":"completed","conclusion":"success"},
+ {"id":101,"head_branch":"main","event":"workflow_dispatch","status":"completed","conclusion":"success","created_at":"2026-10-16T23:16:57Z","head_sha":"abc123"},
+ {"id":100,"head_branch":"main","event":"push","status":"completed","conclusion":"success"}
+ ]}'
+ fi
+ jq -r "$query" <<< "$response"
+ elif [[ "$1 $2" == "run download" ]]; then
+ [[ "$scenario" != download_failure ]] || return 1
+ else
+ echo "Unexpected gh command: $*" >&2
+ return 1
+ fi
+}
+
+assert_contains() {
+ grep -Fq -- "$1" "$2" || {
+ echo "Expected '$1' in $2" >&2
+ exit 1
+ }
+}
+
+run_id=$(latest_successful_kernel_run 2> "$tmp_dir/selection.log")
+[[ "$run_id" == 101 ]]
+assert_contains 'commit abc123' "$tmp_dir/selection.log"
+echo 'ok: selects latest successful main workflow_dispatch run'
+
+export KERNEL_GITHUB_BRANCH=feature
+[[ "$(latest_successful_kernel_run 2>/dev/null)" == 101 ]]
+unset KERNEL_GITHUB_BRANCH
+echo 'ok: always selects main despite branch environment'
+
+scenario=paginated
+: > "$tmp_dir/gh.log"
+[[ "$(latest_successful_kernel_run 2>/dev/null)" == 101 ]]
+assert_contains 'page=2' "$tmp_dir/gh.log"
+echo 'ok: paginates past 100 non-matching runs'
+
+scenario=no_match
+if latest_successful_kernel_run > "$tmp_dir/result" 2> "$tmp_dir/error"; then
+ echo 'Expected selection failure when no successful run exists' >&2
+ exit 1
+fi
+assert_contains 'No successful build-kernel-packages.yml run found' "$tmp_dir/error"
+echo 'ok: reports no matching run'
+
+scenario=success
+: > "$tmp_dir/gh.log"
+download_kernel_artifact "$tmp_dir/artifact" > "$tmp_dir/download.log" 2>&1
+assert_contains "run download 101 --repo $KERNEL_GITHUB_REPO --name $KERNEL_GITHUB_ARTIFACT --dir $tmp_dir/artifact" "$tmp_dir/gh.log"
+echo 'ok: downloads selected artifact into requested directory'
+
+KERNEL_GITHUB_RUN_ID=42
+: > "$tmp_dir/gh.log"
+download_kernel_artifact "$tmp_dir/artifact" > "$tmp_dir/download.log" 2>&1
+assert_contains 'run download 42' "$tmp_dir/gh.log"
+if grep -q '^api ' "$tmp_dir/gh.log"; then
+ echo 'Explicit run id must bypass workflow selection' >&2
+ exit 1
+fi
+KERNEL_GITHUB_RUN_ID=
+echo 'ok: explicit run id bypasses selection'
+
+scenario=api_failure
+: > "$tmp_dir/gh.log"
+if download_kernel_artifact "$tmp_dir/artifact" > "$tmp_dir/download.log" 2>&1; then
+ echo 'Expected API failure to propagate' >&2
+ exit 1
+fi
+if grep -q '^run download ' "$tmp_dir/gh.log"; then
+ echo 'Download must not continue after API failure' >&2
+ exit 1
+fi
+echo 'ok: API failure prevents download'
+
+scenario=download_failure
+if download_kernel_artifact "$tmp_dir/artifact" > "$tmp_dir/download.log" 2>&1; then
+ echo 'Expected artifact download failure to propagate' >&2
+ exit 1
+fi
+echo 'ok: artifact download failure propagates'