Skip to content
OpenNebula · Chapter 18 of 21 Day 16: Build Images with Packer and Share Them in Your Own Marketplace

Day 16: Build Images with Packer and Share Them in Your Own Marketplace

Goal: Build the notes image from Day 10 reproducibly with Packer, publish it in your own marketplace, and fetch it from there again like a user. · Duration: approx. 90 min · Prerequisite: Day 10, Day 15

IDs and addresses in the outputs come from the test run and will differ for you.

Briefing

  • On Day 10, notes-basis was made by hand: start a VM, install packages, save the disk. Whoever has to repeat that in three months with new packages must remember every step.
  • Packer by HashiCorp describes the same path as a file. The qemu builder starts the base image as a VM directly with KVM, without OpenNebula, runs the steps via SSH, and writes out the disk as qcow2. OpenNebula builds its own appliances in the one-apps repository exactly this way.
  • A marketplace is a catalog of apps from which you fetch images into your own cloud (Day 3, Day 15). Besides the public one, you can create your own. The simplest type is http: OpenNebula puts the image into a directory, and a web server delivers it.
 Marketplace OpenNebula ──(Alpine-Image, MD5)──► Packer + qemu/KVM ──► ausgabe/notes-basis.qcow2
                                                    │ apk add podman, podman pull, aufräumen
 oneimage create ◄── /var/tmp ◄────────────────────┘
      │
      ▼ onemarketapp create
 Marketplace lokal  /var/local/market-http ──► http://172.16.0.61:8000
      │
      ▼ onemarketapp export
 Image notes-vom-markt ──► VM m16

Drill 1: Install Packer

Packer comes as a single file. The checksums are right next to it:

ARCH=$(dpkg --print-architecture)
V=1.16.3
cd /tmp
curl -fsSLO https://releases.hashicorp.com/packer/${V}/packer_${V}_linux_${ARCH}.zip
curl -fsSLO https://releases.hashicorp.com/packer/${V}/packer_${V}_SHA256SUMS
grep "linux_${ARCH}.zip" packer_${V}_SHA256SUMS | sha256sum -c -
sudo unzip -o -q packer_${V}_linux_${ARCH}.zip packer -d /usr/local/bin
packer version
  • dpkg --print-architecture returns amd64 or arm64, which is exactly how the files at HashiCorp are named.
  • curl -fsSLO: -f aborts on HTTP errors, -sS stays silent except on errors, -L follows redirects, -O saves under the name from the URL.
  • sha256sum -c - reads checksum and file name from grep and checks the file.
  • unzip -o -q … packer -d /usr/local/bin: extract only the packer file, overwrite without asking, without output.

Expected:

packer_1.16.3_linux_amd64.zip: OK
Packer v1.16.3

Packer starts the build VM with KVM. The /dev/kvm device belongs to the kvm group:

ls -l /dev/kvm
sudo usermod -aG kvm $USER

Expected:

crw-rw---- 1 root kvm 10, 232 Nov 27 17:47 /dev/kvm

usermod -aG appends the group (-a) instead of replacing the group list. It only takes effect after a new login: log out and log in again via SSH. Then:

id | grep -o 'kvm'

Expected: kvm.

Save your progress? Sign up for free

Drill 2: The context CD for the build

The build VM runs outside OpenNebula. But one-context in the Alpine image waits for a context CD (Day 4). Packer can create a CD; you supply the content. For access, the build gets a key of its own:

mkdir -p ~/one-lab/tag16/context
cd ~/one-lab/tag16
ssh-keygen -q -t ed25519 -N '' -C packer-bau -f packer_key
cat > context/context.sh <<EOF
ETH0_MAC='02:00:00:00:16:01'
ETH0_METHOD='dhcp'
NETWORK='YES'
SET_HOSTNAME='bau'
SSH_PUBLIC_KEY='$(cat packer_key.pub)'
EOF
cut -c1-50 context/context.sh
  • ssh-keygen -q -t ed25519 -N '' -C packer-bau -f packer_key: without output (-q), type ed25519, without a passphrase (-N ''), with a comment, as the file packer_key.
  • The EOF without quotes is intentional: this way, the shell substitutes $(cat …).
  • ETH0_METHOD='dhcp': in the build VM there is no OpenNebula to assign an address. qemu brings its own small network with DHCP.
  • ETH0_MAC must match the network card that Packer creates shortly. This is how one-context recognizes which card is ETH0.

Expected:

ETH0_MAC='02:00:00:00:16:01'
ETH0_METHOD='dhcp'
NETWORK='YES'
SET_HOSTNAME='bau'
SSH_PUBLIC_KEY='ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AA

Save your progress? Sign up for free

Drill 3: The Packer template

The same steps as on Day 10, Drill 1, plus the cleanup from the Enterprise Note of Day 10:

cat > notes-basis.pkr.hcl <<'EOF'
packer {
  required_plugins {
    qemu = {
      source  = "github.com/hashicorp/qemu"
      version = "= 1.1.8"
    }
  }
}

variable "basis_url" {
  type        = string
  description = "Download-Adresse des Alpine-Images im Marketplace"
}

variable "basis_md5" {
  type        = string
  description = "MD5-Prüfsumme laut Marketplace"
}

source "qemu" "notes" {
  iso_url          = var.basis_url
  iso_checksum     = "md5:${var.basis_md5}"
  disk_image       = true
  use_backing_file = false
  format           = "qcow2"
  disk_size        = "512M"
  disk_interface   = "virtio"
  accelerator      = "kvm"
  cpus             = 1
  memory           = 512
  headless         = true

  cd_files = ["context/context.sh"]
  cd_label = "CONTEXT"

  qemuargs = [
    ["-netdev", "user,id=net0,hostfwd=tcp::{{ .SSHHostPort }}-:22"],
    ["-device", "virtio-net-pci,netdev=net0,mac=02:00:00:00:16:01"],
  ]

  ssh_username         = "root"
  ssh_private_key_file = "packer_key"
  ssh_timeout          = "10m"
  shutdown_command     = "poweroff"

  output_directory = "ausgabe"
  vm_name          = "notes-basis.qcow2"
}

build {
  sources = ["source.qemu.notes"]

  provisioner "shell" {
    inline = [
      "apk add -q podman",
      "rc-update add cgroups",
      "rc-service cgroups start",
      "podman pull -q ghcr.io/thomaszachmann/notes-api:0.7.1",
      "rm -rf /var/cache/apk/*",
      "podman images",
      "df -h / | tail -1",
    ]
  }

  provisioner "shell" {
    inline = [
      "rm -f /root/.ssh/authorized_keys /etc/ssh/ssh_host_*",
      "rm -f /root/.ash_history",
    ]
  }
}
EOF

The important parts:

  • required_plugins: the qemu builder is a plugin. The version is pinned so that the build runs the same way in a year.
  • iso_url and iso_checksum: where the base image comes from and how Packer checks it. The name “iso” is historical; disk_image = true says: this is a finished disk, not installation media.
  • use_backing_file = false: a standalone copy instead of a layer on top of the original.
  • disk_size = "512M": as large as the base image. Larger would work, but the file system would not grow along by itself.
  • accelerator = "kvm", cpus, memory: the build VM.
  • cd_files and cd_label = "CONTEXT": Packer burns context.sh onto a CD labeled CONTEXT. That is exactly the name one-context looks for.
  • qemuargs: replaces network and card. user is qemu’s built-in network; hostfwd forwards a free port of the host ({{ .SSHHostPort }}) to port 22 of the VM. The MAC is the same as in context.sh.
  • ssh_*: Packer logs in as root with the build key and waits up to ten minutes for it.
  • shutdown_command = "poweroff": shut down cleanly before the disk is copied.
  • The second provisioner cleans up: the build key and the SSH host keys are removed. Otherwise all VMs from the image would have the same host keys, and the build key would end up everywhere.

Packer fetches the plugin itself:

packer init .

Expected (shortened):

Installed plugin github.com/hashicorp/qemu v1.1.8 in "/home/ubuntu/.config/packer/plugins/…"

Save your progress? Sign up for free

Drill 4: Build

The base image is the Alpine from the public Marketplace. OpenNebula provides the address and checksum:

onemarketapp show "Alpine Linux 3.20" | grep -E '^(SOURCE|MD5)'

Expected:

SOURCE         : https://marketplace.opennebula.io/appliance/d74a5f80-20bd-013d-0e49-7875a4a4f528/download/0
MD5            : 07751da61ad7f0d6a3a3faeed06a4994

Reading the datastore directly would also work, but ubuntu is not allowed to: /var/lib/one belongs to oneadmin. So into variables with them:

URL=$(onemarketapp show "Alpine Linux 3.20" | awk '/^SOURCE/{print $3}')
MD5=$(onemarketapp show "Alpine Linux 3.20" | awk '/^MD5/{print $3}')
packer validate -var "basis_url=$URL" -var "basis_md5=$MD5" .

Expected:

The configuration is valid.

And go:

time packer build -color=false -var "basis_url=$URL" -var "basis_md5=$MD5" .
  • -var name=wert sets a variable from the template.
  • -color=false leaves out the color codes, which reads better in logs.

Expected (shortened):

==> qemu.notes: Retrieving ISO
==> qemu.notes: Creating CD disk...
==> qemu.notes: Starting VM, booting disk image
==> qemu.notes: Waiting for SSH to become available...
==> qemu.notes: Connected to SSH!
==> qemu.notes: Provisioning with shell script: /tmp/packer-shell3287397911
==> qemu.notes:  * service cgroups added to runlevel default
==> qemu.notes: REPOSITORY                        TAG         IMAGE ID      CREATED      SIZE
==> qemu.notes: ghcr.io/thomaszachmann/notes-api  0.7.1       eb5553ddb0cf  3 weeks ago  11.9 MB
==> qemu.notes: /dev/vda        474M  214M  234M  48% /
==> qemu.notes: Gracefully halting virtual machine...
==> qemu.notes: Converting hard drive...
Build 'qemu.notes' finished after 1 minute 6 seconds.
--> qemu.notes: VM files in directory: ausgabe

real    1m9.171s

The same numbers as on Day 10: 11.9 MB for notes-api, 214 MB used. Only this time, nobody typed anything by hand. The result:

qemu-img info ausgabe/notes-basis.qcow2 | grep -E 'format|virtual|disk size'

Expected:

file format: qcow2
virtual size: 512 MiB (536870912 bytes)
disk size: 231 MiB

By the way, a second run fails immediately:

* Output directory 'ausgabe' already exists. It must not exist.

Packer does not overwrite a finished result. Before the next build, you move or delete ausgabe.

Save your progress? Sign up for free

Drill 5: Register as an image

The obvious way:

oneimage create -d default --name notes-packer --type OS --format qcow2 \
  --path ~/one-lab/tag16/ausgabe/notes-basis.qcow2

Expected:

[one.image.allocate] Cannot parse image SIZE: cannot access '/home/ubuntu/one-lab/tag16/ausgabe/notes-basis.qcow2' (Permission denied)

OpenNebula does the copying as oneadmin, and oneadmin may not enter your home directory. /var/tmp is readable for both:

cp ausgabe/notes-basis.qcow2 /var/tmp/
oneimage create -d default --name notes-packer --type OS --format qcow2 \
  --path /var/tmp/notes-basis.qcow2
  • -d default: the image datastore.
  • --type OS: a system disk; --format qcow2: the format of the file.
  • --path: where OpenNebula copies the file from. A URL would also work.

Expected:

ID: 11

When oneimage list shows rdy for notes-packer, the copy is in the datastore, and the file in /var/tmp can go:

oneimage list | grep -E '^ +ID |notes-packer'
rm /var/tmp/notes-basis.qcow2

Expected:

  ID USER     GROUP    NAME            DATASTORE     SIZE TYPE PER STAT RVMS
  11 oneadmin oneadmin notes-packer    default       512M OS    No rdy     0

Save your progress? Sign up for free

Drill 6: Your own marketplace

A marketplace of type http needs a directory where OpenNebula puts the images, and a web server that delivers this directory. OpenNebula does not set up the web server itself. The documentation recommends Apache or NGINX. Sunstone already occupies port 80 here; for the lab, Python’s web server on port 8000 is enough, as a systemd service:

sudo install -d -o oneadmin -g oneadmin -m 755 /var/local/market-http
sudo tee /etc/systemd/system/one-market-http.service >/dev/null <<'EOF'
[Unit]
Description=Web-Server für den Marketplace lokal
After=network-online.target

[Service]
User=oneadmin
ExecStart=/usr/bin/python3 -m http.server 8000 --directory /var/local/market-http
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable --now one-market-http
curl -sI http://127.0.0.1:8000/ | head -1
  • install -d -o oneadmin -g oneadmin -m 755: create the directory and set owner and permissions in one step. oneadmin must write, everyone may read.
  • User=oneadmin: the service does not run as root.
  • python3 -m http.server 8000 --directory …: a simple web server that only delivers files.
  • enable --now: start at boot and start right away.

Expected:

HTTP/1.0 200 OK

Now the marketplace itself. BASE_URL is the address under which others fetch the files, that is, the address of the VM one in your network (hostname -I, the first one):

cat > lokal.market <<'EOF'
NAME = "lokal"
MARKET_MAD = "http"
BASE_URL = "http://172.16.0.61:8000"
PUBLIC_DIR = "/var/local/market-http"
EOF
onemarket create lokal.market
onemarket list
  • MARKET_MAD = "http": the driver.
  • PUBLIC_DIR: the directory the web server delivers from.
  • With BRIDGE_LIST, the directory could be on another server. Without it, it is on the front-end.

Expected:

ID: 101
  ID NAME                  SIZE AVAIL        APPS MAD     ZONE STAT
 101 lokal                   0M -               0 http       0 on
   1 Linux Container         0M -               0 linuxco    0 off
   0 OpenNebula Publ         0M -             135 one        0 on

Save your progress? Sign up for free

Drill 7: Publish

onemarketapp create turns an image into an app. --dry shows the template without creating anything:

onemarketapp create --image notes-packer --marketplace lokal --name notes-basis --dry

Expected:

NAME="notes-basis"
ORIGIN_ID=11
TYPE=image

An app without a version and description helps nobody. So the template becomes a file and gets three more lines:

onemarketapp create --image notes-packer --marketplace lokal --name notes-basis --dry > notes-app.tpl
cat >> notes-app.tpl <<'EOF'
VERSION = "0.7.1-1"
DESCRIPTION = "Alpine 3.20 mit Podman und notes-api 0.7.1, gebaut mit Packer"
PUBLISHER = "IT-Trainingslager"
EOF
onemarketapp create notes-app.tpl --marketplace lokal

0.7.1-1 means: notes-api 0.7.1, first build. A new build with the same programs becomes 0.7.1-2.

Expected:

ID: 137

After half a minute:

onemarketapp list | grep -E '^ +ID |lokal'
ls -l /var/local/market-http
onemarketapp show notes-basis | grep -E '^(SOURCE|MD5|VERSION)'

Expected:

  ID NAME                    VERSION  SIZE    ARCH HYPERVISOR STAT TYPE  REGTIME MARKET     ZONE
 137 notes-basis             0.7.1-1  512M                     rdy  img 11/27/26 lokal         0
total 236356
-rw-r--r-- 1 oneadmin oneadmin 242024448 Nov 27 18:05 3bdb5c02f6d9d935e0ac20bf5cb8b9be
SOURCE         : http://172.16.0.61:8000/3bdb5c02f6d9d935e0ac20bf5cb8b9be
MD5            : 6a3652d022396a14509415ae85762e56
VERSION        : 0.7.1-1

The app is a file with a random name in the web directory, plus an entry in the OpenNebula database with address and checksum.

Save your progress? Sign up for free

Drill 8: Fetch from the marketplace

Now the user’s side, just like on Day 15 with the router:

onemarketapp export notes-basis notes-vom-markt -d default

Expected:

IMAGE
    ID: 12

This time no template is created; the app contains only the image. You start a VM from it with the alpine template and a different disk:

onetemplate instantiate alpine --name m16 --user-inputs GRUSS=m16 --disk notes-vom-markt

--disk replaces the template’s disks, just as --nic replaces the networks on Day 5.

After a minute:

onevm show m16 | sed -n '/^VM DISKS/,/^$/p'
IP=$(onevm show m16 | grep -o 'ETH0_IP="[0-9.]*' | cut -d'"' -f2)
ssh -o StrictHostKeyChecking=accept-new root@$IP 'hostname; podman images; rc-status | grep cgroups'

Expected:

VM DISKS
 ID DATASTORE  TARGET IMAGE                               SIZE      TYPE SAVE
  0 default    sda    notes-vom-markt                     -/512M    file   NO
  1 -          sdb    CONTEXT                             -/-       -       -

m16
REPOSITORY                        TAG         IMAGE ID      CREATED      SIZE
ghcr.io/thomaszachmann/notes-api  0.7.1       eb5553ddb0cf  3 weeks ago  11.9 MB
 cgroups                                                           [  started  ]
  • The hostname is m16, not bau: one-context set everything anew with the new context.
  • The login works with your key, although the build key was removed. one-context adds SSH_PUBLIC_KEY at every start.
  • Alpine regenerated the SSH host keys at first start.

If m16 sits in pend, c15 from Day 15 is still running and occupying the CPU.

Save your progress? Sign up for free

Drill 9: Fault exercise – the marketplace does not answer

A colleague reboots the server, and the web service does not come up. Simulated here:

sudo systemctl stop one-market-http
onemarketapp export notes-basis kaputt-test -d default

After 20 seconds:

oneimage list | grep -E '^ +ID |kaputt'

Expected:

  ID USER     GROUP    NAME            DATASTORE     SIZE TYPE PER STAT RVMS
  13 oneadmin oneadmin kaputt-test     default       512M OS    No err     0

The export itself did not complain, but the image is in err. Find the cause.

The solution is in the image:

oneimage show kaputt-test | grep ERROR | cut -c1-140

Expected:

ERROR="Fri Nov 27 18:08:11 2026 : Error copying image in the datastore: curl: (7) Failed to connect to 172.16.0.61 port 8000 after 0

OpenNebula fetches apps from http marketplaces with curl from the BASE_URL. No web server, no download. Repair it and remove the broken image:

sudo systemctl start one-market-http
oneimage delete kaputt-test

Save your progress? Sign up for free

Checkpoint

onemarketapp list | grep -c lokal

Expected: 1.

systemctl is-enabled one-market-http

Expected: enabled.

diff ~/one-lab/tag16/notes-basis.pkr.hcl ~/one-lab/code/loesung/tag16/notes-basis.pkr.hcl

Expected: no output.

Challenge

Prove that the file in the marketplace is exactly what Packer built, and that someone without OpenNebula access can also download it unchanged.

Solution

Three checksums: that of the Packer output, the one stored in the app, and that of a fresh copy over HTTP:

md5sum ausgabe/notes-basis.qcow2
onemarketapp show notes-basis | grep '^MD5'
curl -s http://172.16.0.61:8000/$(onemarketapp show notes-basis | awk -F/ '/^SOURCE/{print $NF}') | md5sum
  • awk -F/ '…{print $NF}': splits the line at / and takes the last field, the file name.

Expected:

6a3652d022396a14509415ae85762e56  ausgabe/notes-basis.qcow2
MD5            : 6a3652d022396a14509415ae85762e56
6a3652d022396a14509415ae85762e56  -

The same sum three times. The file can be fetched without logging in: anyone who knows the address can download it. That is fine for the lab; in production, the web server belongs behind TLS and access control.

Save your progress? Sign up for free

Clean up

The competition on Day 17 expects the host as it was after Day 14. The VM, the router and the gateway and DNS entry from Day 15 must go. Image, marketplace and web service may stay:

onevm terminate m16
onevrouter delete gw
cat > ../tag15/intern-ohne-gw.net <<'EOF'
GATEWAY = ""
DNS = ""
EOF
onevnet update intern ../tag15/intern-ohne-gw.net --append

onevrouter delete also deletes the router VM. After half a minute:

onehost list

Expected:

  ID NAME            CLUSTER    TVM      ALLOCATED_CPU      ALLOCATED_MEM STAT
   0 localhost       default      2    100 / 200 (50%)  896M / 2.3G (37%) on

Two VMs, the two of the OneFlow service, exactly as after Day 14.

Enterprise Note

  • Build in the pipeline: The Packer template belongs in the repository; the build runs in CI on a runner with KVM. Every run produces a new version; old ones stay in the marketplace until nobody needs them anymore.
  • Check the base: iso_checksum is mandatory. If you enter "none", you build on whatever the server happens to deliver.
  • A proper web server: For production, use Apache or NGINX with TLS instead of python3 -m http.server. OpenNebula sets up neither a web server nor access control.
  • Other clouds: The app is a file behind a URL. Another OpenNebula installation can fetch it as an image with oneimage create --path <URL>. Whether it sees the marketplace as a catalog is not described in the documentation for the http type. Only the path via the URL within the same cloud is tested here.
  • Deleting: onemarketapp delete also removes the file from PUBLIC_DIR.

Contents

More