Skip to content

This is the multi-page printable view of this section.

Return to the regular view of this page

Reference

Exact syntax, options, defaults, output formats, and file layouts for every part of Barn.

Look things up here once you know what you want to do. The Guides explain how to do it.

  • Command Reference — Every Linux and macOS command with its options, defaults, examples, and the version that added it.
  • Linux Configuration — The inventory format, every vm_* variable and default, data disks, shares, and drift rules.
  • CLI Contracts — Output modes, the JSON envelope, lifecycle results, and exit codes shared by all commands.
  • Mac Runtime Reference — The barn mac machine model, networks, JSON schemas, failure reasons, and files on disk.
  • Linux Images — The image catalog, aliases, signature checks, local imports, and cache pruning.
  • Image Pipeline — Contributor tooling for validating and normalizing new qcow2 images.

Barn’s public interface is the barn command; Go packages under internal/ may change between releases. barn COMMAND --help shows the options of the build you have installed.

1 - Command Reference

Every Barn command with syntax, all local options, defaults, examples, and version availability.

Find a command below for its arguments, complete local option table, examples, and effects. This reference follows the command-index and command-family organization of PIG. Barn’s CLI contracts describe structured output and exit codes; Configuration defines inventory fields.

Version baseline

This reference covers the Barn 1.5.0. Its command names and flags remain compatible with 1.4.0. Release notes

LabelAvailabilityBehavior
1.1.0Options available across 1.1.0–1.5.01.1.0 used 2 vCPUs / 4 GiB by default and accepted CPU/memory resize through the inventory
1.2.0Added in 1.2.0Resource flags and environment overrides, vm_scale, root-disk growth, lifecycle --parallel, vm_hosts, and hosts install -f; defaults are 1 vCPU / 2 GiB
1.3.0Added in 1.3.0barn time manual, startup, and scheduled guest clock synchronization; shorthand family and architecture-suffixed image aliases (el10a, d13x); embedded catalog 2026112101; macOS 27.2.1 base and macOS network setup/repair fix
1.4.0Added in 1.4.0barn image update, catalog signing key rotation, Debian 13.8 on both architectures, and immediate power-off during Linux purge
1.5.0Changed in 1.5.0New labs use d13. repo build can infer image metadata from filenames, and official catalogs use catalog.json.sig.

To preserve the 1.1.0 resource defaults when upgrading from 1.1.0, set vm_cpu: 2 and vm_mem: 4GiB explicitly and inspect barn plan. Existing applied VMs keep their resources until a resource-changing operation is requested. Use barn version and barn COMMAND --help to check an installed build. See the release notes and release acceptance.

Command index

TaskCommands and detailed reference
Preparesetup, init, validate, doctor
Plan and createplan, up
Start and stopstart, stop, restart, reload
Change and inspectresize, recreate, status
Deletedestroy, purge
Access Linux guestsssh, exec, logs, provision, ssh-config
Publish host nameshosts install, hosts uninstall
Synchronize clockstime status, sync, auto
Refresh catalogupdate, image sync, image reset
Manage Linux imagesimage list, info, pull, update (1.4.0), import, prune
Maintain a repositoryrepo scan, build, verify
Host networknetwork status, install, uninstall
Native macOS VMsmac ls, up, start, stop, restart, configure, recreate, destroy
Mac accessmac open, ssh, exec, password, ssh-config, logs
Mac preparationmac setup, doctor, image ls, image update, image prune
CLI utilitiesversion, completion, help

Global options

barn [--json|--yaml] [-v|--verbose] COMMAND [arguments] [local options]
OptionMeaning
-h, --helpHuman-readable help for the selected command; exits 0
--jsonStructured JSON on stdout; progress and diagnostics stay on stderr
--yamlStructured YAML on stdout; mutually exclusive with --json
-v, --verboseBounded diagnostics on stderr
--versionRoot-command shortcut to display build identity; use barn version --json for a structured report

Global output options can appear before or after a subcommand, but must precede the remote-command -- separator used by ssh and exec. -f, -I, -A, -p, and --yes are local options: consult the selected command’s table. -f means follow for logs; -n means line count for mac logs. Long boolean options accept =true or =false.

BARN_OUTPUT and BARN_VERBOSE set presentation defaults. BARN_HOME selects private state (default ~/.barn); use an absolute path when changing directories. Linux and Mac machines share that data root but have independent lifecycles. See environment variables and exit codes.

barn and help

barn
barn --help
barn help resize
barn image pull --help
barn --json

With no arguments, text mode prints complete help and exits 0; JSON/YAML mode returns suggested actions[]. Explicit help always prints human-readable text. Groups image, repo, network, hosts, time, time auto, and mac image require a subcommand and exit 2 without one. The mac group is the exception: it defaults to mac ls. It is hidden from root help on Linux and Intel Macs, while explicit Mac help remains available.

Short aliases are scoped to their parent. barn im ls is barn image list; barn mac st is barn mac ls. The per-command pages list each alias. There is no rm alias for purge.

1.1 - Preparation and Utilities

Prepare the host with barn setup, write and validate inventories, diagnose the host, and print the version or completion scripts.

barn setup prepares a host to run Linux VMs: it installs QEMU and UEFI firmware, creates the fixed-IP network the nodes share, and writes an inventory if you have none. This page also covers init, validate, doctor, version, and completion. Every command accepts the global options; Available in shows availability from the 1.1.0 baseline onward (version baseline).

barn setup

barn setup [meta|dual|trio|full] [flags]

On a terminal, the first barn up runs this preparation itself and asks once. Run barn setup directly to preview the changes, to prepare a host from a script or CI job, or to get ready before the first up. It creates no VMs and downloads no base images; barn up does that.

barn setup --dry-run              # print the plan, change nothing
barn setup                        # print the plan, ask, then apply
barn setup full -I el9 --yes      # generate a four-node EL9 lab without asking
barn setup -f pigsty.yml --yes    # prepare the host for an existing inventory
barn up

Aliases: s.

What setup changes

Setup skips steps that are already satisfied and prints the whole plan before the first change:

StepWhat it doesRoot
dependenciesInstalls missing QEMU, qemu-img, UEFI firmware, and OpenSSH: brew install qemu on macOS (Homebrew required), apt-get or dnf on LinuxLinux only
capabilitiesRuns the host checks of barn doctorNo
networkInstalls or repairs the fixed-IP network: socket_vmnet as a root service under /opt/barn on macOS, the barn0 bridge through NetworkManager or systemd-networkd on LinuxYes
verifyRe-checks the installed networkNo
configWrites the generated inventory, or uses the existing oneNo

The network step needs root because it changes host networking; in return, QEMU itself runs as you. /etc/hosts is not part of setup: the first barn hosts install installs its root-owned helper, which is why setup reports the hosts-helper step as on-demand.

On macOS, socket_vmnet comes from the first of BARN_VMNET_ARCHIVE, Barn’s cache, Homebrew, or a SHA-256-pinned download from the selected repository or github.com/lima-vm; --mirror and --repo change the download source. Behind a proxy, setup passes HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, and NO_PROXY (either case) through sudo to apt-get and dnf. On Linux, setup installs only the host-architecture emulator; for foreign-architecture guests, install the other qemu-system-* package and its UEFI firmware yourself.

sudo and confirmation

Run setup as your normal user. It asks for your password at most once, at the first root step, after printing why; Homebrew runs as you. On a terminal, setup shows the plan and asks Continue with this setup? [Y/n], unless nothing needs to change.

  • --yes skips that question and is required without a terminal, where setup otherwise exits 2. It cannot answer sudo: without a terminal, sudo must work without a password, or setup exits 3 with reason sudo_unavailable (troubleshooting).
  • --dry-run prints the plan and changes nothing; its next: line is the command that applies it. It cannot be combined with --yes.
  • barn --json setup reports ready, blocked, steps[], dependencies (with missing[] and the exact package-manager commands[]), network, and next/next_argv.

Which inventory it prepares

With no template and no -f, setup reuses the first discovered inventory or writes the meta template to ./barn.yml. A template (meta, dual, trio, or full, with 1 to 4 nodes) generates that lab; -f prepares an existing file and cannot be combined with a template. -c and the specification flags shape generated templates only: setup rejects them for an existing inventory and ignores the matching BARN_* variables when it reuses one.

If the default subnet is taken and the inventory is a fresh, unedited template, setup picks a free private /24 and keeps the original as barn.yml.before-network-change. An inventory you wrote or edited keeps its subnet, and a conflict stops setup.

Options

OptionMeaning / defaultAvailable in
-A, --arch stringoverride deployment vm_arch: native, amd64, or arm64; environment overrides require 1.2.01.1.0
-c, --cidr stringgenerated template network as a canonical RFC1918 IPv4 /241.1.0
-C, --cpu stringBase vCPUs before scale, integer 1–256; effective CPU count is also limited to 256; overrides BARN_CPU1.2.0
-D, --disk stringAbsolute root capacity, at least the base virtual size; bare integer means GiB; overrides BARN_DISK1.2.0
-d, --dry-runshow the resolved setup plan without changing anything1.1.0
-f, --file stringInventory to prepare; mutually exclusive with a template argument1.1.0
-I, --image stringoverride vm_image/vm_version for selected nodes; environment overrides require 1.2.01.1.0
-M, --mem stringBase memory before scale, minimum 512 MiB; bare integer means MiB; overrides BARN_MEM1.2.0
--mirroruse the China official repository at repo.pigsty.cc; overridden by --repo1.1.0
-m, --mode stringmacOS fixed-IP network backend: host or shared (default “host”)1.1.0
-r, --repo stringimage repository URL or local directory, also used for socket_vmnet; overrides --mirror and $BARN_REPO1.1.0
-S, --scale stringInteger 1–256 multiplying base CPU and memory only; disk does not scale; overrides BARN_SCALE1.2.0
-y, --yesaccept the one-time setup plan (required without a terminal)1.1.0

barn init

barn init [meta|dual|trio|full] [flags]

Write an editable, Pigsty-compatible inventory without touching the host. The default is the one-node meta template in ./barn.yml, with the control node at .10; dual, trio, and full add .11, .12, and .13. Existing files are kept unless you pass --force, and -o - prints to stdout.

In 1.5.0, all four templates write vm_image: d13 and vm_arch: native by default. On Barn 1.4.0, pass -I d13 when generating a template to select Debian 13.

Generated nodes get 1 vCPU, 2 GiB of memory, a 64 GiB root disk, and a 128 GiB /data disk, written out as all six specification fields including vm_scale (specification overrides). Barn 1.1.0 templates used 2 vCPUs and 4 GiB (upgrade notes).

OptionMeaning / defaultAvailable in
-A, --arch stringoverride deployment vm_arch: native, amd64, or arm64; environment overrides require 1.2.01.1.0
-c, --cidr stringrebase the generated template to a canonical RFC1918 IPv4 /241.1.0
-C, --cpu stringBase vCPUs before scale, integer 1–256; effective CPU count is also limited to 256; overrides BARN_CPU1.2.0
-D, --disk stringAbsolute root capacity, at least the base virtual size; bare integer means GiB; overrides BARN_DISK1.2.0
--forceOverwrite the destination inventory; default preserves existing files1.1.0
-I, --image stringoverride vm_image/vm_version for selected nodes; environment overrides require 1.2.01.1.0
-M, --mem stringBase memory before scale, minimum 512 MiB; bare integer means MiB; overrides BARN_MEM1.2.0
-o, --output stringwrite to this path instead of ./barn.yml; ‘-’ writes to stdout1.1.0
-S, --scale stringInteger 1–256 multiplying base CPU and memory only; disk does not scale; overrides BARN_SCALE1.2.0
barn init -I d13
barn init full -I d13 -A amd64 -o lab.yml
barn init dual -I d13 -c 10.20.30.0/24 -o -

barn validate

barn validate [flags]

Check an inventory before up. validate checks every field Barn reads and prints the resolved nodes, or the full resolved specification with --json. It requires an inventory file, either -f or the first of barn.yml, barn.yaml, pigsty.yml, and pigsty.yaml in the current directory. In 1.5.0, a readable deployment supplies the same image default as plan. It takes no node names, and overrides apply to this check only. To compare an inventory with the running deployment, use barn plan.

Aliases: v.

OptionMeaning / defaultAvailable in
-A, --arch stringoverride deployment vm_arch: native, amd64, or arm64; environment overrides require 1.2.01.1.0
-C, --cpu stringBase vCPUs before scale, integer 1–256; effective CPU count is also limited to 256; overrides BARN_CPU1.2.0
-D, --disk stringAbsolute root capacity, at least the base virtual size; bare integer means GiB; overrides BARN_DISK1.2.0
-f, --file stringInventory to validate; otherwise use local discovery, with no applied-state fallback1.1.0
-I, --image stringoverride vm_image/vm_version for selected nodes; environment overrides require 1.2.01.1.0
-M, --mem stringBase memory before scale, minimum 512 MiB; bare integer means MiB; overrides BARN_MEM1.2.0
-r, --repo stringimage repository whose catalog checks the images; overrides $BARN_REPO1.1.0
-S, --scale stringInteger 1–256 multiplying base CPU and memory only; disk does not scale; overrides BARN_SCALE1.2.0
barn validate -f lab.yml
barn --json validate -f lab.yml -I d13 -A arm64

barn doctor

barn doctor [flags]

Check whether this host can run Linux VMs: QEMU, native acceleration, firmware, OpenSSH, a short accelerated boot, and host networking. A missing compute capability exits 3 and prints a fix: line for each problem. A missing network is only a warning, because setup installs it. For network detail, run barn network status; for macOS guests, run barn mac doctor.

Aliases: dt. No options of its own.

barn doctor
barn --json doctor
barn doctor --verbose

barn version

barn version [flags]

Print the version, source commit, build time, OS, and architecture to include in a bug report; barn --version prints the same line. --json returns name, version, commit, built, os, and arch. Source builds without a release stamp report dev.

Aliases: ver. No options of its own.

barn version
barn --json version

barn completion

barn completion [bash|zsh|fish|powershell] [flags]

Print one shell’s completion script to stdout, then install it as shown below. It completes commands, flags, templates, image aliases, and, on a best-effort basis, node names. Regenerate it after upgrading Barn. Use text mode: with --json or BARN_OUTPUT=json, the script arrives wrapped in a {shell, script} object.

No options of its own.

source <(barn completion bash)
barn completion zsh > "${fpath[1]}/_barn"
barn completion fish > ~/.config/fish/completions/barn.fish
barn completion powershell

Implementation

See cmd/barn/command_setup.go for the CLI and internal/setup/ for host preparation. cmd/barn/command_misc.go and cmd/barn/command_root.go define the diagnostic and root commands.

1.2 - Linux Lifecycle

Plan, create, start, resize, inspect, and explicitly remove Linux virtual machines.

These commands take a Linux lab from an inventory to running VMs, change it, and tear it down. The Available in column of each option table names the release that introduced the option (version baseline).

Choosing a command

You want toRunWhat happens to disks
See what a change would doplanNothing; read-only
Create the lab, or bring it back after a stop or rebootupKept
Boot, shut down, or reboot existing nodes as they arestart, stop, restartKept
Restart nodes and re-apply the inventory (stop, then up)reloadKept; nodes new in the inventory are created
Change CPU or memory, or grow the root diskresizeKept
Change image, architecture, data disks, network, or sharesrecreateRoot and non-persistent data disks replaced
Remove some nodes, or the whole lab but keep persistent datadestroyDeleted, except persistent data disks
Start over from nothingpurgeEverything deleted, persistent data disks included

The full retention rules are in What survives each operation.

Selecting nodes

Node arguments are resolved node names such as meta and node-1; omit them to select every node the command covers. IP addresses, groups, and vm_alias are not selectors.

plan, up, reload, resize, and recreate read the desired inventory from -f, then the current directory’s inventory, then applied state. The other lifecycle commands work from applied state only, so they run from any directory that uses the same BARN_HOME.

All commands accept the global options. Specification overrides (-I, -A, -C, -M, -S, -D) and their environment variables are defined in Configuration. --parallel appears only in the tables that list it; plan, resize, and status do not accept it. Structured results and exit codes are in CLI contracts.

barn plan

Run plan before up, resize, or recreate to see what they would change. It changes no VM and downloads nothing.

barn plan [node...] [flags]

The plan compares the effective desired inventory with applied state and reports exact images, resources, per-disk actions, and the nodes that need creation, resize, recreation, start, or explicit removal. Catalog images need only local metadata; inspecting a named local image also needs qemu-img.

Exit 0 means a plan was produced, including a plan blocked by nodes missing from the inventory, so automation must inspect action, blocked, and the change arrays (planning output). Explicit selectors keep the applied definitions of unselected peers.

Aliases: pl.

OptionMeaning / defaultAvailable in
-A, --arch stringoverride deployment vm_arch: native, amd64, or arm64; environment overrides require 1.2.01.1.0
-C, --cpu stringBase vCPUs before scale, integer 1–256; effective CPU count is also limited to 256; overrides BARN_CPU1.2.0
-D, --disk stringAbsolute root capacity, at least the base virtual size; bare integer means GiB; overrides BARN_DISK1.2.0
-f, --file stringdesired inventory; defaults to the discovered inventory, then the applied state1.1.0
-I, --image stringoverride vm_image/vm_version for selected nodes; environment overrides require 1.2.01.1.0
-M, --mem stringBase memory before scale, minimum 512 MiB; bare integer means MiB; overrides BARN_MEM1.2.0
-r, --repo stringimage repository URL or directory; overrides $BARN_REPO1.1.0
-S, --scale stringInteger 1–256 multiplying base CPU and memory only; disk does not scale; overrides BARN_SCALE1.2.0
barn plan
barn plan -f pigsty.yml meta
barn --json plan -I d13 -A amd64

barn up

up is the everyday command: it creates missing nodes, starts stopped ones, and finishes any guest setup left undone, while healthy running VMs keep running.

barn up [node...] [flags]

Unless --no-wait is set, up verifies each guest’s readiness marker over management SSH, corrects guest clock offsets greater than two seconds against the host, and refreshes host SSH aliases and the guests’ host and control-node entries. Non-fatal guest setup or clock-sync problems appear in warnings; ready nodes still succeed.

On an interactive first run, up prepares missing host dependencies and generates meta when no inventory or applied deployment exists. Scripts run setup --yes first.

up never applies a changed node definition: use resize for CPU, memory, or root growth and recreate for anything else. Nodes removed from the inventory stay until you destroy them. --rollback removes only safe, uncommitted artifacts left by preparation failures in this run.

OptionMeaning / defaultAvailable in
-A, --arch stringoverride deployment vm_arch: native, amd64, or arm64; environment overrides require 1.2.01.1.0
-C, --cpu stringBase vCPUs before scale, integer 1–256; effective CPU count is also limited to 256; overrides BARN_CPU1.2.0
-D, --disk stringAbsolute root capacity, at least the base virtual size; bare integer means GiB; overrides BARN_DISK1.2.0
-f, --file stringdesired inventory; defaults to the discovered inventory, then the applied state1.1.0
-I, --image stringoverride vm_image/vm_version for selected nodes; environment overrides require 1.2.01.1.0
-M, --mem stringBase memory before scale, minimum 512 MiB; bare integer means MiB; overrides BARN_MEM1.2.0
--mirroruse the China official repository at repo.pigsty.cc; overridden by --repo1.1.0
-n, --no-waitreturn once QEMU is running, without waiting for the guest to boot1.1.0
-p, --parallel intNode concurrency: omitted = max(1, logical CPUs - 2); 0 = all selected nodes; positive = limit1.2.0
-r, --repo stringimage repository URL or directory; overrides --mirror and $BARN_REPO1.1.0
--rollbackremove safe artifacts from nodes that fail to prepare1.1.0
-S, --scale stringInteger 1–256 multiplying base CPU and memory only; disk does not scale; overrides BARN_SCALE1.2.0
barn up
barn up -f pigsty.yml meta
barn up --mirror --rollback
barn up meta --no-wait

barn start

Use start to boot nodes that already exist, from any directory: it reads applied state, not the inventory, and never creates nodes.

barn start [node...] [flags]

Unless --no-wait is set, start waits for SSH and corrects guest clock offsets greater than two seconds. It refreshes SSH access; to retry unfinished guest setup on a VM that is already running, use up. An unavailable host share fails only its node, and independent nodes continue.

OptionMeaning / defaultAvailable in
-n, --no-waitreturn once QEMU is running, without waiting for the guest to boot1.1.0
-p, --parallel intNode concurrency: omitted = max(1, logical CPUs - 2); 0 = all selected nodes; positive = limit1.2.0
barn start
barn start meta --no-wait

barn stop

Use stop to shut nodes down and free host CPU and memory; root disks, data disks, keys, and deployment state all stay.

barn stop [node...] [flags]

stop identifies each VM by its recorded process identity. With no names it stops the whole Linux deployment; macOS VMs and the host network keep running.

OptionMeaning / defaultAvailable in
-p, --parallel intNode concurrency: omitted = max(1, logical CPUs - 2); 0 = all selected nodes; positive = limit1.2.0
barn stop meta
barn stop

barn restart

Use restart to reboot nodes exactly as they were created. Inventory edits are ignored; use reload to pick them up.

barn restart [node...] [flags]

restart stops and starts existing nodes from applied state, then waits for SSH and checks guest clocks unless --no-wait is set.

OptionMeaning / defaultAvailable in
-n, --no-waitreturn once QEMU is running, without waiting for the guest to boot1.1.0
-p, --parallel intNode concurrency: omitted = max(1, logical CPUs - 2); 0 = all selected nodes; positive = limit1.2.0
barn restart
barn restart meta --no-wait

barn reload

Use reload to restart nodes after editing the inventory: Barn re-reads it, stops the selected nodes, and runs up, so nodes you added are created in the same step.

barn reload [node...] [flags]

reload validates the desired specification and startup dependencies before it stops anything. Changes that need resize or recreate, and applied nodes missing from the inventory, fail this preflight while every VM keeps running. To reboot with the recorded configuration only, use restart.

OptionMeaning / defaultAvailable in
-A, --arch stringoverride deployment vm_arch: native, amd64, or arm64; environment overrides require 1.2.01.1.0
-C, --cpu stringBase vCPUs before scale, integer 1–256; effective CPU count is also limited to 256; overrides BARN_CPU1.2.0
-D, --disk stringAbsolute root capacity, at least the base virtual size; bare integer means GiB; overrides BARN_DISK1.2.0
-f, --file stringdesired inventory; defaults to the discovered inventory, then the applied state1.1.0
-I, --image stringoverride vm_image/vm_version for selected nodes; environment overrides require 1.2.01.1.0
-M, --mem stringBase memory before scale, minimum 512 MiB; bare integer means MiB; overrides BARN_MEM1.2.0
--mirroruse the China official repository at repo.pigsty.cc; overridden by --repo1.1.0
-n, --no-waitreturn once QEMU is running, without waiting for the guest to boot1.1.0
-p, --parallel intNode concurrency: omitted = max(1, logical CPUs - 2); 0 = all selected nodes; positive = limit1.2.0
-r, --repo stringimage repository URL or directory; overrides --mirror and $BARN_REPO1.1.0
--rollbackremove safe artifacts from nodes that fail to prepare1.1.0
-S, --scale stringInteger 1–256 multiplying base CPU and memory only; disk does not scale; overrides BARN_SCALE1.2.0
barn reload -f pigsty.yml
barn reload meta --mirror

barn resize

Use resize to change CPU or memory, or grow the root disk, without losing anything on the VM: its identity, disks, and SSH keys stay.

barn resize [node...] [flags]

Desired resources come from the inventory, environment variables, or CLI overrides; CLI overrides do not rewrite the inventory. Supported CPU and memory increases are hot-plugged; decreases and changes the VM cannot take live fall back to a stop and start. Image, architecture, data-disk, network, and share changes need recreate; new nodes need up, and removed nodes need destroy.

-D 128GiB grows the existing root to 128 GiB. Barn stops QEMU, expands the image, boots the guest to grow and verify its last plain ext4/XFS root partition, and returns a VM that was stopped to stopped. The target can only grow the disk and must align to 512 bytes. After an interruption, repeat the same target. Shrinking, LVM, encrypted roots, and roots that are not the last partition are unsupported; see root growth and recovery.

OptionMeaning / defaultAvailable in
-A, --arch stringoverride deployment vm_arch: native, amd64, or arm64; environment overrides require 1.2.01.1.0
-C, --cpu stringBase vCPUs before scale, integer 1–256; effective CPU count is also limited to 256; overrides BARN_CPU1.2.0
-D, --disk stringAbsolute root capacity, at least the base virtual size; bare integer means GiB; overrides BARN_DISK1.2.0
-f, --file stringdesired inventory; defaults to the discovered inventory, then the applied state1.1.0
-I, --image stringoverride vm_image/vm_version for selected nodes; environment overrides require 1.2.01.1.0
-M, --mem stringBase memory before scale, minimum 512 MiB; bare integer means MiB; overrides BARN_MEM1.2.0
-S, --scale stringInteger 1–256 multiplying base CPU and memory only; disk does not scale; overrides BARN_SCALE1.2.0
barn plan -f pigsty.yml meta
barn resize -f pigsty.yml meta
barn --json status meta

barn recreate

Use recreate for changes resize cannot make, such as a new image, architecture, data-disk layout, network, or shares: Barn rebuilds the selected VMs from the desired inventory.

Warning

recreate deletes the selected nodes’ root disks and non-persistent data disks, and everything stored on them. Only compatible persistent data disks are reattached. Run barn plan first to see which nodes it replaces; What survives each operation has the full rules.

barn recreate [node...] [flags]

On a terminal you type recreate to confirm; scripts pass --yes or --force (there is no -y).

Without selectors recreate applies the whole inventory, and fails before stopping any VM if the inventory omits an applied node: destroy that node explicitly or add it back. Selected recreation keeps unselected peers as they are. A successful recreate also refreshes SSH access.

Aliases: rc.

OptionMeaning / defaultAvailable in
-A, --arch stringoverride deployment vm_arch: native, amd64, or arm64; environment overrides require 1.2.01.1.0
-C, --cpu stringBase vCPUs before scale, integer 1–256; effective CPU count is also limited to 256; overrides BARN_CPU1.2.0
-D, --disk stringAbsolute root capacity, at least the base virtual size; bare integer means GiB; overrides BARN_DISK1.2.0
-f, --file stringdesired inventory; defaults to the discovered inventory, then the applied state1.1.0
--forcerecreate without the interactive confirmation (required without a terminal)1.1.0
-I, --image stringoverride vm_image/vm_version for selected nodes; environment overrides require 1.2.01.1.0
-M, --mem stringBase memory before scale, minimum 512 MiB; bare integer means MiB; overrides BARN_MEM1.2.0
--mirroruse the China official repository at repo.pigsty.cc; overridden by --repo1.1.0
-n, --no-waitreturn once QEMU is running, without waiting for the guest to boot1.1.0
-p, --parallel intNode concurrency: omitted = max(1, logical CPUs - 2); 0 = all selected nodes; positive = limit1.2.0
-r, --repo stringimage repository URL or directory; overrides --mirror and $BARN_REPO1.1.0
-S, --scale stringInteger 1–256 multiplying base CPU and memory only; disk does not scale; overrides BARN_SCALE1.2.0
--yessame as --force1.1.0
barn plan meta
barn recreate meta
barn recreate -f pigsty.yml meta --yes

barn status

Use status to check what is running and how each node is configured, from any directory.

barn status [node...] [flags]

status shows recorded node configuration and live QEMU process identity. running means a verified VM process, not a successful SSH probe. --verbose adds runtime details; --json exposes node records, notes on active operations, and failures. A degraded node makes the command exit 5 while healthy peers are still listed. Text output shows compact SPEC values such as 2c4g.

Aliases: st.

No local options beyond --help; global presentation options still apply.

barn status
barn status meta --verbose
barn --json status

barn destroy

Use destroy to remove nodes you no longer need, or the whole Linux lab while keeping persistent data disks for a later rebuild.

Warning

destroy deletes the root disks and non-persistent data disks of the selected nodes, or of every node when you pass no names. Persistent data disks are kept unless you add --delete-persistent; --purge also deletes them along with SSH keys and deployment state. See What survives each operation.

barn destroy [node...] [flags]

On a terminal you type destroy to confirm; scripts pass --yes or --force (there is no -y). --delete-persistent and --purge work only on the whole deployment. The image cache, the host network, and native Mac VMs remain.

Removing the control node makes the first remaining node the control node; update admin_ip and run up to configure its control SSH access.

Aliases: de.

OptionMeaning / defaultAvailable in
--delete-persistentalso delete owned persistent data disks1.1.0
--forcedestroy without the interactive confirmation (required without a terminal)1.1.0
-p, --parallel intNode concurrency: omitted = max(1, logical CPUs - 2); 0 = all selected nodes; positive = limit1.2.0
--purgeterminal disposal: also delete persistent disks, keys, and deployment state1.1.0
--yessame as --force1.1.0
barn destroy meta
barn destroy --yes
barn destroy --yes --purge

barn purge

barn purge and barn destroy --yes --purge immediately power off running Linux VMs before deleting their disks. Run barn stop first to give databases and other guest services time to shut down.

Use purge to start over: it deletes the entire Linux deployment in one step, without reading an inventory. It is also how you remove retained persistent data disks once no deployment state is left.

Caution

purge deletes immediately, with no confirmation unless you pass --ask: every node’s root disk, all persistent data disks, SSH keys, deployment state, and the default SSH fragment. See What survives each operation.

barn purge [flags]

purge takes no node names and has no --yes, -y, or --force. --ask shows the deletion scope first and proceeds only on y or yes; Enter cancels. Cached images, host networking, and Mac VMs remain. Without an applied deployment, purge still removes leftover deployment data under BARN_HOME, such as retained persistent data disks and keys, and succeeds when nothing is left; artifacts whose ownership Barn cannot verify block deletion. --parallel controls node work during disposal.

OptionMeaning / defaultAvailable in
--askshow the deletion scope and ask for y/yes before purging1.1.0
-p, --parallel intNode concurrency: omitted = max(1, logical CPUs - 2); 0 = all selected nodes; positive = limit1.2.0
barn purge --ask
barn --json purge

Implementation

See cmd/barn/command_lifecycle.go for lifecycle commands and TestPlanKeepsAnExistingLabsImageDefault in cmd/barn/lifecycle_overrides_test.go for upgrade behavior.

1.3 - Guest Access and Hosts

Open a shell on Linux guests, run commands and scripts, read logs, and publish SSH aliases and /etc/hosts names.

These commands reach running Linux guests from the host: ssh and exec run a shell or one command, provision streams a script to several nodes, and logs shows what a node printed. ssh-config and hosts publish node names so other host tools can reach the nodes too. Every command accepts the global options; Available in shows availability from the 1.1.0 baseline onward (version baseline).

Remote commands and --

barn ssh and barn exec share one argument rule: Barn flags and at most one node name, then --, then the remote command. They differ in what the guest receives:

barn ssh  [node] [-- command...]   # words joined into one line for the guest shell
barn exec [node] -- command...     # program and arguments passed separately
barn ssh meta -- …barn exec meta -- …
Guest receivesOne string, parsed by the guest shell, as with plain sshThe program and its arguments, with no shell
Pipes, ;, $VARWork; quote them so your local shell leaves them aloneWrap the command in sh -c '…'
Spaces, quotes, empty argumentsRe-parsed by the guest shellPreserved exactly
No commandOpens an interactive login shellFails: exec requires -- and a command
  • Before --: Barn flags such as --json, plus an optional node name. It must be a resolved node name, not an IP address, alias, or group; an unknown name exits 2. Without one, Barn picks the prepared control node, or else the first prepared node.
  • After --: everything goes to the guest, including a second -- and anything that looks like a Barn or OpenSSH flag. The first word must not be empty. For compatibility, exec also accepts one quoted string and hands it to the guest shell.
  • Exit status: Barn exits with the remote command’s status, so exit 17 in the guest makes barn exit 17. Check whether a nonzero code came from the guest before reading it as a Barn error class.
barn ssh meta -- 'df -h /data; id'           # a shell line, quoted like plain ssh
barn exec meta -- printf '<%s>\n' 'a b' ''   # 'a b' stays one argument; '' is kept
barn exec meta -- sh -c 'uptime; id'         # shell features through sh -c

barn ssh

barn ssh [flags] [node] [-- command...]

Open an interactive shell on a node, or run a shell line there (argument rules). With --json, session output goes to stderr and the final report to stdout.

No options of its own.

barn ssh
barn ssh meta
barn ssh meta -- 'df -h /data; id'

barn exec

barn exec [flags] [node] -- command...

Run one command on a node with no shell in between (argument rules); scripts and agents should use this form. Text mode passes the guest’s output and exit status straight through. With --json, the report has success, exit_code, stdout, and stderr.

Aliases: ex. No options of its own.

barn exec meta -- hostname
barn exec meta -- printf '<%s>\n' 'a b' ''
barn --json exec meta -- sh -c 'echo out; exit 17'

barn logs

barn logs [node] [flags]

Read a node’s log; start here when a node does not become ready (troubleshooting). --source serial (the default) reads the guest serial console and qemu reads QEMU diagnostics, with the QEMU argv shown only under --verbose. Both take one node and default to the prepared control node, or else the first prepared node. events reads the deployment-wide, bounded Barn event log, including setup; it takes no node and works before any deployment exists.

--follow keeps streaming: raw bytes in text mode, NDJSON with --json, and a YAML document stream with --yaml. Here -f means --follow, not --file.

Aliases: l.

OptionMeaning / defaultAvailable in
-f, --followcontinue streaming appended log data1.1.0
-s, --source stringlog source: serial, qemu, or events (default “serial”)1.1.0
barn logs meta
barn logs meta --source qemu
barn logs --source events --follow
barn --json logs meta --follow

barn provision

barn provision [node...] [flags]

Run a local Bash script on running nodes, for example to bootstrap or check several at once; with no node names, it runs on all of them. Barn streams the script over the deployment’s verified SSH connection, so no copy stays on the guest, and records its SHA-256. It never creates or starts VMs.

--script is required. Nodes run one at a time unless you raise --parallel, which must be positive: unlike lifecycle commands, provision rejects 0. --timeout bounds the whole operation. --sudo runs the script through sudo -n, so the guest user needs passwordless sudo, as official images provide. --json returns script.sha256 and per-node results[] with node, success, exit_code, stdout, and stderr; if only some nodes fail, the exit code is 5.

OptionMeaning / defaultAvailable in
-p, --parallel intPositive concurrency limit; default 1; zero is invalid1.1.0
-s, --script stringlocal Bash script to stream to each selected guest1.1.0
--sudorun the guest script through sudo -n1.1.0
-t, --timeout durationhard deadline for the operation (default 1h0m0s)1.1.0
barn provision --script ./check.sh meta
barn provision --script ./bootstrap.sh --sudo --parallel 2 --timeout 30m

barn ssh-config

barn ssh-config [node...] [flags]

Print the deployment’s OpenSSH config fragment, which lets plain ssh, scp, and other OpenSSH tools reach nodes by name (ssh meta). Lifecycle commands such as barn up keep the default fragment, ~/.ssh/barn_config, current, so you rarely need this by hand. Use it to inspect the fragment, to limit it to some nodes, or to install another one with --name.

--install writes the fragment and adds one Include line to ~/.ssh/config. --remove removes only the fragment and Include installed under that name; it needs no deployment, takes no node names, and cannot be combined with --install. If ~/.ssh/config cannot be edited safely, for example because it is a symlink, Barn writes the fragment and prints the Include line for you to add.

Aliases: sc.

OptionMeaning / defaultAvailable in
-i, --installinstall the deployment fragment and one Include in ~/.ssh/config1.1.0
--name stringSSH Host and fragment prefix (default “barn”)1.1.0
--removeremove the Include and fragment Barn installed1.1.0
barn ssh-config
barn ssh-config --install meta
barn ssh-config --install --name lab
barn ssh-config --remove --name lab

barn hosts install

barn hosts install [flags]

SSH aliases help only OpenSSH tools. To let browsers, psql, and other host programs resolve node names and aliases, publish them in a Barn-owned block of /etc/hosts; barn up does not do this.

By default, the block lists the applied nodes’ names and aliases. Since 1.2.0, -f pigsty.yml publishes the inventory’s nodes plus all.vars.vm_hosts instead, even before the VMs exist (local service names). Each run replaces the whole block, so a later run without -f drops names that came only from the inventory.

On a terminal, Barn shows the change and asks Apply this /etc/hosts change? [Y/n]. Without a terminal, or with --json or --yaml, it only prints the plan; --yes applies it without asking, though sudo may still want a password. Barn edits the file through a root-owned helper, /opt/barn/libexec/barn-hosts-helper, which it installs on first use and verifies by digest. A block that is already current needs no privilege.

Aliases: i.

OptionMeaning / defaultAvailable in
-f, --file stringInventory nodes, aliases and vm_hosts; usable before VM creation1.2.0
-y, --yesapply the displayed privileged plan without confirmation (sudo may still ask for a password)1.1.0
barn hosts install --json
barn hosts install --yes
barn hosts install -f pigsty.yml --yes

barn hosts uninstall

barn hosts uninstall [flags]

Remove the Barn-owned block from /etc/hosts, keeping every other line. It needs no inventory or deployment. Confirmation works as for hosts install, except that the terminal question, Remove the Barn block from /etc/hosts? [y/N], defaults to no.

Aliases: u.

OptionMeaning / defaultAvailable in
-y, --yesapply the displayed privileged plan without confirmation (sudo may still ask for a password)1.1.0
barn hosts uninstall --json
barn hosts uninstall --yes

Implementation

command_root.go · command_access.go · main.go

1.4 - Guest Time Synchronization

Measure Linux guest clocks against the host, correct them, and enable optional scheduled checks.

While the host sleeps or a VM is paused, the guest does not run, so its clock falls behind the host’s; in an offline lab, guest NTP has no source to correct it. barn time measures each Linux guest against the host clock and sets it over management SSH, so it works without guest Internet access. Barn checks clocks on demand with barn time sync, when up, start, restart, reload, or recreate brings guests to ready, and, if you opt in, every minute from an OS timer.

The guest side needs Python 3.6 or later and passwordless sudo. barn time is new in 1.3.0 (version baseline), acts on the deployment that BARN_HOME selects, and accepts the global options.

Measure and correct clocks

barn time status
barn --json time status meta node-1
barn time sync
barn time sync meta node-1 --timeout 30s

status measures; sync sets each guest clock to the host’s, forward or backward, and measures again. Without node names, both cover the whole applied deployment and skip stopped, exited, and uncreated nodes, which is not a failure. Results show the offset (positive means the guest is ahead), its uncertainty (half the round trip), and the guest’s NTP synchronization state, service, and source before any change.

A backward step moves application wall time backward too, so choose the moment deliberately when time-sensitive workloads run in the guest.

CommandOptionDefaultMeaningAvailable in
time status [node...]--timeout1mTotal deadline, from 1s to 10m1.3.0
time sync [node...]--timeout1mTotal deadline, from 1s to 10m1.3.0

Barn checks the VM process, the instance SSH identity, and the guest readiness marker, takes three samples, and uses the one with the shortest round trip, compensating for transport time with the guest’s monotonic clock. A measurement fails if all three round trips exceed 250 ms, and a sync fails if more than 500 ms of offset remains afterwards. Nodes fail independently, each with its own error, and any failure makes the exit code nonzero.

Startup checks

up, start, restart, reload, and recreate check the guests they bring to ready and correct offsets above two seconds before returning, so a barn provision that follows sees the corrected time; services already enabled in the guest may start earlier during boot. A failed check does not fail the command: it appears in the lifecycle result’s top-level warnings[] with code time_sync, and its next suggests barn time sync for the affected nodes. --no-wait skips the check.

Scheduled checks

Enable the timer when the host sleeps often or VMs stay paused between sessions:

barn time auto enable
barn time auto status
barn --json time auto status
barn time auto disable

enable installs a timer for the invoking Unix user that records the executable path, BARN_HOME, and PATH. Run it from an installed binary, and again after moving Barn or switching BARN_HOME. The timer checks every running Linux guest of the recorded BARN_HOME, whatever the current directory or inventory.

HostSchedulerJob files
macOSlaunchd calendar job~/Library/LaunchAgents/com.pgsty.barn.time.plist
Linuxsystemd user timer and oneshot service${XDG_CONFIG_HOME:-~/.config}/systemd/user/barn-time-sync.{timer,service}

A check runs every minute for at most 45 seconds, corrects offsets above two seconds, and skips the deployment while another barn command holds its lock. Missed checks run after the host resumes, but the timer never wakes the host, and it needs the user’s launchd session or systemd user manager to be running.

If drift returns within ten minutes of a correction while the guest ran continuously and its NTP reports synchronized, the guest’s NTP source disagrees with the host. Barn reports source-conflict and stops correcting that node automatically, so the two do not keep pulling the clock apart. Host sleep, VM pause, and guest reboots do not count; the guest’s monotonic clock tells them apart. To clear the conflict, align the guest’s NTP source with the host or run barn time sync; an offset back within the threshold or a guest reboot also clears it.

status shows whether the job files are installed and the scheduler has them active, plus the latest result from $BARN_HOME/time-last.json, which each run replaces. Correction history lives in $BARN_HOME/time-sync.json; Barn prunes it when nodes or deployments are destroyed, and barn purge removes it with time-last.json. disable stops the timer and removes its job files; manual and startup checks keep working.

Host NTP and offline Pigsty

barn time corrects the clock but gives the guest no NTP source, so Pigsty’s node_timex_sync_status need not become 1. For continuous synchronization in an offline lab, serve time from the host: macOS ships sntpd, disabled by default, and Linux can use chronyd. Let the server fall back to its local clock when no upstream source is reachable, and allow only the lab network. Pigsty rewrites the Chrony configuration when it deploys NODE, so point the guests at the host’s .1 address on the lab /24 through node_ntp_servers in the Pigsty inventory. Once Chrony keeps the guests synchronized, you can disable the Barn timer and keep barn time sync for manual corrections.

Implementation

command_time.go · timesync · timejob

1.5 - Image Commands

Refresh signed catalogs, inspect or download images, import local files, and prune caches.

Refresh signed catalogs, inspect or download images, import local files, and prune caches.

barn image update is available from 1.4.0. Version baseline · Global options

Official repositories and HTTP sources require a trusted detached signature. An explicitly selected custom HTTPS repository or local directory can be unsigned, provided the source is exactly that repository’s catalog.json. Any supplied signature must verify. See catalog trust.

barn update

barn update [flags]

Fetch catalog.json and its signature when required by repository policy, verify trust and revision rules, then atomically activate the catalog. Ordinary commands read local metadata. A newly built local repository can be read directly before its first explicit update. Remote catalogs require an explicit refresh. This updates image metadata, not the Barn executable. Repository precedence is --repo > --mirror > BARN_REPO > the global official repository. See repository selection and trust.

OptionMeaning / defaultAvailable in
--mirroruse the China official repository at repo.pigsty.cc; overridden by --repo1.1.0
-r, --repo stringimage repository URL or directory; overrides --mirror and $BARN_REPO1.1.0
barn update
barn update --mirror
barn --json update --repo /srv/barn

barn image list

barn image list [flags]

List every catalog architecture and registered local image. It has no image selector or architecture filter. The active local catalog is used; run barn update explicitly to refresh it. Aliases barn images and barn im select the same image command group.

Aliases: ls.

OptionMeaning / defaultAvailable in
-r, --repo stringimage repository URL or directory; overrides $BARN_REPO1.1.0
barn image list
barn --json image list
barn image list --repo /srv/barn

barn image info

barn image info [image[:channel]|image@version-prefix] [flags]

Inspect metadata and verified cache state for one image, using the catalog default if omitted. Select a family (d13), shorthand family alias (e/el/rocky → el10, u/ubuntu → u26, d/debian → d13), architecture-suffixed alias (el10a, d13x, da), channel (d13:stable), or numeric version prefix (el9@9). Architecture defaults to native; an explicit -A arm64 agrees with d13a, while -A amd64 or -A native conflicts with it (exit 2). The compatibility spelling --architecture/-a is also accepted for --arch/-A. It does not download the artifact. Supported aliases and exact embedded versions are in Linux images.

Aliases: in.

OptionMeaning / defaultAvailable in
-A, --arch stringartifact architecture (defaults to native): native, amd64 (x86_64, x64), or arm64 (aarch64, a64)1.1.0
-r, --repo stringimage repository URL or directory; overrides $BARN_REPO1.1.0
barn image info
barn image info el10a
barn image info d13 -A arm64
barn --json image info el9@9

barn image pull

barn image pull [image[:channel]|image@version-prefix] [flags]

Download the selected artifact and verify its SHA-256, byte size, qcow2 structure, and virtual capacity before activating the cache entry. Omitted image and architecture select the catalog default and native host architecture. Shorthand family and architecture-suffixed aliases such as el10a and d13x work here as well (a matching -A is accepted, a conflicting architecture or explicit native exits 2). Existing valid cached bytes are reused. The catalog’s upstream URL is provenance, not a download fallback. --architecture/-a remains a compatibility alias. A foreign artifact does not install the corresponding QEMU emulator.

Aliases: p.

OptionMeaning / defaultAvailable in
-A, --arch stringartifact architecture (defaults to native): native, amd64 (x86_64, x64), or arm64 (aarch64, a64)1.1.0
--mirroruse the China official repository at repo.pigsty.cc; overridden by --repo1.1.0
-r, --repo stringimage repository URL or directory; overrides --mirror and $BARN_REPO1.1.0
barn image pull
barn image pull d13 --mirror
barn image pull d13 -A amd64 --repo /srv/barn

barn image update

barn image update [image[:channel]...] [flags]

Barn refreshes the selected repository’s catalog under its trust policy, then downloads and verifies the selected files. With no arguments, it updates the image families and architectures already in the cache. An empty cache results in a catalog refresh only.

To fetch a specific build into an empty cache, name an architecture alias such as d13i (amd64) or d13a (arm64). A bare family such as d13 updates its cached architectures and uses the host architecture for its first download. The default channel is stable. Use image pull for a pinned version such as d13@20261123.2671.1. Existing VMs keep their original base images.

The command alias is u.

OptionEffectAvailable in
-A, --arch stringSelect one architecture, including native, amd64 or arm641.4.0
-d, --dry-runVerify the candidate catalog and preview downloads and requested cleanup without writing local state1.4.0
--pruneAfter successful downloads, remove files eligible under the normal pruning rules1.4.0
--mirrorSelect the China official repository1.4.0
-r, --repo stringSelect a repository URL or directory. Takes precedence over --mirror and BARN_REPO1.4.0
barn image update --dry-run
barn image update d13i d13a
barn image update --mirror --prune --dry-run

--prune applies to the whole cache, including when you name individual images. The active catalog, applied VMs and registered local aliases protect the files they reference. Pruning rules

barn image import

barn image import <path> [flags]

Copy a local regular qcow2 image into the private cache and validate its container, optionally against an expected digest. Relative paths, ~/, and symlinks to regular files are accepted. qemu-img is required; importing does not boot the image, add cloud-init, or change credentials.

A local-* name registers an immutable inventory reference and requires boot mode plus the source login user. Named imports can record a foreign architecture with -A; qcow2 metadata does not identify CPU architecture, and unnamed imports cannot use -A. Set both vm_image and a matching vm_arch when using it. See import and cache rules.

Aliases: i.

OptionMeaning / defaultAvailable in
-A, --arch stringGuest architecture recorded with --name; defaults to native; does not convert the image1.1.0
-b, --boot stringrequired with --name: bios or uefi1.1.0
--name stringImmutable local-* alias; requires --boot and --source-user1.1.0
-s, --sha256 stringoptional expected SHA-2561.1.0
-u, --source-user stringrequired with --name: source image login user1.1.0
barn image import ./base.qcow2
barn image import ./debian-13-generic-arm64.qcow2 --name local-dev --boot uefi --source-user debian -A arm64

barn image sync

barn image sync <url|path> [flags]

Activate a catalog from one exact URL or local file, reading its adjacent .sig signature under the trust policy above. This is the recovery/import path; use update for the configured repository’s normal endpoint. --repo chooses which repository’s active metadata to replace. An unsigned custom source must be exactly <repo>/catalog.json; an arbitrary recovery file requires a trusted signature.

Older revisions require --allow-downgrade. For custom repositories that allow unsigned catalogs, switching from a previously signed catalog to an unsigned one also requires this flag. It never permits an invalid signature or bypasses the official-repository signature requirement and revision-content checks. Future downgrade protection still remembers the highest revision.

Aliases: sy.

OptionMeaning / defaultAvailable in
--allow-downgradeactivate a catalog older than the newest revision seen so far1.1.0
-r, --repo stringRepository whose active catalog is replaced1.1.0
barn image sync /srv/barn/catalog.json
barn image sync --repo /srv/barn /srv/recovery/catalog.json
barn image sync --allow-downgrade /srv/recovery/catalog.json

barn image reset

barn image reset [flags]

Reactivate the catalog embedded in the current binary for the selected repository. It keeps the highest accepted revision used by downgrade protection. Cached images and VM disks are retained; this is not a cache deletion command.

OptionMeaning / defaultAvailable in
-r, --repo stringRepository whose active catalog is reset to the embedded catalog1.1.0
barn image reset
barn --json image reset --repo /srv/barn

barn image prune

barn image prune [flags]

List reclaimable cache files by default. Use --yes to delete the candidates or --dry-run to preview them. The selected active catalog, applied node base-image digests, and registered local aliases protect their referenced images. Recognized staging files and read-only quarantine files such as *.qcow2.corrupt-<timestamp> are also eligible for removal.

Preview with the same repository selection you will use for deletion. Deletion is sequential; an error on a later file does not restore files already removed. See pruning rules.

Aliases: pr.

OptionMeaning / defaultAvailable in
-d, --dry-runshow unreferenced images and stale staging files without deleting1.1.0
-r, --repo stringimage repository URL or directory; overrides $BARN_REPO1.1.0
-y, --yesDelete the listed unreferenced files; mutually exclusive with --dry-run1.1.0
barn image prune --dry-run
barn image prune --repo /srv/barn --dry-run
barn image prune --repo /srv/barn --yes

Implementation

The 1.5.0 image commands are in cmd/barn/command_image.go and cmd/barn/images.go. Catalog verification is covered by internal/image/manifest_test.go.

The version baseline lists changes through 1.5.0.

1.6 - Repository Commands

Scan, build and verify a repository of qcow2 images, with optional metadata in repo.yaml.

A static repository has a flat images/ directory and a generated catalog.json. In 1.5.0, barn repo build reads names, versions and architectures from filenames. Add repo.yaml for aliases, channels, nonstandard names or different boot settings. Build a static repository · Repository format

barn repo scan /srv/barn     # inspect the files under images/
barn repo build /srv/barn    # write catalog.json
barn repo verify /srv/barn   # compare the catalog with the images and optional metadata

All three have been available since 1.1.0. Each takes one repository root and has no options beyond the global options.

barn repo scan

barn repo scan <root> [flags]

Report the state of every qcow2 file without changing anything or needing qemu-img:

StateMeaning
trackedSelected by filename inference or repo.yaml, and present
missingReferenced by repo.yaml but absent from images/
untrackedPresent in images/ but not referenced by repo.yaml
unsafeNot a safe regular qcow2 file

--json returns root and the four arrays. The scan exits 0 whenever it completes, even with findings, so a script must check missing and unsafe itself:

barn --json repo scan /srv/barn | jq -e '(.missing + .unsafe) | length == 0'

barn repo build

barn repo build <root> [flags]

Inspect selected images with qemu-img and atomically write catalog.json with the final digests and sizes. A supplied repo.yaml controls selection. A missing or unsafe declared artifact fails the build.

With an explicit revision, increase it when the catalog changes. With the revision omitted, Barn assigns it automatically and preserves the previous bytes on an unchanged rebuild. Upload immutable images before publishing the catalog. Signing and trust rules

barn repo build /srv/barn
barn --json repo build /srv/barn

barn repo verify

barn repo verify <root> [flags]

Rebuild the catalog in memory from the filenames, optional repo.yaml and actual image bytes, and require a byte-for-byte match with the existing catalog.json. Requires qemu-img. Run it before publishing or after copying a repository. It checks consistency only; clients check signatures when they activate the catalog.

barn repo verify /srv/barn
barn --json repo verify /srv/barn

Implementation

The self-hosted repository guide gives a two-command example.

1.7 - Host Network Commands

Inspect, install, repair, and remove the fixed-IP network that lets Linux nodes reach each other.

Every Linux node gets two NICs: one reaches the Internet through QEMU’s built-in NAT, and one sits on a fixed /24 where the host and the other nodes reach it at the address your inventory names (why two NICs). These commands manage the host side of that second network, socket_vmnet on macOS and the barn0 bridge on Linux. barn setup and the first interactive barn up install it for you (host preparation); use these commands to check, repair, reconfigure, or remove it.

One network serves all Linux guests on the host; native Mac VMs have their own. install and uninstall print a privileged plan first and, on a terminal, ask before applying it. Without a terminal, or with --json or --yaml, they only print the plan; --yes applies it without asking, though sudo may still want a password.

barn network also answers to n and net. Every command accepts the global options; Available in shows availability from the 1.1.0 baseline onward (version baseline).

barn network status

barn network status [flags]

Show the backend, installed CIDR, ownership, health, and the preflight findings that lifecycle commands check before changing anything. It is read-only. --cidr checks against an expected subnet; without it, status inspects the installed one. For partial or invalid results, see troubleshooting.

On Linux, 1.5.0 checks KVM access, bridge prerequisites and the configured private network. Run barn doctor for the full QEMU capability check.

Aliases: st.

OptionMeaning / defaultAvailable in
-c, --cidr stringOptional expected private /24; otherwise inspect the installed subnet1.1.0
barn network status
barn --json network status --cidr 10.10.10.0/24

barn network install

barn network install [flags]

Install or repair the backend for --cidr: socket_vmnet on macOS in host or shared vmnet mode, or barn0 through the active Linux network manager, which accepts only host. An existing network must match the chosen subnet and mode, so check status before changing either.

On a fresh Mac, run barn setup instead. A first install needs a pinned socket_vmnet archive and a new vmnet interface UUID, which setup supplies; without both --archive and --interface-id, network install exits 3 with reason network_absent and suggests barn setup. Both flags are macOS-only.

Aliases: i.

OptionMeaning / defaultAvailable in
-a, --archive stringmacOS: pinned socket_vmnet archive1.1.0
-c, --cidr stringnetwork: an RFC1918 IPv4 /24 (default “10.10.10.0/24”)1.1.0
-i, --interface-id stringmacOS: persistent vmnet UUID1.1.0
-m, --mode stringmacOS vmnet mode: host or shared (default “host”)1.1.0
-y, --yesapply the displayed privileged plan without confirmation (sudo may still ask for a password)1.1.0
barn network install --json
barn network install --cidr 10.10.10.0/24 --yes

macOS Internet Sharing

Install and repair work while Internet Sharing is on, as long as its vmnet preferences set neither a custom subnet address nor a mask. If the preview cannot read those preferences, it says so, and Barn checks them after you approve, before writing network files or restarting socket_vmnet. A subnet that conflicts with a live interface, route, or node address blocks the plan at preview. Preferences that turn out unreadable, conflicting, or only half set stop the operation before the host changes.

barn network uninstall

barn network uninstall [flags]

Remove Barn-owned network configuration and restore the host settings recorded at install. Stop the Linux nodes first; uninstall refuses while any node is running. The terminal question, Remove the Barn network? [y/N], defaults to no. VM disks and native Mac VM networks stay in place.

Aliases: u.

OptionMeaning / defaultAvailable in
-y, --yesapply the displayed privileged plan without confirmation (sudo may still ask for a password)1.1.0
barn stop
barn network uninstall --json
barn network uninstall --yes

Implementation

The 1.5.0 status checks are in cmd/barn/command_network.go and internal/doctor/network.go.

1.8 - macOS Commands

Syntax, options, and examples for every barn mac subcommand.

Syntax, options, and examples for every barn mac subcommand. The machine model, networks, JSON results, and failure reasons these commands share are defined in the Mac Runtime Reference; a guided first run is in macOS Virtual Machines.

Common rules

  • Host. The commands need an Apple Silicon Mac on macOS 27 or later with the matching Barn.app, run as the logged-in desktop user (requirements). At most two macOS VMs run at a time per Mac; starting a third fails with mac_vm_limit.
  • Machine names. A command with an optional [name] uses the only existing machine, or mac1. With several machines and none named mac1, pass a name. configure, recreate, and destroy always need one. start and stop take several names or --all, not both.
  • Sizes. --memory and --disk are binary even when written GB: 16G, 16GiB, and 16GB all mean 16 GiB, and a bare number is bytes. Linux inventory GB is decimal.
  • Confirmation. recreate and destroy print what they will delete and ask you to type the command name. --yes or --force skips the question and is required without a terminal; neither command has a -y shorthand. Commands that download macOS from Apple (up, setup, image update) ask first; -y/--yes skips that question and is required without a terminal.
  • State. Machines live under $BARN_HOME/mac, separate from the Linux inventory. These commands ignore the Linux BARN_IMAGE/BARN_ARCH/BARN_CPU/BARN_MEM/BARN_SCALE/BARN_DISK overrides.

Every option below has been available since 1.1.0.

barn mac ls

Start here to see what exists: every machine with its state, address, SSH readiness, macOS build, resources, and shares.

barn mac ls [flags]

It reads local records and queries running machines; it never creates, downloads, or starts anything. barn mac without a subcommand runs ls. The JSON shape is in ls output.

Aliases: list, status, st.

No local options beyond --help; global presentation options still apply.

barn mac ls
barn --json mac ls

barn mac up

Use up to get a machine running: it creates the machine the first time, starts it afterwards, and returns once SSH and passwordless sudo work.

barn mac up [name] [flags]

The default name is mac1. On a Mac without a prepared macOS base, up first downloads the restore image from Apple after you confirm and installs it once; later machines clone that base in seconds. A --disk size that differs from the prepared base’s capacity installs a matching base first.

Creation options apply only to a new machine. On an existing machine up just starts it; an option that differs from the recorded setting fails with mac_configuration_conflict, and the next: line prints the command to use instead. --share names default to the folder’s last path component, and ~/ expands to your home directory.

--no-wait returns once the VM is running. On a first boot, provisioning may still be in progress; run barn mac up NAME again to wait for SSH and finish initialization before using ssh or exec.

OptionMeaning / defaultAvailable in
--clipboard on|offon/off, true/false, or yes/no; default on, active while the desktop window is focused1.1.0
--cpu intvCPUs, default 4; minimum 2, maximum host logical CPU count1.1.0
--disk sizeBase capacity, minimum 32 GiB; default uses the prepared base, or 100 GiB initially1.1.0
--ipsw stringinstall macOS from this restore image instead of downloading from Apple1.1.0
--memory sizeMemory, default 8 GiB; a whole MiB from 4 GiB to host RAM1.1.0
-n, --no-waitreturn once the VM runs; first boot may still be initializing1.1.0
--openshow the desktop as soon as the VM runs1.1.0
--share [name=]path[:ro]Repeatable [name=]path[:ro|:rw]; default writable, mounted under /Volumes/My Shared Files1.1.0
--subnet stringCanonical private /24, or auto; default selects the first free subnet1.1.0
--user stringGuest administrator; default is the host username, or barn if that name is invalid1.1.0
-y, --yesdownload macOS from Apple without asking (required without a terminal)1.1.0
barn mac up
barn mac up dev --cpu 8 --memory 16G --share ~/src --open
barn mac up build --yes --no-wait

barn mac start

Use start to boot machines that have already completed their first up. It waits for SSH and never creates a machine or downloads anything.

barn mac start [name...] [flags]

Select names or --all, not both. A machine that has not finished its first boot fails with mac_not_initialized: if it is running, watch its first boot with barn mac open NAME; if it is stopped, continue with barn mac up NAME --open. --recovery boots macOS Recovery with its desktop shown and does not wait for SSH.

OptionMeaning / defaultAvailable in
--allstart every machine1.1.0
-n, --no-waitreturn once the VM runs, without waiting for SSH1.1.0
--openshow the desktop as soon as the VM runs1.1.0
--recoveryboot macOS Recovery and show its desktop1.1.0
barn mac start mac1
barn mac start --all
barn mac start mac1 --recovery

barn mac stop

Use stop to shut machines down cleanly through macOS; disks and settings stay as they are.

barn mac stop [name...] [flags]

A machine that has not stopped after two minutes is powered off, and the result says so ("forced": true). --force powers off at once, like holding the power button; unsaved work in the guest is lost.

OptionMeaning / defaultAvailable in
--allstop every machine1.1.0
--forcePower off immediately instead of requesting shutdown; unsaved guest work is lost1.1.0
barn mac stop dev
barn mac stop --all
barn mac stop dev --force

barn mac restart

Use restart to apply settings saved with configure, or to reboot a guest that misbehaves.

barn mac restart [name] [flags]

It shuts the machine down normally and starts it again. It takes at most one name and has no --all.

OptionMeaning / defaultAvailable in
-n, --no-waitreturn once the VM runs, without waiting for SSH1.1.0
--openshow the desktop as soon as the VM runs1.1.0
barn mac restart dev
barn mac restart dev --open

barn mac configure

Use configure to change a machine’s CPUs, memory, shared folders, network, or clipboard setting without touching its disk or account.

barn mac configure <name> [flags]

CPUs, memory, shared folders, and the subnet change only while the machine is stopped; otherwise the command fails with mac_running. The clipboard setting can change anytime. Saved configuration, including a clipboard change, applies at the next start; to toggle clipboard sharing for the current session, use the menu bar.

Omitted options keep their values. --share adds a share or replaces the share of that name; --unshare removes one. --subnet auto moves the machine to the first free subnet, which is the fix for mac_subnet_in_use.

OptionMeaning / defaultAvailable in
--clipboard on|offon/off, true/false, or yes/no; omitted retains the setting1.1.0
--cpu intvCPUs, minimum 2 and maximum host logical CPU count; omitted retains current value1.1.0
--memory sizeMemory, a whole MiB from 4 GiB to host RAM; omitted retains current value1.1.0
--share [name=]path[:ro]Add or replace a named share; repeatable, writable by default, optional :ro or :rw1.1.0
--subnet stringmove to this private /24 network, or auto for the first free one1.1.0
--unshare stringArraystop sharing the named folder (repeatable)1.1.0
barn mac stop dev
barn mac configure dev --cpu 8 --memory 16G --share ~/src
barn mac configure dev --unshare src --clipboard off
barn mac start dev

barn mac recreate

Use recreate to get a clean disk from the base image while keeping the machine’s name and settings, or, with --update, to move the machine to the newest prepared macOS.

Warning

recreate erases the machine’s disk: files, apps, and settings inside the guest are lost. Shared folders on the host are untouched. Copy anything you need off the guest first.

barn mac recreate <name> [flags]

The new machine keeps its name, account, CPUs, memory, disk capacity, shared folders, clipboard setting, and address, and gets a new login password and new SSH keys.

--update clones the default base that barn mac image update prepared, at the machine’s own disk capacity. If the new macOS build is prepared only at another capacity, prepare it first, for example barn mac setup --disk 200G.

OptionMeaning / defaultAvailable in
--forceskip the confirmation (required without a terminal)1.1.0
-n, --no-waitreturn once the VM runs, without waiting for SSH1.1.0
--updateuse the newest prepared macOS base1.1.0
--yesSame as --force; no -y shorthand1.1.0
barn mac recreate dev
barn mac image update --yes
barn mac recreate dev --update --yes

barn mac destroy

Use destroy to delete machines you no longer need.

Warning

destroy powers each named machine off and deletes its disk, SSH keys, password, and settings. The shared macOS base, other machines, and shared folders on the host are kept.

barn mac destroy <name...> [flags]

Explicit names are required. Run barn mac image prune afterwards to remove bases that no machine uses.

OptionMeaning / defaultAvailable in
--forceskip the confirmation (required without a terminal)1.1.0
--yesSame as --force; no -y shorthand1.1.0
barn mac destroy dev
barn mac destroy mac1 mac2 --yes

barn mac open

Use open to see and use the machine’s desktop; it starts a stopped machine first.

barn mac open [name] [flags]

Closing the window keeps the machine running in the background, and the clipboard is shared while the window is focused. A running machine that has not finished its first boot can be watched here; for a stopped one, use barn mac up NAME --open.

No local options beyond --help; global presentation options still apply.

barn mac open
barn mac open dev

barn mac ssh

Use ssh for an interactive shell in the machine, or to run a shell command line in it.

barn mac ssh [flags] [name] [-- command...]

Without a command, ssh opens an interactive session. A command after -- is joined into one line for the guest shell, as plain ssh does, and its exit status is returned. Argument rules are in SSH and exec.

No local options beyond --help; global presentation options still apply.

barn mac ssh dev
barn mac ssh dev -- 'sw_vers; id'

barn mac exec

Use exec in scripts: it runs one program with its arguments passed exactly as given and returns the program’s exit status.

barn mac exec [flags] [name] -- command...

A command after -- is required. Use sh -c explicitly for pipelines and other shell expressions. With --json the result carries exit_code, stdout, and stderr. Argument rules are in SSH and exec.

No local options beyond --help; global presentation options still apply.

barn mac exec dev -- sw_vers
barn mac exec dev -- printf '<%s>\n' 'a b' ''
barn --json mac exec dev -- sh -c 'echo out; exit 3'

barn mac password

Use password when the guest desktop asks for the login password, at the lock screen or an administrator prompt.

barn mac password [name] [flags]

The password is stored next to the machine’s SSH key with the same protection. --copy puts it on the clipboard instead of printing it.

OptionMeaning / defaultAvailable in
-c, --copycopy to the clipboard instead of printing1.1.0
barn mac password dev
barn mac password dev --copy

barn mac ssh-config

Use ssh-config to let ssh, scp, rsync, and editors reach each machine by name, with its own key and pinned host key.

barn mac ssh-config [flags]

Without options it prints the OpenSSH fragment. The first machine to become ready installs the fragment as one Include in ~/.ssh/config, and lifecycle commands keep it current. --remove deletes only what Barn installed and keeps it out until --install. A name that ~/.ssh/config already uses for another host is published by address only. If ~/.ssh/config is a symlink or hard link, the command fails with ssh_config_linked and prints the Include line for you to add.

--install and --remove are mutually exclusive. This command takes no machine names.

OptionMeaning / defaultAvailable in
-i, --installinstall the entries as one Include in ~/.ssh/config1.1.0
--removeremove the entries Barn installed1.1.0
barn mac ssh-config
barn mac ssh-config --install
barn mac ssh-config --remove

barn mac logs

Use logs when a machine fails to start, loses its network, or does not shut down: it shows the last lines of the machine’s runtime log, including Apple Virtualization errors.

barn mac logs [name] [flags]

--lines/-n must be positive and defaults to 100. Here -n means lines, not no-wait. There is no follow option.

OptionMeaning / defaultAvailable in
-n, --lines intnumber of recent lines (default 100)1.1.0
barn mac logs dev
barn mac logs dev --lines 200

barn mac setup

Use setup to prepare the macOS base ahead of time, for example in a provisioning script, so the first up only has to clone it.

barn mac setup [flags]

It downloads macOS from Apple after you confirm, or reads --ipsw, and installs it once into the unbooted base that every machine is cloned from. up does the same automatically when no base is prepared.

OptionMeaning / defaultAvailable in
--disk sizeBase capacity, at least 32 GiB. Defaults to the current base capacity or 100 GiB for the first base1.1.0
--ipsw stringinstall macOS from this restore image instead of downloading from Apple1.1.0
-y, --yesdownload macOS from Apple without asking (required without a terminal)1.1.0
barn mac setup --yes
barn mac setup --ipsw ~/Downloads/restore.ipsw --disk 200G

barn mac image ls

Use image ls to see which restore images and bases take up disk space, and which machines use them.

barn mac image ls [flags]

It lists each restore image and base with its state and disk usage. It reads local state only and does not start the native runner.

Aliases: list.

No local options beyond --help; global presentation options still apply.

barn mac image ls
barn --json mac image ls

barn mac image update

Use image update to move to Apple’s newest macOS 27 build.

barn mac image update [flags]

It asks Apple for the newest macOS 27 restore image, downloads it after you confirm, and installs it as the default base for new machines. Existing machines keep their base until you run barn mac recreate NAME --update.

OptionMeaning / defaultAvailable in
--ipsw stringuse this restore image instead of downloading from Apple1.1.0
-y, --yesdownload without asking (required without a terminal)1.1.0
barn mac image update --yes
barn mac image ls

barn mac image prune

Use image prune to reclaim disk space from bases that no machine uses.

barn mac image prune [flags]

It lists unused bases other than the current default. --installers adds downloaded restore images and partial downloads. Nothing is deleted without --yes.

OptionMeaning / defaultAvailable in
--installersinclude downloaded restore images and partial downloads1.1.0
-y, --yesDelete the listed unused images; otherwise only list candidates1.1.0
barn mac image prune
barn mac image prune --installers --yes

barn mac doctor

Run doctor first when something goes wrong, and after installing or upgrading Barn.

barn mac doctor [flags]

It checks macOS and Apple Silicon support, the Mac component’s signature, free disk space, the prepared base, and every machine: its files, keys, shared folders, network, and SSH. It changes nothing and starts nothing, and exits 3 if any check fails.

No local options beyond --help; global presentation options still apply.

barn mac doctor
barn --json mac doctor

Implementation

command_mac.go

2 - Configuration

The inventory file that defines a Linux lab — its shape, the variables Barn reads, their defaults, and how flags and environment variables override them.

A Linux lab is one YAML file that lists each node under its fixed IPv4 address. This page defines the file’s shape, every variable Barn reads with its default, and how command-line flags and environment variables override them.

barn.yml
all:
  vars:                                  # applies to every host below
    admin_ip: 10.10.10.10                # the control node
    vm_image: d13                        # Debian 13
  children:                              # ordinary Ansible groups; they may nest
    lab:
      vars:
        vm_mem: 4GiB                     # group default, overrides all.vars
      hosts:
        10.10.10.10: { nodename: meta }  # key = the node's address on the lab /24
        10.10.10.11: { nodename: node-1 }
        10.10.10.12: { nodename: node-2, vm_cpu: 2 }  # host value wins over groups

This is an ordinary Ansible inventory. Barn reads the vm_* variables and a few Pigsty fields and ignores everything else, so the same file can also drive Pigsty or Ansible: add vm_* variables to a Pigsty pigsty.yml, and Barn creates exactly the nodes its playbooks target.

Check the file and preview its effect before starting anything:

barn validate -f barn.yml
barn --json validate -f barn.yml
barn plan -f barn.yml

validate checks YAML syntax, field rules, and image references against the local catalog without starting VMs or downloading images. Its JSON output includes valid, source, spec_hash, and resolved; if the catalog cannot be read, it warns and leaves image selectors unresolved. To check against another repository’s catalog, pass --repo, for example --repo https://repo.pigsty.cc/barn for the China mirror (validate has no --mirror). up later verifies what validate cannot: local-* image bytes, host capabilities, shared directories, networking, and guest SSH.

To start from a template, barn init [meta|dual|trio|full] writes a 1-, 2-, 3-, or 4-node inventory: meta at .10, then node-1, node-2, and node-3 at .11–.13. Templates define VMs only; Pigsty service roles stay in your playbook. --cidr moves the template to another /24 while keeping the host octets, and barn init full -o - prints it instead of writing a file.

Discovery

Commands that need a desired state look for an inventory in this order and use the first one that exists:

  1. The path given with -f.
  2. barn.yml, barn.yaml, pigsty.yml, then pigsty.yaml in the current directory. All four use the same format. A parse or validation error in the first match stops the command; Barn does not try the next name.
  3. The applied specification stored in BARN_HOME — only for plan, up, reload, recreate, and resize.
CommandsDesired state comes from
plan, up, reload, recreate, resize-f, then discovery, then the applied specification
validate-f, then discovery; an error if neither exists, even when a deployment exists
setup [template]-f, then discovery, otherwise a generated meta; a template argument and -f are mutually exclusive
init [template]Writes a new inventory without reading any state; --force overwrites an existing file
hosts installUses applied node names by default. An explicit -f reads that inventory and its vm_hosts mappings
start, stop, restart, status, destroy, purgeOperate on the applied deployment in BARN_HOME

The inventory must resolve to a regular file of at most 4 MiB; symlinks are followed, and relative share paths resolve beside the real file.

One Linux deployment per BARN_HOME

Barn keeps exactly one Linux deployment per BARN_HOME (default ~/.barn). The inventory is the desired state; BARN_HOME holds what is actually applied. Because a lab is defined by its fixed addresses rather than by the directory you work in, renaming or moving the inventory does not create a second deployment, and commands that use applied state (status, ssh, stop, start, destroy, …) work from any directory. Set BARN_HOME to an absolute path if you set it at all, so every working directory reaches the same deployment. The design rationale is in Design.

What Barn reads

An inventory needs a top-level all: group. Barn walks its hosts and nested children, and reads only node IPv4 keys, nodename, admin_ip, pg_cluster, pg_seq, node_admin_username, node_admin_uid, and the vm_* variables. It parses static YAML: Ansible inventory plugins, Jinja expressions, group_vars, and host_vars are not evaluated.

  • Other fields: Variables outside that list, such as pg_role, pg_version, repo_*, and node_packages, are ignored and never cause VM drift.
  • Inheritance: Values inherit all.vars → nested children.<group>.vars → host variables, deepest wins. A host-level list such as vm_disks replaces the inherited list entirely. If two sibling groups at the same depth give one node different values, set the variable on the host.
  • Repeated hosts: An IPv4 address listed in several groups is one node; its inherited variables merge.
  • Control node: admin_ip in all.vars names the control node. If it is omitted or matches no managed node, Barn picks the first managed node in traversal order (each group’s hosts before its children). Set admin_ip so reordering groups cannot move the control role.
  • Login account: All nodes share one login user matching [a-z_][a-z0-9_-]{0,31}, default dba. With dba, an explicit node_admin_uid must be 88; with a custom user, node_admin_uid only has to be an integer and the guest assigns the UID.
  • Skipped hosts: vm_skip: true marks a physical or external host. It may use a hostname or IPv6 key and does not count toward the managed /24; at least one managed node must remain. Skipping an existing node shows it as missing in plan without destroying it.
  • Strict vm_* namespace: Unknown vm_* keys (with a spelling suggestion), wrong types, Jinja templates, duplicate keys, and multi-document YAML fail with the line number and the rule violated. YAML anchors and << merge keys work: explicit keys win, then the first mapping in a merge sequence.

VM variables

VariableDefaultMeaning
vm_skipfalseSkip virtualization for this physical or external host
vm_imaged13 (new lab in 1.5.0)Image family, :channel reference, or image@version selector; see Image and architecture
vm_versionunsetNewest numeric version matching this prefix, such as 9 or 9.7
vm_archnativeDeployment-wide guest architecture; follows the host unless set to amd64 or arm64
vm_cpu1Base vCPU count; the effective count after scaling must be 1–256
vm_mem2048Base memory: bare integer in MiB, or a size string such as 8GiB (minimum 512MiB)
vm_scale1Positive integer multiplying CPU and memory only
vm_hosts[]Extra host /etc/hosts mappings, declared only in all.vars
vm_disk64Root disk capacity: bare integer in GiB, or a size string such as 64GiB
vm_disks[{path: /data}]Extra data disks; the default is one 128 GiB non-persistent disk at /data
vm_alias[]Extra names for guest /etc/hosts, SSH config, and optionally host /etc/hosts
vm_shares[]QEMU 9p host-directory shares on Linux and macOS hosts

An empty host mapping (10.10.10.10: {}) defines a complete VM with these defaults.

Bare integers mean MiB for vm_mem and GiB for disks. Size strings take a positive integer and a case-insensitive unit: 8G, 512m, 4gib, and 64GB all work. K/M/G/T and KiB/MiB/GiB/TiB are binary; KB/MB/GB/TB are decimal. Fractions (1.5GiB) and unitless strings ("8192") are invalid. up checks that the root disk is at least the base image’s virtual size.

Names and addresses

Each node’s name is the first of: explicit nodename, <pg_cluster>-<pg_seq>, or node-<last-octet>. Names must be unique, 1–63 characters of lowercase letters, digits, and hyphens, and must not start or end with -. vm_alias adds lowercase DNS names (dots allowed) that must differ from every node name and other alias. Keep an explicit nodename on every host: otherwise renaming pg_cluster turns an existing node into a missing old node plus a new one.

Every node gets two NICs: one for internet access through QEMU’s built-in NAT, and one on a fixed /24 so nodes reach each other at the addresses the inventory names. All managed nodes must share one RFC1918 /24: .1 is the host gateway, .2–.8 are reserved, and .9–.254 are available to nodes. Inside the guest, ip -br addr shows the inventory address on the fixed-IP NIC.

Resource scaling

vm_scale multiplies CPU and memory so you can size a whole lab up or down with one number. Barn resolves vm_cpu, vm_mem, and vm_scale independently through inheritance, then multiplies once:

CPU    = resolved(vm_cpu, default=1) × resolved(vm_scale, default=1)
Memory = resolved(vm_mem, default=2048 MiB) × resolved(vm_scale, default=1)
SettingsEffective CPUEffective memory
None12 GiB
vm_scale: 336 GiB
vm_cpu: 2, vm_scale: 366 GiB
vm_mem: 4GiB, vm_scale: 3312 GiB
vm_cpu: 2, vm_mem: 4GiB, vm_scale: 3612 GiB

Scales do not compound: a host’s vm_scale: 1 replaces a group’s vm_scale: 3. Scale is an integer from 1 to 256, subject to the 256-vCPU limit and memory overflow checks; quoted numbers, fractions, booleans, null, zero, and negative values fail. Base memory must still be at least 512 MiB. Root disks, data disks, and shares do not scale. The keys are exactly vm_cpu and vm_mem (vm_memory is not an alias).

Preview CPU or memory changes with barn plan -f pigsty.yml and apply them with barn resize -f pigsty.yml. These defaults changed in 1.2.0; inventories that omit them read differently after an upgrade from 1.1.0 (see Upgrade Barn). Commands that use applied state without an inventory keep the recorded resources.

Specification overrides

Six fields can also be set per command, so scripts and one-off experiments can change a lab without editing the file (1.2.0+; 1.1.0 has only --image and --arch, without environment variables).

Inventory fieldCLIEnvironment variableDefault
vm_image--image/-IBARN_IMAGEd13 (new lab in 1.5.0)
vm_arch--arch/-ABARN_ARCHnative
vm_cpu--cpu/-CBARN_CPU1
vm_mem--mem/-MBARN_MEM2048 MiB
vm_scale--scale/-SBARN_SCALE1
vm_disk--disk/-DBARN_DISK64 GiB
barn init full -C 2 -M 4GiB -S 2 -D 128GiB
barn plan -f barn.yml -S 3
BARN_SCALE=2 barn validate -f barn.yml -S 1

Each field resolves per node; the first source that sets it wins:

  1. CLI flag
  2. Non-empty environment variable
  3. Host variable
  4. Deepest child group
  5. Parent groups
  6. all.vars
  7. Default
  • CPU and memory are always bases, multiplied once by the final scale. -S 3 replaces the scale rather than multiplying it; add -S 1 to set exact CPU and memory.
  • CLI and environment values override host values on the selected nodes. Put common defaults in all.vars when host exceptions should stay in effect.
  • The inventory itself must still be valid: syntax, field types, and inheritance conflicts are checked as usual.
  • Whitespace-only environment values count as unset, and an invalid environment value shadowed by a flag is ignored: BARN_CPU=bad barn plan -C 2 uses 2. Suggested follow-up commands repeat effective environment overrides as explicit flags.
CommandOverridesEffect
init, template-generating setupAll sixWritten into the new inventory, defaults included; CPU and memory as bases plus scale
up that generates an inventory interactivelyAll sixSaved in the generated inventory
validate, plan, up, reload, recreateAll sixChange this run’s desired specification only; the YAML is not rewritten, so the next run against the file reports drift
resizeAll sixApplies CPU and memory changes and grows the root disk; -I/-A are only checked for consistency
setup reusing an inventoryNoneFlags are rejected and environment variables ignored
start, stop, restart, status, destroy, purgeNoneApplied state is used; environment variables are ignored

Image commands and barn mac also ignore the six variables; image info and image pull take their own -A. With no inventory, only applied state, --scale or BARN_SCALE requires -f; -C and -M then set absolute values with an implicit scale of 1.

--disk sets the absolute root capacity, which must be at least the base image’s virtual size: plan checks catalog metadata and creation checks the actual image again. It applies on creation, on explicit recreate, and to in-place growth with resize -D (BARN_DISK with resize only grows). Growth supports a last plain ext4/XFS root partition and never shrinks; see root disk growth. The default 128 GiB /data disk is separate.

Image and architecture

vm_image chooses the guest OS per node; vm_arch chooses one CPU architecture for the whole deployment. New labs in 1.5.0 default to Debian 13 (d13) on the host architecture. On Barn 1.4.0, barn init -I d13 writes the same image to a new inventory.

barn plan -I d13                 # Debian 13 using the environment, inventory, or host architecture
barn up -I d13 -A amd64          # amd64 Debian 13 for this invocation
barn plan -A native              # override the inventory architecture with the host's
barn init full -I d13 -A arm64   # save both choices in a new inventory

Precedence

OrderImage (per node)Architecture (whole deployment)
1--image/-I, on the selected nodes--arch/-A
2BARN_IMAGEBARN_ARCH
3vm_image and vm_version: host, then groups, then all.varsvm_arch
4Saved deployment default, or the embedded default for a new labnative: the host architecture

-I and BARN_IMAGE replace both vm_image and vm_version. A bare family name such as d13 leaves the architecture alone; -A native overrides the environment and inventory and follows the host again.

ArchitectureAliasesMeaning
native—Follow the current host; the default
amd64x86_64, x64x86-64 guest
arm64aarch64, a64ARM64 guest

Architecture-suffixed aliases

An image alias ending in a (arm64) or x/i (amd64), such as el10a, d13x, d12i, ea, ua, or da, carries its own architecture. For inventory commands:

  • From -I or BARN_IMAGE, the suffix sets the deployment architecture, overriding vm_arch.
  • In vm_image, the suffix takes precedence over vm_arch: native, the value generated templates write. A concrete vm_arch that names the other architecture fails validation, as do nodes whose suffixes disagree.
  • -A and BARN_ARCH must agree with every suffix still in effect: naming the other architecture, or native, fails with exit 2. A matching value such as el10a -A arm64 is accepted.

Image selection details

  • vm_arch belongs to the whole deployment: set it once in all.vars. Every managed node must resolve to the same architecture.
  • The catalog must offer the requested architecture. A missing variant is an error; Barn never substitutes another architecture.
  • When vm_image is omitted, existing labs use their saved default for existing and added nodes. A lone vm_version selects a version of that family. A new lab uses the binary’s embedded default even when a custom repository declares another default.
  • Built-in aliases are normalized while parsing the inventory: ubuntu → u26, rocky → el10, debian → d13. With a custom repository, write canonical family names in vm_image rather than reassigning built-in aliases.

vm_version keeps the family and the version prefix in separate fields:

barn.yml
vm_image: el9
vm_version: "9.9"

An exact catalog version wins; otherwise Barn matches dot-separated numeric prefixes and picks the highest (9.9 selects the latest 9.9.* build, 9 the latest 9.x release, and 9.10 sorts after 9.9). Use vm_version only with a bare family name in vm_image, without :channel or @version.

Keep or change a choice

  • Overrides on up, plan, reload, recreate, resize, and validate apply to that invocation only. To keep them, set all.vars.vm_arch and the node or group vm_image, and remove any superseded vm_version. init and template-generating setup write both into the new inventory; setup rejects -I/-A with an existing inventory.
  • Without an inventory file, lifecycle commands apply overrides on top of the saved specification. start and restart always use applied state.
  • Existing VMs are never converted. After you edit vm_arch or omit -A, up reports drift; switching the architecture requires recreate with all existing nodes selected. resize cannot change the image or architecture.
  • A guest whose architecture differs from the host runs under QEMU TCG emulation. On Linux, barn setup installs only the native emulator: install the target qemu-system-* binary and UEFI firmware first. See Runtime policy.

Data disks

Each node gets one 128 GiB /data disk by default, separate from the root disk, so test data has its own device and, with persistent: true, can outlive destroy and recreate. vm_disks replaces that list; vm_disks: [] creates a node with no data disks.

barn.yml
vm_disks:
  - path: /data
    size: 128
    fs: auto
    persistent: false
FieldDefaultMeaning
pathrequiredAbsolute mount path, normalized; spaces, Unicode, and shell punctuation are allowed. Simple paths keep their existing disk names; other paths get stable digest-based names. Identities must be unique per node; system directories and overlapping mounts are rejected
size128Capacity: GiB integer or size string
fsautoauto, xfs, or ext4. A blank auto disk gets XFS when the guest has mkfs.xfs, otherwise ext4; explicit xfs or ext4 requires that tool and never falls back. Healthy existing filesystems are mounted as-is
persistentfalseWhen true, ordinary destroy and recreate keep the disk image on the host, and the recreated node reattaches it while its identity and definition stay compatible

Data disks are test storage: up can reset a corrupted ext4 or XFS filesystem, persistent disks included. When Barn resets a data disk lists the exact rules.

Shares

vm_shares mounts host directories into Linux guests through QEMU Virtio-9p, for source code and build artifacts you edit on the host. It works on Linux and macOS hosts. For a native macOS guest, use the --share option of barn mac up or barn mac configure to mount a directory through VirtioFS.

barn.yml
vm_shares:
  - host: ./src
    guest: /src
    readonly: true
FieldDefaultMeaning
hostrequiredAbsolute path, ~/, a path relative to the inventory, or a directory symlink. Must exist, be accessible to the invoking user (ownership not required), and not overlap BARN_HOME
guestrequiredAbsolute mount point, normalized; spaces, Unicode, and shell punctuation are accepted, control characters are not
readonlytrueSet false for a writable share
  • Host QEMU and the guest kernel must support 9p; backend device limits apply.
  • Shares use the invoking user’s real filesystem permissions. Host sources may overlap and may have several readers or writers; coordinating concurrent writes is up to you.
  • Guest mount points must not overlap each other, data-disk mounts, system directories, or the login user’s .ssh directory. Do not put PostgreSQL data directories on 9p.
  • If the guest user cannot write a readonly: false share, Barn mounts it read-only with a warning and leaves host ownership alone; fix host permissions and re-run barn up to upgrade the mount.
  • Changing vm_shares on an existing node requires barn recreate. A missing host directory during up or start fails only that node; restart, reload, and recreate verify share paths before stopping any running VM.

Local service names

all.vars.vm_hosts (1.2.0+) publishes extra names, such as Pigsty service domains, in the host’s /etc/hosts alongside node names and vm_alias:

pigsty.yml
all:
  vars:
    vm_hosts:
      - {address: 10.10.10.10, names: [i.pigsty, m.pigsty]}
      - {address: 10.10.10.100, names: [pg-dns-service]}
  hosts:
    10.10.10.10: {nodename: meta}
barn hosts install -f pigsty.yml --json  # preview, including before VM creation
barn hosts install -f pigsty.yml --yes  # publish; sudo may ask for a password
barn hosts uninstall --yes
  • Each entry needs an address and a non-empty names list. Addresses must be canonical IPv4 in the inventory’s /24, within .9–.254 (.1–.8 are reserved for the host and DHCP).
  • Identical name/address pairs deduplicate. Names compare case-insensitively; one name with two addresses fails validation, as does a conflicting name already present outside the Barn-owned block.
  • The mappings touch only the host’s /etc/hosts: they do not change the VM spec hash, configure guest DNS, set up a VIP, or cause drift. up never publishes them.
  • hosts install without -f publishes only names and aliases from applied state and replaces the whole Barn block, dropping these service names; repeat the -f command to keep them.
  • An unchanged block needs no sudo. Wildcards, SRV records, and live primary discovery need a real DNS service.

Pigsty’s development bin/sandbox-dns extracts its portal, node, PostgreSQL, VIP, and MinIO names for this interface; see the migration audit.

Drift

Barn hashes each node’s resolved definition and compares it with applied state, so editing the inventory never changes a VM until you run the command that applies that kind of change:

ChangeApply with
New nodebarn up
CPU or memory, including vm_scalebarn resize <node>; keeps identity and disks
Larger vm_diskbarn resize <node>, or barn resize -D <size> <node> without editing; grow-only
Image, data disks, shares, or other VM definitionbarn recreate <node>
vm_arch, login user, or the /24barn recreate of the whole deployment
Node removed or set to vm_skip: trueShown as missing in plan; remove it with barn destroy <node>

barn up also starts stopped nodes and retries unfinished guest provisioning on running nodes without restarting QEMU. After barn update, a node whose definition is unchanged keeps its recorded base image. Creating or explicitly recreating a node resolves its selector against the active catalog.

Node selectors limit a command to the named nodes: plan node-1, up node-1, reload node-1, recreate node-1, and resize node-1 keep the applied definitions of unselected peers, even if the inventory edits or omits them. The whole inventory must still parse, and conflicts with applied addresses, aliases, control-node roles, or deployment-wide settings are still rejected; images for uncreated, unselected nodes are not resolved.

3 - CLI Contracts

Output modes, the JSON/YAML envelope, exit codes, prompts, lifecycle results, and recovery rules shared by every Barn command.

Every barn command follows the same output, prompt, and exit-code rules, so a script can handle all of them the same way. This page defines those rules; per-command syntax and flags are in the Command Reference, and native Mac VM contracts in Mac Reference.

barn [--json|--yaml] [-v|--verbose] <command> [flags] [node...]

Each command page lists its short aliases (barn st is barn status); the network group also answers to n and net.

Output modes

Results go to stdout and everything else to stderr, so redirecting stdout captures only the result.

Modestdoutstderr
Text (default)Results and follow-up hints (connect:, retry:, next:)Live progress, prompts, error: lines
--json or --yamlOne JSON or YAML document: the command’s report or a failure objectProgress and diagnostics
-v, --verboseUnchangedAdds bounded diagnostic logs

In text mode, an operation that runs for a second or longer on a terminal redraws one live table on stderr (NAME ADDRESS STATE MESSAGE, ITEM STATE MESSAGE, or IMAGE STATE MESSAGE) above a completion line ending in [DONE], [FAILED], or [CANCELLED]. When stdout and stderr are both terminals and --verbose is off, the finished table stays in place and stdout adds only the follow-up hints.

Two cases differ: logs --follow streams NDJSON with --json or a YAML document stream with --yaml, and structured interactive ssh sends the session to stderr and only its final report to stdout.

--json and --yaml are long-form only and mutually exclusive; BARN_OUTPUT sets the default. Presentation flags may come before or after the command but must precede the -- that starts a remote command. barn --json with no command returns suggested next commands in actions[].

Exit codes

Check the exit code first, then parse the output.

CodeerrorMeaning
0Success (including ready guests with non-fatal warnings[] or repairs[])
1runtimeOperation executed and failed (external tool, download, or guest failure)
2usageInvalid CLI syntax, missing inventory file, or invalid configuration/image selector
3capabilityHost lacks a required dependency, active Barn network, or privilege
4conflictOperation conflicts with current deployment state or another active barn process
5partialNode-level batch failure; inspect failures[] (successful peer nodes remain intact)
6resourceHost IP address, port, subnet, or disk path is already in use
7integrityDigest, catalog signature or signed revision, instance identity, or file ownership verification failed
130cancelledInterrupted by SIGINT/SIGTERM or interactive confirmation declined
  • ssh and exec return the remote command’s exit code verbatim, so text output, JSON exit_code, and the process status agree. 255 can mean either an OpenSSH transport failure or a remote command that exited 255.
  • Deployment lock: When another barn process holds the deployment, mutating commands wait up to 10 minutes while naming the holder, then exit 4 with reason: "deployment_busy". Read-only and access commands (status, ssh, exec, ssh-config, hosts) do not wait; status shows the last committed state and names the active operation in note.
  • Catalog trust: A missing or invalid catalog signature fails with reason: "catalog_signature"; a catalog that reuses an accepted or embedded revision number with different bytes fails with reason: "catalog_equivocation". Permission and I/O errors while reading a cached signature are runtime failures (exit 1).

Structured failures

With --json or --yaml, commands that have their own report schema — doctor, network, provision, lifecycle commands, and ssh/exec — write that report even when they fail; exec, for example, returns success, exit_code, stdout, and stderr. A command that fails before it has a report writes one failure object instead:

FieldPresentMeaning
errorAlwaysError class from the exit code table
messageAlwaysHuman-readable summary
reasonWhen knownStable snake_case cause for automation
nextWhen knownSuggested next command
operation_idWhen assignedCorrelates with barn logs --source events
commandAn external program failedname, argv, exit_status, signal, timed_out, stderr
failures, rolled_backExit 5 from a lifecycle batchFailed nodes and rolled-back preparations, as in Lifecycle results

Common reason values on Linux commands:

reasonerrorCause and usual next step
no_inventoryusageNo inventory in the current directory: barn init, or pass -f
unknown_nodeusageA selector is not a node name in the inventory or deployment
unknown_imageusageThe image selector is not in the active catalog
qemu_missingcapabilityQEMU is missing or unusable; next names the fix
network_absentcapabilityThe Barn network is not installed: barn setup
sudo_unavailablecapabilitysudo failed, or needs a password while stdin is not a terminal
no_deploymentconflictBARN_HOME holds no applied deployment: barn up
node_not_runningconflictThe node is stopped: barn start <node>
resize_requiredconflictDrift that barn resize applies
recreate_requiredconflictDrift that needs barn plan, then barn recreate <node>
nodes_removedconflictThe inventory omits existing nodes; see Lifecycle results
deployment_changedconflictApplied state changed during recreate preflight; review and retry
deployment_busyconflictAnother command held the lock for 10 minutes
interrupted_transitionconflictA node is still mid-transition after an interrupted command; run the next command
hosts_name_takenconflict/etc/hosts maps a Barn name outside the Barn-owned block
disk_fullresourceThe host disk ran out of space
image_integrityintegrityA cached or downloaded image failed verification

Errors in the command line itself, such as an unknown flag or a command group without a subcommand (barn image), exit 2 with error: "usage".

In text mode, a failure prints error: <message> on stderr, then the last stderr lines of any failed external program and a next: command when one is known. When a remote command under ssh or exec fails, only its own output appears, without an error: line. The design rationale is in CLI contracts.

Prompts and scripts

Commands that change the host or delete data ask for confirmation when stdin is a terminal, and never wait for input in a script:

Commandstdin is a terminalstdin is not a terminal
recreate, destroyLists the nodes to replace or remove and asks you to type the command name; anything else cancels with exit 130. --yes or --force skips the promptExit 2 unless --yes or --force is given (there is no -y)
setupShows the plan and asks onceRequires --yes, else exit 2; --dry-run previews and cannot be combined with --yes
network, hosts install/uninstallShows the privileged plan and asks (install defaults to yes, uninstall to no); with --json/--yaml it only previewsPrints the plan and exits 0 without applying; pass --yes, or check applied in the report
up, start, restart, reload with a host dependency or the network missingShows the host-preparation plan and asks once, as setup does; an interactive up with neither an inventory nor a deployment also generates metaReports what is missing; run barn setup --yes first

Privileged steps run through sudo, which may still ask for your password; when it needs one and stdin is not a terminal, the command fails with sudo_unavailable. On Linux, network uninstall keeps the global networkd unit state when other host links exist or exclusive Barn use cannot be established: the plan reports preserve_networkd, and the applied report explains the decision in checks.networkd.

barn purge never asks unless you pass --ask, which shows the nodes and deletion scope and accepts y/yes; n/no, an empty line, or EOF cancels with exit 130. It accepts no --yes, -y, or --force. With no deployment, purge and whole-deployment destroy succeed cleanly, and purge still removes retained persistent disks whose Barn ownership metadata is intact; unverifiable retained directories block deletion. If deployment state is missing, destroy --force --delete-persistent and destroy --force --purge direct you to barn purge.

Flag conventions

  • On Linux commands, -f means --file (except barn logs -f, which is --follow), -n means --no-wait (barn mac logs -n sets the line count), and -d means --dry-run.
  • Safety and repository flags are long-form only: --ask, --mirror, --force, --rollback, --remove, --allow-downgrade, --sudo, --delete-persistent, --purge.
  • -y exists only where a command’s option table lists it; on destroy and recreate, --yes is the same as --force.
  • Path arguments such as -f, --script, a local --repo, image import sources, and repo roots accept relative paths, ~/, and symlinks.
  • Specification flags (-I, -A, -C, -M, -S, -D) and their environment variables follow Specification overrides.

Lifecycle results

Without node arguments, lifecycle commands act on every managed node; ssh, exec, and per-node logs default to the prepared control node, or the first prepared node if the control node is not ready. Selectors are resolved node names such as meta, not IP addresses, group names, or vm_alias entries. Which inventory a command reads is defined in Discovery.

Lifecycle commands (up, start, stop, restart, reload, resize, recreate, status, destroy, purge) return one report:

FieldContents
nodes[]Per node: name, address, state (such as running or stopped), ready, image, cpus, memory_bytes, root_disk_bytes, runtime, guest_arch, accelerator, ssh_host, ssh_port, pid, error
nodes[].warnings[]Non-fatal guest problems, each with stage and detail
nodes[].repairs[]Recovery actions Barn completed, such as resetting a corrupted data disk
warnings[]Deployment-level warnings with code (ssh_config, time_sync, guest_metadata, event_log), message, detail, next
failures[]Failed nodes with node, stage, error, and optional reason
rolled_back[]Nodes whose uncommitted preparation files --rollback removed
resources[]Per node: base_cpu, base_memory_bytes, scale, root_disk_bytes, effective cpus and memory_bytes, and each value’s sources
operation_id, spec_hash, note, ssh_configEvent-log correlation, applied specification hash, concurrent-operation note, SSH fragment result

What each command changes is in Linux Lifecycle, and which change needs which command in Drift. When drift needs a destructive change, up and reload exit 4 (conflict) and point to barn plan and then barn recreate <node> or barn destroy <node>. A whole-deployment recreate refuses an inventory that omits an existing node before any VM stops (reason: "nodes_removed", exit 4): remove the node with barn destroy <node> or add it back. Barn checks the scope again under the destruction lock; if applied state changed meanwhile, recreate exits with reason: "deployment_changed".

Destroying the control node makes the first remaining node the control node. Point admin_ip at it and run barn up to install its control SSH access (--no-wait defers this); until then, an inventory that still names the deleted node as control is role drift, which up refuses. To bring the old node back, add it as a regular node. Barn refuses, before deleting anything, to destroy the control node when the successor has an unfinished prepare record that cannot be completed, and names the successor.

Planning

barn plan is read-only and exits 0 even when its action is resize, recreate, or blocked-removal. Scripts should read action, the create, resize, recreate, start, and missing arrays, and the optional blocked explanation. Plans never download images; catalog images need only local metadata, while local-* images are also checked with qemu-img.

Readiness

Barn reads /var/lib/barn/ready.json over management SSH. A Linux guest is ready when its node name, generation and spec hash match the expected values. During startup on up, start, restart, reload, and recreate, Barn also corrects guest clocks more than 2 seconds off the host, reporting a failure as a time_sync warning. Non-fatal problems go to nodes[].warnings and completed recovery actions to nodes[].repairs; the command still exits 0. Re-running barn up retries unfinished guest setup on running VMs without restarting them, and gives existing guests the current recovery helper.

--no-wait returns once QEMU is running and defers SSH readiness, clock correction, data-disk recovery, and guest /etc/hosts updates to the next barn up. Which disk problems Barn repairs and which it only reports is described in Storage.

Node failures

When some nodes fail in a batch, Barn keeps the nodes that succeeded, exits 5, and summarizes each failure as N of M node(s) failed: <node> (<stage>: <error>); .... Stages include prepare, start, readiness, bootstrap, guest-setup, stop, and status. For readiness or bootstrap failures, read barn logs <node> and see A node did not become ready.

Status

barn status reads recorded state plus live QEMU process identity: running means the process is alive, not that guest SSH answers. It flags TCG emulation, and on Apple Silicon appends mac: <names>; barn mac ls when Mac VMs exist. --verbose adds forwarded SSH ports, architecture, accelerator, and QEMU PID. A degraded node, including an online resize interrupted after hot-plugging (stage: "resize", reason: "resize_incomplete"), still lists its healthy peers, fills failures[], and exits 5.

SSH configuration

up and recreate rewrite Barn’s host SSH fragment (~/.ssh/barn_config), guest /etc/hosts, and control-node SSH entries; start and restart refresh SSH aliases; per-node destroy removes that node’s entry; whole-deployment destroy removes the fragment. If ~/.ssh/config cannot be updated, or is a symlink or hard link (which Barn never edits), Barn still writes ~/.ssh/barn_config, prints the Include line to add yourself, records an ssh_config warning, and exits 0; barn ssh keeps working. On the control node, Barn-managed entries accept replacement host keys without writing known_hosts, so recreated nodes stay reachable, and your own SSH entries are kept.

Lifecycle concurrency

up, start, stop, restart, reload, recreate, destroy, and purge work on up to max(1, logical CPUs - 2) nodes at once (1.2.0+; 1.1.0 used at most four workers). --parallel/-p changes that for one invocation:

barn up -p 0                      # all selected nodes at once
barn up --parallel 8
barn start -p 1                   # serial
barn restart meta node-1 -p 2

The limit applies to disk preparation, startup, and shutdown; state commits and artifact removal keep their order, and disk preparation finishes before startup begins. A startup worker stays busy until its guest passes SSH readiness, or with --no-wait until QEMU starts and its process identity is verified. Values above 16 are accepted, values above the node count add no workers, negative values are rejected, and suggested retry commands keep the value, including 0. provision --parallel has its own default of 1.

Root disk growth

barn resize -D 128GiB meta
BARN_DISK=128GiB barn resize meta

-D is an absolute target. Growth needs downtime: running nodes return to running, and stopped nodes boot temporarily for checks and expansion, then stop again. Repeating a completed target changes nothing and does not restart the VM; a smaller target fails. The root must use 512-byte logical sectors and a last plain ext4/XFS partition in a GPT or primary MBR layout; LVM, encrypted devices, later partitions, and missing guest tools fail before the image is modified. Root data, VM UUIDs, and SSH keys are kept; data disks are not resized.

Barn records recovery stages and checks image, guest disk, partition, and filesystem sizes before finishing. After a failure, status shows a root-resize warning: fix the reported problem and repeat the same resize -D target. A grown image is never shrunk to undo an incomplete expansion. Update vm_disk to keep the new size, or the next run reports drift. Implementation and measurements: root growth acceptance.

SPEC display

Node tables show effective CPU and memory in a SPEC column such as 1c2g, 2c4g, or 8c16g: c is vCPUs and g is GiB, so 1536 MiB is 1.5g and 512 MiB is 0.5g. Memory that is not a whole number of MiB shows its exact byte count with b, and an unknown specification shows -. Plans show changes as 2c4g → 4c8g and root capacity in a separate ROOT column.

status and completion results show applied resources; plan, validate, and setup show desired ones. When scale is not 1, output explains the base, multiplier, result, and sources; --verbose explains it at scale 1 too. JSON keeps numeric CPU counts and byte sizes in resources[], so scripts never parse SPEC. The flags that set these values are in Specification overrides.

Interruption and recovery

  • Cancellation: On cancellation Barn sends SIGTERM to the external program it is running (sudo forwards it to the privileged command) and waits at most 10 seconds for that process and its inherited output pipes. Descendants that ignore SIGTERM need outside supervision.
  • Fault isolation: During up or start, a missing host share or a failed new-node preparation affects only that node; independent stopped nodes still start, and the command exits 5 with a retry command that keeps your -f, --repo, and other flags.
  • Interrupted transitions: A QEMU PID reused by an unrelated process marks the node stopped; a stop interrupted while the VM kept running marks it running. After an online resize interrupted mid-change, status reports resize_incomplete: retry barn resize <node> or run barn restart <node>. Other interrupted transitions print the recovery command (destroy resolves them directly), and the next run after a failed initial up rolls back uncommitted journal artifacts automatically.
  • Event log: setup and the lifecycle run that follows share one operation_id. Even if setup fails before a deployment exists, barn logs --source events --json shows the bounded phase log, without sensitive arguments or credentials; setup --dry-run writes none.
  • Retained persistent disks: Disks left by a previously removed node do not block destroying the remaining nodes; delete them with destroy --delete-persistent or purge.
  • macOS setup: setup finishes Homebrew discovery or installation and the pinned socket_vmnet download before asking for administrator privileges, so a slow download cannot expire an earlier sudo token and a failed download never prompts for a password.

Logs and environment

barn logs reads the guest serial console by default; --source qemu selects QEMU diagnostics and --source events the deployment-wide event log. --follow streams raw bytes in text mode, NDJSON with --json, and YAML documents with --yaml. QEMU argv appears only with --verbose.

Environment variablePurpose
BARN_HOMEPrivate state directory (default ~/.barn), one Linux deployment each; accepts relative paths, ~/, and directory symlinks, but not / or the home root. Prefer an absolute path across working directories
BARN_IMAGE/BARN_ARCH/BARN_CPU/BARN_MEM/BARN_SCALE/BARN_DISKVM specification overrides; CLI takes priority. Read only by commands accepting each field; see specification overrides
BARN_REPODefault image repository URL or path; overridden by --mirror and --repo
BARN_OUTPUTDefault output format (text, json, or yaml); overridden by --json/--yaml
BARN_VERBOSEBoolean default for diagnostic output; overridden by -v/--verbose
BARN_VMNET_ARCHIVEPath to a local pinned socket_vmnet archive for macOS setup; accepts relative paths, ~/, and symlinks (SHA-256 verification still applies)
NO_COLORAny non-empty value disables ANSI color output

An invalid BARN_OUTPUT or BARN_VERBOSE makes every command exit 2 (usage) unless the matching flag overrides it; --help always works.

SSH passthrough and completion

barn ssh and barn exec take Barn flags and an optional node name, then --, then the remote command, and exit with the remote command’s status. ssh hands the guest shell one string; exec passes the program and its arguments unchanged. The full rule, with examples, is in Remote commands and --.

barn completion bash|zsh|fish|powershell prints a completion script (for Bash, reload it after upgrades with source <(barn completion bash)). It completes commands, aliases, templates, image aliases, enumerated flag values, YAML files for -f, and node names from the current inventory or applied state, and stops suggesting Barn flags after --.

4 - Mac Runtime Reference

What a barn mac machine owns, how it is networked, and the JSON results, failure reasons, and files that scripts rely on.

barn mac runs named macOS virtual machines on an Apple Silicon Mac, alongside the Linux lab but separate from it. This page defines what scripts and agents depend on: what each machine owns, how it is networked, what the commands return, how they fail, and where state lives.

Per-command syntax and options are in the macOS Command Reference; the walkthrough is macOS Virtual Machines.

barn [--json|--yaml] [-v|--verbose] mac <command> [flags] [name...]

Host and runner

Barn drives Apple’s Virtualization framework through Barn.app, the native macOS app bundle that ships with the Apple Silicon release and the Homebrew formula (install). The CLI and the app must come from the same build: before any VM operation the CLI checks that the app’s runner speaks protocol 2, and barn mac doctor also verifies the runner’s local code signature.

  • Run barn mac as the logged-in desktop user. Commands that talk to the runner reject root with mac_root, and a host that is not Apple Silicon on macOS 27 or later with mac_host_unsupported. Disk space and the two-VM limit are under requirements.
  • On Linux and Intel Macs, barn --help hides mac. Commands that only read local state, such as barn mac image ls, work without the runner.
  • barn mac with no subcommand runs barn mac ls.
  • The CLI looks for the runner relative to its own resolved binary path, covering the app bundle (Barn.app/Contents/MacOS/barn-mac-runner), the pkg installer, and Homebrew libexec layouts. BARN_MAC_RUNNER overrides the search with an absolute, relative, or ~/ path.

Machines

A machine is a named macOS VM with its own copy-on-write disk cloned from a shared base image, its own private network and fixed address, an administrator account with passwordless sudo, and its own SSH keys. Machines never join the Linux lab or read its inventory, and Linux destroy and purge leave them alone.

Names are 1–32 characters: lowercase letters, digits, and internal hyphens, starting with a letter (mac1, dev, build-2). mac1 is the default name.

SettingNew machine defaultChange it with
CPUs4configure --cpu, while stopped
Memory8 GiBconfigure --memory, while stopped
Shared foldersnoneconfigure --share / --unshare, while stopped
Subnetfirst free /24configure --subnet, while stopped
Clipboard synconconfigure --clipboard, anytime; applies at the next start
Disk capacitythe prepared base’s capacity, or 100 GiB for the first basefixed
Administrator accountyour host macOS username, or barn if that is not a valid account namefixed
macOS buildthe default baserecreate --update (erases the disk)

Disk capacity and the administrator account are fixed for the machine’s lifetime and survive recreate; create a new machine to change them. Value ranges and syntax are in barn mac up and barn mac configure.

  • Administrator account: passwordless sudo, Ed25519 SSH key authentication, automatic desktop login, and Remote Login enabled. SSH password authentication is off. A random local password, needed at the lock screen and in GUI administrator prompts, is saved in the machine’s password file (mode 0600) and printed by barn mac password.
  • Hostnames: the guest ComputerName is <name> and LocalHostName is barn-<name> (reachable as barn-<name>.local).
  • Shared folders: one VirtioFS device mounts every share at /Volumes/My Shared Files/<name> in the guest. Each host source must resolve to an existing directory; symlinks are followed. Share names may contain spaces and Unicode and must be valid UTF-8 of 1–255 bytes, other than . or .., without / or ASCII control characters. configure --share with an existing name replaces that share’s path and mode.
  • Clipboard sync: plain text up to 1 MiB is synced over the machine’s SSH connection whenever its desktop window gains or loses focus. Pasteboard items marked concealed are skipped.
  • Host limit: Apple runs at most two macOS VMs at a time per Mac, counted across all apps and including an in-progress base installation (requirements). Starting a third fails with mac_vm_limit and names a machine to stop.

Networks

Each machine gets its own private /24, so its address stays the same across restarts and does not collide with another machine or the Linux lab. The machine’s runner creates the network with Apple’s shared-mode vmnet API when the machine starts and tears it down when it stops, without root or a background daemon.

ItemValue
SubnetFirst free /24 from 10.10.20.0/24 through 10.10.59.0/24 that overlaps neither a host route nor another machine, or an explicit --subnet
Gateway.1, on the Mac host
Guest IP.10, a vmnet DHCP reservation for the machine’s MAC address
ReachabilityHost-to-guest routing and outbound NAT; no LAN bridging and no inbound port forwards

If a route added later, such as a VPN, overlaps a machine’s saved subnet, start refuses with mac_subnet_in_use. Run barn mac configure NAME --subnet auto to move it to a free subnet. SSH trust survives the move because Barn pins the guest host key to barn-mac-<instance_id>, not to the IP address.

macOS Local Network privacy can block a third-party terminal or IDE from reaching the guest subnet, usually as No route to host. Allow that app under System Settings → Privacy & Security → Local Network. barn mac ssh and exec are unaffected: they run /usr/bin/ssh, and Barn’s own SSH transport goes through /usr/bin/nc, both Apple system binaries.

SSH and exec

barn mac ssh and barn mac exec connect with the machine’s own key and pinned host key and return the remote command’s exit status. They differ in how they hand the command to the guest:

  • ssh joins the arguments after -- into one command string for the guest shell, as plain ssh does. Without a command it opens an interactive shell.
  • exec passes the program and each argument separately, so spaces, quotes, and empty arguments arrive intact. It requires a command. Wrap pipelines, redirection, and compound commands in sh -c '...'. For compatibility exec also accepts a single command string as shell shorthand; new scripts should pass separate arguments or an explicit sh -c.
barn mac ssh dev
barn mac ssh dev -- 'sw_vers; id'
barn mac exec dev -- sw_vers
barn mac exec dev -- printf '<%s>\n' 'a b' ''
barn mac exec dev -- sh -c 'sw_vers; id'
barn --json mac exec dev -- sh -c 'echo out; exit 3'

Argument rules for both commands:

  • A remote command always follows --, and its first argument must not be empty. Interactive barn mac ssh dev needs no separator.
  • Before --, pass Barn flags (--json, -v, --help) and at most one existing machine name; omit the name to select the default machine. Everything after -- belongs to the guest command.
  • An unknown machine name or invalid arguments exit 2 (usage) before any connection is attempted, with barn mac ls as the next step.
  • --json needs a remote command; an interactive shell has no JSON form.

JSON output

Every barn mac command except interactive ssh supports --json and --yaml. The result goes to stdout; progress goes to stderr.

ls

In this sample, barn mac image update has made 27.2.1 the default base (base), while mac1 still runs the 27.0 base it was cloned from (machines[0].image).

{
  "schema_version": 2,
  "root": "/Users/alice/.barn/mac",
  "prepared": true,
  "base": {"version": "27.2.1", "build": "26B131", "base_id": "26B131-c8269f7cdc99451b71db4104"},
  "machines": [
    {
      "name": "mac1",
      "kind": "macos",
      "state": "running",
      "ready": true,
      "ssh": "ready",
      "address": "10.10.20.10",
      "address_stable": true,
      "ssh_host": "10.10.20.10",
      "ssh_port": 22,
      "user": "alice",
      "image": {"version": "27.0", "build": "26A428", "base_id": "26A428-e16af589f4b705ca397f5b21"},
      "cpus": 4,
      "memory_bytes": 8589934592,
      "disk": {"capacity_bytes": 107374182400, "allocated_bytes": 1202647040},
      "network": {"subnet": "10.10.20.0/24", "gateway": "10.10.20.1", "address": "10.10.20.10"},
      "shares": [{"name": "src", "host": "/Users/alice/src", "guest": "/Volumes/My Shared Files/src", "readonly": false}],
      "clipboard": true,
      "pid": 2545,
      "instance_id": "b1482ffc-2da7-45d9-ace5-c5f3193a9172",
      "warnings": []
    }
  ],
  "running": 1,
  "limit": 2
}
FieldValues
baseThe default base for new machines
machines[].imageThe base this machine was cloned from
stateprepared (created, first boot not completed), starting, running, stopping, stopped, unknown
readytrue when this check verified guest SSH and passwordless sudo
sshready, pending (first boot in progress), unavailable, offline, unchecked
observedPresent when the running guest reports a macOS build different from its base
window_visiblePresent while the desktop window is open
error, warningsThe last failure recorded for the machine, and SSH issues found during this check
running, limitMachines running in this BARN_HOME, and Apple’s per-host limit; the limit itself is enforced across the whole Mac

Lifecycle results

Single-machine commands (up, restart, open, recreate, configure) return one result object. Batch commands (start, stop, destroy) return {"machines": [...]}, even for one name. When a batch partly fails, the result lists both the machines that succeeded and the failures, and the command exits 5.

{"name": "mac1", "action": "created", "state": "running", "ready": true,
 "address": "10.10.20.10", "user": "alice", "version": "27.2.1", "build": "26B131"}
FieldValues
actioncreated, started, running (already running), restarted, recreated, opened, configured, stopped, powered_off, already_stopped, destroyed, absent
forcedtrue when the VM was powered off rather than shut down: the two-minute shutdown in stop or restart timed out, or stop --force was used (action: powered_off)
windowtrue when the desktop window was opened
warningsNon-fatal notices, such as a clipboard change that takes effect at the next start

Other commands:

  • exec --json: the same schema as Linux barn exec --json (node, exit_code, stdout, stderr).
  • password --json: name and password, or {"name": "mac1", "copied": true} with --copy.
  • ssh-config --json: fragment when printing; installation status with --install or --remove.
  • logs --json: name and logs.
  • doctor --json: ok and checks[] (name, ok, detail, optional next); exits 3 if any check fails.

Failures

A failed command reports a stable reason and, when there is one, a next command to run. Exit codes follow the CLI exit code table; ssh and exec pass the remote command’s exit status through.

ReasonExitMeaning and next step
mac_host_unsupported3Host is not Apple Silicon or is running macOS older than 27
mac_runner_missing3Barn.app / native runner is not installed alongside the barn CLI
mac_runner_protocol3Installed Barn.app uses a different runner protocol version; reinstall matching CLI and app builds
mac_root2Invoked as root; run as the logged-in desktop user without sudo
mac_download_consent2Non-interactive macOS download requires --yes (or supply a local file with --ipsw)
mac_machine_absent4Named VM does not exist; create it with barn mac up NAME
mac_not_initialized4VM has not finished its first boot; complete initialization with barn mac up NAME
mac_not_running4ssh or exec called on a stopped VM; run barn mac start NAME
mac_running4Requested configuration change requires the VM to be stopped; run barn mac stop NAME
mac_configuration_conflict4up flags differ from the existing VM; run the suggested configure or recreate command
ssh_config_linked4~/.ssh/config is a symlink or hard link; add the printed Include line manually
mac_vm_limit6Two macOS VMs are already running on this Mac; stop the reported VM first
mac_subnet_in_use6A host route overlaps the VM’s subnet; run barn mac configure NAME --subnet auto
disk_full6Insufficient free disk space to download or install the macOS base image
mac_machine_damaged7An initialized VM slot is missing its disk or identity files (the slot directory is preserved for inspection)
mac_readiness_interrupted130barn mac stop interrupted a first-boot SSH readiness wait

Files

$BARN_HOME/mac

  • config.jsonInstallation identity, default base image, and ssh_config_off flag
  • images/
    • ipsw/
      • <build>.ipswCached Apple restore image (.partial while downloading)
      • <build>.ipsw.jsonRestore image metadata and digest
    • base/
      • <id>/Read-only, unbooted macOS base image bundle
  • slots/
    • <name>/
      • state.jsonMachine record (schema 2)
      • disk.asifCopy-on-write APFS disk layer cloned from the base image
      • machine-id.binApple Virtualization machine identifier
      • auxiliary-storage.binNVRAM / boot auxiliary storage
      • id_ed25519Per-VM SSH private key
      • id_ed25519.pubPer-VM SSH public key
      • known_hostsPinned guest host key under barn-mac-<instance>
      • passwordGenerated guest login password (mode 0600)
      • runner.logPer-VM runtime log read by barn mac logs
  • runtime/Global state lock and per-machine operation locks

Outside $BARN_HOME/mac:

  • Control sockets: /tmp/barn-mac-<uid>-<hash>/.
  • OpenSSH fragment: barn mac ssh-config manages ~/.ssh/barn-mac_config and a # barn-mac:include block in ~/.ssh/config, independent of the Linux # barn:include block. barn mac ssh-config --remove sets ssh_config_off in config.json, so lifecycle commands stop re-adding the Include block until you run barn mac ssh-config --install.
  • Desktop preferences: window positions live in ~/Library/Preferences/com.pgsty.barn.plist (0.9.0 used ~/Library/Preferences/io.pgsty.barn.mac-runner.plist).
  • Inside the guest: Barn writes ~/.ssh/authorized_keys, /private/etc/sudoers.d/80-barn, and /etc/ssh/sshd_config.d/000-barn.conf, sets ComputerName and LocalHostName, and disables idle sleep with pmset.

Recovery state

An interrupted recreate leaves a recovery journal, and barn mac image prune keeps every base that journal still references until recovery cleanup finishes. While a journal is malformed, barn mac image ls, the space estimate in barn mac doctor, and pruning fail until it is repaired, and every image stays in place. If one machine’s state cannot be read, barn mac ls fails as a whole, while commands that name the other machines keep working.

5 - Images

Signed catalogs, built-in aliases, repository selection, local cache verification, imports, and pruning.

Barn resolves Linux guest images from a static catalog and immutable qcow2 artifacts. Official and HTTP repositories require ML-DSA-87 catalog signatures, while explicitly selected local directory and HTTPS repositories may be unsigned. You can activate newer image catalogs with barn update without replacing the barn binary; the binary defines the trusted signing public keys and qcow2 safety rules.

Warning

el7 (CentOS Linux 7.9) is an EOL deprecated compatibility image. The catalog also marks el8 (Rocky Linux 8) and u22 (Ubuntu 22.04 LTS) as deprecated as support is phased out. Prefer el9, el10, d12, d13, u24, or u26 for new labs.

Aliases and pull order

Official catalog 2026120302 selects Debian 13 (d13:stable) on the host architecture by default. It covers nine distribution families and 17 stable artifacts, with 35 artifacts including retained versions. Only el7 is amd64-only. Every other family provides both amd64 and arm64.

Both public mirrors published this catalog on December 3, 2026. Run barn update to activate it and barn image info d13 to see the selected version. Barn 1.4.0 verifies the Minisign signature and still needs barn init -I d13 to generate a Debian 13 inventory. Barn 1.5.0 verifies the ML-DSA-87 signature on the same bytes. Debian image acceptance · Platforms and Limits

Familystable in 2026120302Family aliasesArchitecture aliases (arm64 / amd64)
d1320261130.2678.1d, debian, debian13, trixied13a, da / d13x, d13i, dx, di
d1220261130.2678.1debian12, bookwormd12a / d12x, d12i
el77.9.20221112.0c7, centos7, centos79— / el7x, el7i, c7x, c7i
el88.10.20240528.3rocky8el8a / el8x, el8i
el99.9.20261112.1rocky9 (rocky in 1.2.0)el9a / el9x, el9i
el1010.3.20261112.1e, el, rocky, rocky10el10a, ea, ela / el10x, el10i, ex, ei, elx, eli
u2220261109.0.1ubuntu22, ubuntu2204, jammyu22a / u22x, u22i
u2420261017.0.1ubuntu24, ubuntu2404, noble (ubuntu in 1.2.0)u24a / u24x, u24i
u2620261108.0.1u, ubuntu, ubuntu26, ubuntu2604, resoluteu26a, ua / u26x, u26i, ux, ui

Unversioned family shorthands point to the newest mainstream family (e/el/rocky → el10, u/ubuntu → u26, d/debian → d13; in Barn 1.2.0, rocky mapped to el9 and ubuntu mapped to u24). Appending a selects arm64, and appending x or i selects amd64—accepted everywhere an image reference is read (image info/pull, --image/-I, BARN_IMAGE, and vm_image, including :channel or @version). For image info/pull, an explicit -A must name the matching architecture. Inventory commands also honor BARN_ARCH. An inventory’s default vm_arch: native defers to an architecture-suffixed vm_image.

Distribution notes:

  • u22, u24, and u26 are Ubuntu 22.04, 24.04, and 26.04 LTS; d12 and d13 are Debian 12 and 13. Barn’s image recipe builds them from the distributions’ cloud images: the image ships a dba user (UID/GID 88), XFS userspace tools are present, and en_US.UTF-8 is available while C.UTF-8 stays the default locale.
  • el7 is CentOS Linux 7.9 (amd64 BIOS), and el8, el9, and el10 are Rocky Linux (amd64 and arm64 UEFI). All three Rocky families go through Barn’s recipe (dba, UID/GID 88). The current el10 images also include signed kernel modules required by Docker’s default bridge networking, iptables firewall rules, and overlay filesystem. el7 remains the distribution’s unmodified cloud image.
  • cloud-init configures accounts and networking on first boot for every image.
  • After a catalog refresh, existing nodes with unchanged definitions use their recorded image, even if the version has left the catalog. New nodes and explicit barn recreate operations resolve the selected image against the active catalog. Catalog rotation tests
AliasDistributionArchitecturesBootStatus
el7CentOS Linux 7.9 / 2211amd64BIOSdeprecated
el8Rocky Linux 8.10amd64, arm64UEFIdeprecated
el9Rocky Linux 9.9amd64, arm64UEFIsupported
el10Rocky Linux 10.3amd64, arm64UEFIsupported
d12, d13Debian 12 / 13amd64, arm64UEFIsupported
u22Ubuntu 22.04 LTSamd64, arm64UEFIdeprecated
u24, u26Ubuntu 24.04 / 26.04 LTSamd64, arm64UEFIsupported
barn update
barn image list
barn image info d13
barn image info d13:stable
barn image info el9@9.9
barn image pull d13@20261123.2671.1
barn image pull d13 --arch arm64

barn image list prints every version and architecture in the active catalog along with registered local-* aliases. barn image info defaults to the host architecture (like image pull, unless an architecture-suffixed alias is given) and can inspect uncached catalog metadata without QEMU; if a local cache file is present, info also runs qemu-img verification on it. Neither list nor info downloads image files.

Catalog status values indicate support tier (supported, testing, deprecated, or unknown); non-supported images still boot normally and emit a status warning.

When pulling an image, Barn executes four steps:

  1. Load the active catalog — Reads the selected repository’s active local catalog once for the command (either the binary’s embedded catalog or the revision last activated for that repository by barn update or barn image sync).
  2. Resolve the selector and architecture — Resolves image[:channel] or image@version-prefix (or the active catalog’s default if omitted) and the target architecture. Bare aliases in standalone image pull default to the host, while architecture-suffixed aliases select arm64 or amd64 directly; lifecycle commands use vm_arch (or an architecture-suffixed alias), also defaulting to the host when unset. --arch/-A overrides non-pinned choices and rejects conflicting pinned aliases; see configuration precedence.
  3. Verify the local cache — Reuses an existing cached file immediately if its byte size, SHA-256 digest, and qemu-img structural checks all pass.
  4. Download with resume and digest checks — Downloads the artifact from the selected repository with automatic retries and HTTP range resumption, verifying the final size, SHA-256, and qcow2 header before moving it into the cache. The two official mirrors (https://repo.pigsty.io/barn and https://repo.pigsty.cc/barn) can fall back to each other during artifact downloads, while custom --repo sources download exclusively from the specified root. Upstream URLs recorded in the catalog serve as provenance metadata only.

Repository selection precedence is --repo → --mirror (https://repo.pigsty.cc/barn) → BARN_REPO → compiled default (https://repo.pigsty.io/barn). Both official endpoints require valid ML-DSA-87 catalog signatures.

Barn tracks each repository separately under $BARN_HOME/images/manifests/. Pass the same --repo or set BARN_REPO when using its images. A freshly built local directory works immediately. For a custom HTTPS repository, run barn update --repo <url> to activate its catalog.

Barn automatically restores read-only permissions (0444) on verified cache files. If an unreferenced cached file fails verification, Barn renames it to .corrupt-<timestamp> before re-downloading; if a VM still uses that base image, Barn leaves the file in place and reports an integrity error.

Runtime policy

When guest and host architectures match, Barn uses hardware virtualization (Apple HVF on macOS, KVM on Linux) with one built-in exception: the stock Rocky Linux 8 arm64 kernel uses a 64 KiB page size that Apple HVF does not support, so Barn automatically runs el8 on Apple Silicon under same-architecture QEMU TCG and flags tcg in status output. Cross-architecture guests (after resolving vm_arch and any command override) also run under TCG; for amd64 guests on arm64 hosts, Barn pins TCG to a single translation thread to preserve x86 memory ordering.

The ARM64 TCG runtime uses cortex-a72 to avoid firmware hangs with the max CPU model in some QEMU/AAVMF combinations. ARM64 guests on Linux x86-64 have passed an actual Barn boot and SSH check. Barn’s catalog and runtime currently accept only amd64 and arm64; other architectures offered by a distribution or QEMU still require Barn integration before use with barn up.

el7 is supported only on native linux/amd64. On Linux hosts, barn setup installs the native QEMU package set; before booting a foreign vm_arch with up or recreate, install the target architecture’s qemu-system-* emulator and UEFI firmware (barn plan can resolve catalog images without them, though local-* imports still require qemu-img).

barn image pull d13 --mirror
barn image pull d13 --repo https://mirror.example/barn
BARN_REPO=/absolute/local/repository barn up

Trust and verification

Barn 1.5.0 checks catalog.json.sig. Barn 1.4.0 reads catalog.json.minisig over the same bytes. Mirror and key instructions

Release binaries embed the official ML-DSA-87 public key (private signing keys live outside the source repository). Catalog activation rejects unknown signing keys, malformed JSON, conflicting content at the same revision number (equivocation), and revisions lower than the repository’s highest accepted revision unless --allow-downgrade is passed to barn image sync. A missing required signature, an invalid signature, or a revision with conflicting bytes produces exit code 7 (integrity). A new trusted signature over identical catalog bytes is accepted, which also repairs a damaged cached signature.

Every cached or imported image must be a standalone qcow2 file matching its declared byte size and SHA-256 digest, with no backing file, external data file, encryption, or unknown incompatible qcow2 feature bits. Barn marks verified base images read-only and creates copy-on-write overlay disks for each VM node.

barn update
barn image sync --repo https://repo.example/barn \
  https://repo.example/barn/catalog.json
barn image sync --repo /srv/barn --allow-downgrade /srv/barn/catalog.json
barn image reset --repo /srv/barn
  • barn update fetches, verifies, and activates the current catalog from --repo or --mirror.
  • barn image sync activates a catalog from an explicit URL or file path (for unsigned custom repositories, the source path must be <repo>/catalog.json) and supports --allow-downgrade.
  • barn image reset reverts the active catalog for --repo (or default repo) back to the binary’s embedded catalog while keeping the recorded highest-revision watermark intact.

Static repository format

A static Barn image repository uses the following directory layout:

/srv/barn

  • repo.yamlOptional image definitions and policy (schema 1)
  • catalog.jsonGenerated runtime image catalog with digests and sizes (schema 3)
  • catalog.json.sigML-DSA-87, required for official and HTTP repositories
  • catalog.json.minisigCompatibility sidecar for official 1.4.0 clients
  • images/
    • <image>-<version>-<arch>.qcow2Immutable qcow2 image artifacts

Without repo.yaml, Barn reads <image>-<version>-<arch>.qcow2, selects the highest version of each family for stable and uses UEFI. An optional repo.yaml (schema: 1) declares defaults, aliases, channels, versions, architectures, boot modes, support status, source_user (for example, rocky upstream or dba after official normalization), and optional upstream provenance URLs—without manual checksums or byte sizes. barn repo build inspects the qcow2 files and generates catalog.json (schema: 3) with each variant’s filename, SHA-256 digest, file size, and virtual disk capacity.

repo.yaml
schema: 1
revision: 1
defaults: { image: d13, channel: stable, arch: native, boot: uefi }
images:
  d13:
    aliases: [debian13, trixie]
    channels: { stable: "1" }
    versions:
      "1":
        status: unknown
        variants:
          amd64: {}
          arm64: {}

When a variant omits file, Barn expects images/<image>-<version>-<arch>.qcow2 (for example, images/d13-1-amd64.qcow2 and images/d13-1-arm64.qcow2).

Repository management rules (barn repo scan|build|verify /absolute/repo):

  • Repository roots accept relative paths, ~/, and directory symlinks. The root and images/ may be shared writable directories. repo.yaml may link to a non-empty regular file up to 4 MiB. Artifact entries remain regular files; catalog.json output symlinks are not overwritten.
  • Boot mode inherits along variant → family → defaults.boot; status inherits along variant → version → unknown. Every family must define the default channel pointing to an existing version, and family/alias names must be unique and cannot start with local-. Avoid reassigning built-in aliases (ubuntu, debian, rocky, etc.) to different families, because inventory parsing normalizes built-in aliases via the embedded catalog first.
  • Channels and dot-separated numeric prefixes (el9@9.9, el9@9) resolve to an exact version key when present or the highest matching numeric version, yielding an immutable artifact identity (image, exact version, arch):
    d13:stable + native
      -> d13@20261130.2678.1 + arm64
      -> images/d13-20261130.2678.1-arm64.qcow2
  • barn repo scan is read-only and does not require qemu-img; it exits 0 while reporting any missing, unsafe, or untracked files in its output arrays (automation must check that missing and unsafe are empty).
  • barn repo build and barn repo verify use qemu-img. An unchanged rebuild preserves the catalog bytes. If you set revision explicitly, increase it when the contents change. Upload the images first, then the catalog with its applicable sidecars. Build and verification

Local layout and imports

Barn stores cached catalogs, downloaded images, and local imports under $BARN_HOME/images (default ~/.barn/images):

$BARN_HOME/images

  • manifests/Active catalog.json and highest accepted revision per repository
  • local-images.jsonRegistry of named local-* image aliases
  • local/
    • <sha256>.qcow2Imported local qcow2 files indexed by content digest
  • d13/
    • d13-20261130.2678.1-arm64.qcow2Verified read-only catalog artifacts by family
    • d13-20261130.2678.1-amd64.qcow2

Import a local qcow2 file into the cache or register it under a local-* alias:

barn image import /path/to/debian-13-generic.qcow2
barn image import --name local-mybase --boot uefi \
  --source-user debian /path/to/debian-13-generic.qcow2

Import rules:

  • image import accepts relative paths, ~/, and symlinks to regular files, and requires qemu-img. Reads are bounded by the actual local file size or declared catalog size; downloads stop on overflow, while legacy downloads without a declared artifact size are bounded at 8 GiB. Optional --sha256 verifies an expected digest.
  • image import copies and validates the qcow2 container as-is without modifying guest credentials, installing cloud-init, or booting the image.
  • Source filenames may contain spaces or Unicode and need no particular extension; Barn validates the qcow2 contents. New imports use local/<sha256>.qcow2, so different images can share a source filename and identical bytes reuse a cache entry. Existing aliases keep their original cache paths when reimported. Updates that exceed the 1 MiB registry metadata limit fail before changing existing aliases.
  • Named imports (--name local-<alias>) require --boot bios|uefi and --source-user <user> and default to the host architecture. --arch/-A can record an explicit amd64 or arm64 architecture, including aliases. The qcow2 metadata cannot identify the guest CPU, and import does not convert architectures. Match inventory vm_arch or the lifecycle command’s -A when using the image. Aliases are immutable and can be referenced via vm_image: local-mybase; unnamed imports only pre-populate the cache and cannot accept -A.

Pruning

barn image prune --dry-run
barn image prune --yes

barn image prune (or barn image prune --dry-run) lists candidate files that can be reclaimed; passing --yes deletes them.

prune protects images referenced by the selected repository’s active catalog, applied nodes, and registered local-* aliases. It can remove unreferenced images, recognized staging files, and read-only quarantine files ending in .qcow2.corrupt-<timestamp> or .img.corrupt-<timestamp>. To retain a quarantined copy for inspection, copy it outside the cache before cleanup. Preview the candidates with --dry-run and the same --repo you will use for deletion. If a later file fails inspection, files already deleted by prune --yes stay deleted.

To export the binary’s embedded schema-3 catalog byte-for-byte when bootstrapping a mirror, run go run ./tools/catalogexport /absolute/new/catalog.json. Any public catalog published at the embedded revision number must match those exact bytes.

6 - Self-hosted repositories and official signatures

Build a repository from local qcow2 images and verify official Barn releases.

Share a lab repository by distributing its images and catalog. Barn 1.5.0 supports filename-based builds and ML-DSA-87 verification. Barn 1.4.0 uses repo.yaml for builds and Minisign for official catalogs.

Create and use a lab repository

Place your images under repo/images/, for example lab-pg-1-arm64.qcow2. Run these commands on a host with qemu-img:

barn repo build ./repo
barn up --repo ./repo -I lab-pg

The first command writes catalog.json. Barn takes the image name, version and architecture from each filename and defaults to UEFI. An existing repo.yaml still selects the repository contents. A local repository can be unsigned and use your original image files.

To share it, serve catalog.json and images/ over HTTPS. Set the address on the client and activate the catalog. Run the same barn update when the repository changes.

export BARN_REPO=https://images.example.org/lab
barn update
barn up -I lab-pg

barn update --repo ./repo refreshes only that directory. Explicitly selected local and custom HTTPS repositories can be unsigned. Plain HTTP requires a valid ML-DSA-87 signature. Both 1.4 and 1.5 clients check image SHA-256 digests and byte counts from a schema 3 catalog.

Official images and packages

Use barn up or barn update with the official repository as usual. New clients verify catalog.json.sig with their built-in key. The maintainer publishes a separate catalog.json.minisig over the same catalog for 1.4.0 clients.

Internal mirrors of the official repository should copy both signature files with the catalog. Users who cached that mirror’s catalog in Barn 1.4.0 can refresh it after upgrading with barn update --repo <mirror>.

Initial script installations rely on HTTPS. For independent verification, get the public key through a trusted channel and use OpenSSL 3.5 or later to check the release manifest. Then check the installer and platform archive against that manifest. Use your existing installation channel for upgrades.

openssl pkeyutl -verify -rawin -pubin -inkey /trusted/official-key.pem \
  -pkeyopt context-string:barn/release/v1 -in checksums.txt -sigfile checksums.txt.sig
shasum -a 256 -c checksums.txt --ignore-missing

Generate and store the maintainer key

Barn signs its official image catalogs and CLI release manifests with one ML-DSA-87 key. Run the Bash commands below from the Barn source root with OpenSSL 3.5 or later and ML-DSA support.

First-time generation and public fingerprint

The official key was generated on December 3, 2026. Restore the same key when moving to another machine. The commands below document initial provisioning and stop if the private key already exists. Backup and recovery

The private key is a passphrase-free PKCS#8 PEM. Anyone who can read it can sign as Barn. Keep it on the maintainer’s machine with disk encryption, a mode 0700 directory and a mode 0600 file. Only the exported public key goes into the source tree and build machines.

(
  set -eu
  umask 077
  keydir="$HOME/.config/barn/signing"
  install -d -m 0700 "$keydir"
  set -C
  openssl genpkey -algorithm ML-DSA-87 > "$keydir/official.pem"
  openssl pkey -in "$keydir/official.pem" -check -noout
  openssl pkey -in "$keydir/official.pem" -pubout -out internal/image/official-key.pem
  chmod 0644 internal/image/official-key.pem
)

Get the public key from a trusted release commit. This command calculates SHA-256 over its DER-encoded SubjectPublicKeyInfo. The fingerprint for the official key introduced on December 3, 2026 is 5b108c30d99f93a28184fef362367dc63d4f7c1c2e56c2e0d89c7e3e1f17a262. New Barn clients display the short ID 583F7D5BAA0D16C5 in catalog state. Public key in v1.5.0

openssl pkey -pubin -in internal/image/official-key.pem -outform DER | openssl dgst -sha256

Backup and recovery

Keep a second copy of the private key on a separate encrypted removable volume. Unlock and mount it first, then replace /Volumes/BarnBackup with its actual mount point. Both cmp commands exit silently on success. They check that the backup is byte-identical and that it yields the public key embedded in the client. Eject the volume and store it offline.

(
  set -euo pipefail
  umask 077
  volume=/Volumes/BarnBackup
  key="$HOME/.config/barn/signing/official.pem"
  test -d "$volume"
  install -d -m 0700 "$volume/barn-signing"
  backup="$volume/barn-signing/official.pem"
  set -C
  cat "$key" > "$backup"
  cmp "$key" "$backup"
  openssl pkey -in "$backup" -pubout | cmp - internal/image/official-key.pem
)

To move to a new signing machine, obtain internal/image/official-key.pem from a trusted release commit and restore from the removable volume. The commands check the public key first and preserve any existing private key at the destination. Recover the original key from backup after a disk failure. A compromised key or loss of all copies requires distributing a client that trusts a replacement key.

(
  set -euo pipefail
  umask 077
  backup=/Volumes/BarnBackup/barn-signing/official.pem
  keydir="$HOME/.config/barn/signing"
  openssl pkey -in "$backup" -pubout | cmp - internal/image/official-key.pem
  install -d -m 0700 "$keydir"
  set -C
  cat "$backup" > "$keydir/official.pem"
  cmp "$backup" "$keydir/official.pem"
)

Sign and publish as the maintainer

From the Barn source root, select the image repository and the signing directory. Recompute the image digests and check that the catalog matches the repository.

repo=../repo/barn
keydir="$HOME/.config/barn/signing"
barn repo verify "$repo"

Reuse an existing catalog.json.minisig if it verifies. When the repository changes, first increase the revision and run barn repo build "$repo", then recreate the legacy signature with the original 1.4.0 key using make catalog-sign CATALOG_KEY="$keydir/barn-catalog-active-20261126.key" CATALOG_FILE="$repo/catalog.json". The tool reads the legacy key’s passphrase from CATALOGSIGN_PASSWORD. Sign those same catalog bytes with the new key.

make catalog-verify CATALOG_PUBLIC_KEY="$keydir/barn-catalog-active-20261126.pub" CATALOG_FILE="$repo/catalog.json"
./packaging/official-sign.sh sign "$repo/catalog.json" "$keydir/official.pem"
./packaging/official-sign.sh verify "$repo/catalog.json"

Upload new images to both mirrors and verify their sizes and SHA-256 digests before publishing the same catalog.json.sig, catalog.json.minisig and catalog.json at each repository root. Synchronize the embedded catalog, revision, timestamp and packaging/image-repository/repo.yaml, then run make catalog-check. On each mirror it verifies both signatures, compares the remote catalog with the embedded bytes and checks every stable image’s length. Use go run ./tools/catalogcheck -verify-bytes to stream and hash every stable image on both mirrors.

Once the official CLI draft is ready, run ./packaging/sign-release.sh /absolute/draft "$HOME/.config/barn/signing/official.pem" /absolute/signed. Upload the resulting release.json, checksums.txt and checksums.txt.sig together to that draft, then verify and publish it with make release-publish RELEASE_TAG="$tag". Release sequence

7 - Image Pipeline

Contributor tools that validate or offline-normalize qcow2 candidates for Barn’s official Linux images.

This page is for contributors who build Barn’s official Linux images; if you only use images, skip it. To share images of your own, build a static repository instead.

The tools live under packaging/image-pipeline/ in the Barn source checkout. build.sh turns one downloaded qcow2 with a known SHA-256 into a testing candidate bundle, either validated as it is or normalized offline; build-official.py runs it over the official matrix and assembles a candidate repository. The builder needs no network access or signing keys and leaves Barn’s runtime state alone. Its output then goes through live smoke tests and release review.

  • Tools: Python 3 and qemu-img; offline mode also needs working libguestfs tools (virt-customize, virt-cat). Override them with --qemu-img, --virt-customize, and --virt-cat, or with QEMU_IMG, VIRT_CUSTOMIZE, and VIRT_CAT.
  • Storage: keep source images, RPM/DEB package caches, and output directories outside the Git working tree, which tracks only recipes and lockfiles.
  • Architecture: --arch records the target architecture in the metadata; run offline customization where libguestfs can execute that architecture.

Modes and profiles

  • validate copies and re-hashes the source, checks that it is a single-file qcow2 with qemu-img check, and writes an evidence bundle without touching guest files or credentials.
  • offline normalizes guest access on a staged copy with virt-customize --no-network and virt-cat: it confirms UID/GID 88 is free of unrelated accounts, configures the locked dba/admin identity, disables SSH password and root login, strips SSH host keys, shell history, machine-id, and cloud-init caches, restores SELinux labels, and reads back a deterministic guest marker.

The profile adds distribution-specific steps; build.sh defaults to --profile base:

ProfileNormalization stepsPackage inputs
baseAccount, sudo, SSH, and cloud-init normalization onlyNone (package flags rejected)
el8Base normalization plus Python 3, SSH drop-in include, legacy network cleanup, chronyd, and SELinux relabelingLocked RPM dependency set
el9Base normalization plus legacy network cleanup and SELinux relabelingNone (package flags rejected)
el10Base normalization plus signed kernel-modules and kernel-modules-extra matching kernel-core, Docker bridge/iptables/overlay module verification, and SELinux relabelingLocked RPM dependency set
d12, d13Base normalization plus offline XFS userspace tools and en_US.UTF-8 / C.UTF-8 locale setupLocked DEB dependency set

validate accepts only --profile base. In offline mode, el8, el10, d12, and d13 require --package-lock and --package-cache matching the profile and architecture; build-official.py supplies both for official targets.

Official candidate matrix

build-official.py builds the ten official targets, Debian 12 and 13 (d12, d13) and Rocky Linux 8, 9, and 10 (el8, el9, el10), each on amd64 and arm64, from the upstream URLs, package locks, release versions, SHA-256 digests, and SOURCE_DATE_EPOCH pinned in official-v1.json. --list prints what your checkout pins. Ubuntu artifacts come from the same recipe run directly by pipeline.py, and need no offline package lock because Ubuntu cloud images already ship xfsprogs. Debian source inspection and candidate tests · Rocky Linux image tests

./packaging/image-pipeline/build-official.py --list

./packaging/image-pipeline/build-official.py \
  --source-cache /absolute/source-cache \
  --package-cache /absolute/package-cache \
  --output /absolute/existing-output-root \
  --target d13/arm64 --fetch

Create --source-cache, --package-cache, and --output beforehand and pass canonical absolute paths. --fetch downloads missing pinned HTTPS inputs and verifies their SHA-256 before virt-customize --no-network runs; without it, every locked input must already be cached. Omit --target to build all ten, or repeat it for a subset.

Once all ten bundles exist, assemble a candidate static repository from the parent directory that holds them, repeating --assemble-from for bundles spread over several parents:

./packaging/image-pipeline/build-official.py \
  --assemble-from /absolute/existing-output-root \
  --output /absolute/new-candidate-repository

Assembly requires exactly one bundle per target and a new --output path that does not exist yet. It runs barn repo build and barn repo verify with the barn on PATH or --barn /absolute/path/to/barn. The result maps channels to candidate (for example d13:candidate) with status testing, ready for live VM acceptance before promotion to stable and supported.

Validate a single downloaded image

SOURCE_DATE_EPOCH=1796256000

./packaging/image-pipeline/build.sh \
  --mode validate \
  --source /absolute/debian-13-generic-amd64-20261130-2678.qcow2 \
  --expected-sha256 c0f41265017c18124897401ccdd335dd4e1a0c262092384d5e6723855acb7446 \
  --output /absolute/new/evidence-directory \
  --name d13 --release 20261130.2678.0 --arch amd64 \
  --source-user debian --boot uefi \
  --source-uri https://cloud.debian.org/images/cloud/trixie/20261130-2678/debian-13-generic-amd64-20261130-2678.qcow2 \
  --artifact-url 'https://images.example/d13/{sha256}.qcow2' \
  --license NOASSERTION \
  --source-date-epoch "$SOURCE_DATE_EPOCH" \
  --manifest-version 2026120301

--source must be a canonical absolute path to a regular file, not a symlink, of at most 16 GiB; that cap is the recipe’s, while Barn checks runtime images against their catalog size (local import). --output must be a new path in an existing directory. The builder takes an adjacent lockfile, stages in a 0700 temporary directory, and renames the finished bundle into place; on failure it removes only its staging directory.

Each completed bundle contains:

FilePurpose
<name>-<release>-<arch>-<digest-prefix>.qcow2Validated read-only candidate qcow2 image
build-recipe.jsonBuilder invocation, tool versions, and input digests
manifest-candidate.jsonUnsigned candidate metadata (status: "testing")
provenance.intoto.jsonSLSA build provenance statement
sbom.spdx.jsonSPDX software bill of materials covering declared pipeline inputs and injected packages
validation.jsonBefore/after qcow2 checks, normalization marker results, and pending release gates
checksums.txtSHA-256 checksums of the other files in the bundle
package-lock.jsonIncluded when the profile installs locked RPM/DEB packages

Promote a candidate

With fixed inputs and tool versions, validate mode is byte-for-byte reproducible; for offline mode, build the candidate twice and compare the bundles as release evidence. To promote a candidate to a public supported release:

  1. Run live VM smoke tests across the target host and guest combinations.
  2. Update repo.yaml with the new catalog revision and supported status.
  3. Run barn repo build and barn repo verify.
  4. Sign catalog.json and publish its detached signature as catalog.json.minisig.
  5. Verify the published repository endpoints.