This is the multi-page printable view of this section.
Reference
- 1: Command Reference
- 1.1: Preparation and Utilities
- 1.2: Linux Lifecycle
- 1.3: Guest Access and Hosts
- 1.4: Guest Time Synchronization
- 1.5: Image Commands
- 1.6: Repository Commands
- 1.7: Host Network Commands
- 1.8: macOS Commands
- 2: Configuration
- 3: CLI Contracts
- 4: Mac Runtime Reference
- 5: Images
- 6: Self-hosted repositories and official signatures
- 7: Image Pipeline
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 macmachine 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
qcow2images.
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
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
| Label | Availability | Behavior |
|---|---|---|
| 1.1.0 | Options available across 1.1.0–1.5.0 | 1.1.0 used 2 vCPUs / 4 GiB by default and accepted CPU/memory resize through the inventory |
| 1.2.0 | Added in 1.2.0 | Resource 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.0 | Added in 1.3.0 | barn 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.0 | Added in 1.4.0 | barn image update, catalog signing key rotation, Debian 13.8 on both architectures, and immediate power-off during Linux purge |
| 1.5.0 | Changed in 1.5.0 | New 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
| Task | Commands and detailed reference |
|---|---|
| Prepare | setup, init, validate, doctor |
| Plan and create | plan, up |
| Start and stop | start, stop, restart, reload |
| Change and inspect | resize, recreate, status |
| Delete | destroy, purge |
| Access Linux guests | ssh, exec, logs, provision, ssh-config |
| Publish host names | hosts install, hosts uninstall |
| Synchronize clocks | time status, sync, auto |
| Refresh catalog | update, image sync, image reset |
| Manage Linux images | image list, info, pull, update (1.4.0), import, prune |
| Maintain a repository | repo scan, build, verify |
| Host network | network status, install, uninstall |
| Native macOS VMs | mac ls, up, start, stop, restart, configure, recreate, destroy |
| Mac access | mac open, ssh, exec, password, ssh-config, logs |
| Mac preparation | mac setup, doctor, image ls, image update, image prune |
| CLI utilities | version, completion, help |
Global options
| Option | Meaning |
|---|---|
-h, --help | Human-readable help for the selected command; exits 0 |
--json | Structured JSON on stdout; progress and diagnostics stay on stderr |
--yaml | Structured YAML on stdout; mutually exclusive with --json |
-v, --verbose | Bounded diagnostics on stderr |
--version | Root-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
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
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
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.
Aliases: s.
What setup changes
Setup skips steps that are already satisfied and prints the whole plan before the first change:
| Step | What it does | Root |
|---|---|---|
dependencies | Installs missing QEMU, qemu-img, UEFI firmware, and OpenSSH: brew install qemu on macOS (Homebrew required), apt-get or dnf on Linux | Linux only |
capabilities | Runs the host checks of barn doctor | No |
network | Installs 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 Linux | Yes |
verify | Re-checks the installed network | No |
config | Writes the generated inventory, or uses the existing one | No |
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.
--yesskips that question and is required without a terminal, where setup otherwise exits2. It cannot answersudo: without a terminal,sudomust work without a password, or setup exits3with reasonsudo_unavailable(troubleshooting).--dry-runprints the plan and changes nothing; itsnext:line is the command that applies it. It cannot be combined with--yes.barn --json setupreportsready,blocked,steps[],dependencies(withmissing[]and the exact package-managercommands[]),network, andnext/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
| Option | Meaning / default | Available in |
|---|---|---|
-A, --arch string | override deployment vm_arch: native, amd64, or arm64; environment overrides require 1.2.0 | 1.1.0 |
-c, --cidr string | generated template network as a canonical RFC1918 IPv4 /24 | 1.1.0 |
-C, --cpu string | Base vCPUs before scale, integer 1–256; effective CPU count is also limited to 256; overrides BARN_CPU | 1.2.0 |
-D, --disk string | Absolute root capacity, at least the base virtual size; bare integer means GiB; overrides BARN_DISK | 1.2.0 |
-d, --dry-run | show the resolved setup plan without changing anything | 1.1.0 |
-f, --file string | Inventory to prepare; mutually exclusive with a template argument | 1.1.0 |
-I, --image string | override vm_image/vm_version for selected nodes; environment overrides require 1.2.0 | 1.1.0 |
-M, --mem string | Base memory before scale, minimum 512 MiB; bare integer means MiB; overrides BARN_MEM | 1.2.0 |
--mirror | use the China official repository at repo.pigsty.cc; overridden by --repo | 1.1.0 |
-m, --mode string | macOS fixed-IP network backend: host or shared (default “host”) | 1.1.0 |
-r, --repo string | image repository URL or local directory, also used for socket_vmnet; overrides --mirror and $BARN_REPO | 1.1.0 |
-S, --scale string | Integer 1–256 multiplying base CPU and memory only; disk does not scale; overrides BARN_SCALE | 1.2.0 |
-y, --yes | accept the one-time setup plan (required without a terminal) | 1.1.0 |
barn init
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).
| Option | Meaning / default | Available in |
|---|---|---|
-A, --arch string | override deployment vm_arch: native, amd64, or arm64; environment overrides require 1.2.0 | 1.1.0 |
-c, --cidr string | rebase the generated template to a canonical RFC1918 IPv4 /24 | 1.1.0 |
-C, --cpu string | Base vCPUs before scale, integer 1–256; effective CPU count is also limited to 256; overrides BARN_CPU | 1.2.0 |
-D, --disk string | Absolute root capacity, at least the base virtual size; bare integer means GiB; overrides BARN_DISK | 1.2.0 |
--force | Overwrite the destination inventory; default preserves existing files | 1.1.0 |
-I, --image string | override vm_image/vm_version for selected nodes; environment overrides require 1.2.0 | 1.1.0 |
-M, --mem string | Base memory before scale, minimum 512 MiB; bare integer means MiB; overrides BARN_MEM | 1.2.0 |
-o, --output string | write to this path instead of ./barn.yml; ‘-’ writes to stdout | 1.1.0 |
-S, --scale string | Integer 1–256 multiplying base CPU and memory only; disk does not scale; overrides BARN_SCALE | 1.2.0 |
barn validate
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.
| Option | Meaning / default | Available in |
|---|---|---|
-A, --arch string | override deployment vm_arch: native, amd64, or arm64; environment overrides require 1.2.0 | 1.1.0 |
-C, --cpu string | Base vCPUs before scale, integer 1–256; effective CPU count is also limited to 256; overrides BARN_CPU | 1.2.0 |
-D, --disk string | Absolute root capacity, at least the base virtual size; bare integer means GiB; overrides BARN_DISK | 1.2.0 |
-f, --file string | Inventory to validate; otherwise use local discovery, with no applied-state fallback | 1.1.0 |
-I, --image string | override vm_image/vm_version for selected nodes; environment overrides require 1.2.0 | 1.1.0 |
-M, --mem string | Base memory before scale, minimum 512 MiB; bare integer means MiB; overrides BARN_MEM | 1.2.0 |
-r, --repo string | image repository whose catalog checks the images; overrides $BARN_REPO | 1.1.0 |
-S, --scale string | Integer 1–256 multiplying base CPU and memory only; disk does not scale; overrides BARN_SCALE | 1.2.0 |
barn doctor
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 version
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 completion
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.
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
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 to | Run | What happens to disks |
|---|---|---|
| See what a change would do | plan | Nothing; read-only |
| Create the lab, or bring it back after a stop or reboot | up | Kept |
| Boot, shut down, or reboot existing nodes as they are | start, stop, restart | Kept |
Restart nodes and re-apply the inventory (stop, then up) | reload | Kept; nodes new in the inventory are created |
| Change CPU or memory, or grow the root disk | resize | Kept |
| Change image, architecture, data disks, network, or shares | recreate | Root and non-persistent data disks replaced |
| Remove some nodes, or the whole lab but keep persistent data | destroy | Deleted, except persistent data disks |
| Start over from nothing | purge | Everything 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.
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.
| Option | Meaning / default | Available in |
|---|---|---|
-A, --arch string | override deployment vm_arch: native, amd64, or arm64; environment overrides require 1.2.0 | 1.1.0 |
-C, --cpu string | Base vCPUs before scale, integer 1–256; effective CPU count is also limited to 256; overrides BARN_CPU | 1.2.0 |
-D, --disk string | Absolute root capacity, at least the base virtual size; bare integer means GiB; overrides BARN_DISK | 1.2.0 |
-f, --file string | desired inventory; defaults to the discovered inventory, then the applied state | 1.1.0 |
-I, --image string | override vm_image/vm_version for selected nodes; environment overrides require 1.2.0 | 1.1.0 |
-M, --mem string | Base memory before scale, minimum 512 MiB; bare integer means MiB; overrides BARN_MEM | 1.2.0 |
-r, --repo string | image repository URL or directory; overrides $BARN_REPO | 1.1.0 |
-S, --scale string | Integer 1–256 multiplying base CPU and memory only; disk does not scale; overrides BARN_SCALE | 1.2.0 |
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.
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.
| Option | Meaning / default | Available in |
|---|---|---|
-A, --arch string | override deployment vm_arch: native, amd64, or arm64; environment overrides require 1.2.0 | 1.1.0 |
-C, --cpu string | Base vCPUs before scale, integer 1–256; effective CPU count is also limited to 256; overrides BARN_CPU | 1.2.0 |
-D, --disk string | Absolute root capacity, at least the base virtual size; bare integer means GiB; overrides BARN_DISK | 1.2.0 |
-f, --file string | desired inventory; defaults to the discovered inventory, then the applied state | 1.1.0 |
-I, --image string | override vm_image/vm_version for selected nodes; environment overrides require 1.2.0 | 1.1.0 |
-M, --mem string | Base memory before scale, minimum 512 MiB; bare integer means MiB; overrides BARN_MEM | 1.2.0 |
--mirror | use the China official repository at repo.pigsty.cc; overridden by --repo | 1.1.0 |
-n, --no-wait | return once QEMU is running, without waiting for the guest to boot | 1.1.0 |
-p, --parallel int | Node concurrency: omitted = max(1, logical CPUs - 2); 0 = all selected nodes; positive = limit | 1.2.0 |
-r, --repo string | image repository URL or directory; overrides --mirror and $BARN_REPO | 1.1.0 |
--rollback | remove safe artifacts from nodes that fail to prepare | 1.1.0 |
-S, --scale string | Integer 1–256 multiplying base CPU and memory only; disk does not scale; overrides BARN_SCALE | 1.2.0 |
barn start
Use start to boot nodes that already exist, from any directory: it reads applied state, not the inventory, and never creates nodes.
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.
| Option | Meaning / default | Available in |
|---|---|---|
-n, --no-wait | return once QEMU is running, without waiting for the guest to boot | 1.1.0 |
-p, --parallel int | Node concurrency: omitted = max(1, logical CPUs - 2); 0 = all selected nodes; positive = limit | 1.2.0 |
barn stop
Use stop to shut nodes down and free host CPU and memory; root disks, data disks, keys, and deployment state all stay.
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.
| Option | Meaning / default | Available in |
|---|---|---|
-p, --parallel int | Node concurrency: omitted = max(1, logical CPUs - 2); 0 = all selected nodes; positive = limit | 1.2.0 |
barn restart
Use restart to reboot nodes exactly as they were created. Inventory edits are ignored; use reload to pick them up.
restart stops and starts existing nodes from applied state, then waits for SSH and checks guest clocks unless --no-wait is set.
| Option | Meaning / default | Available in |
|---|---|---|
-n, --no-wait | return once QEMU is running, without waiting for the guest to boot | 1.1.0 |
-p, --parallel int | Node concurrency: omitted = max(1, logical CPUs - 2); 0 = all selected nodes; positive = limit | 1.2.0 |
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.
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.
| Option | Meaning / default | Available in |
|---|---|---|
-A, --arch string | override deployment vm_arch: native, amd64, or arm64; environment overrides require 1.2.0 | 1.1.0 |
-C, --cpu string | Base vCPUs before scale, integer 1–256; effective CPU count is also limited to 256; overrides BARN_CPU | 1.2.0 |
-D, --disk string | Absolute root capacity, at least the base virtual size; bare integer means GiB; overrides BARN_DISK | 1.2.0 |
-f, --file string | desired inventory; defaults to the discovered inventory, then the applied state | 1.1.0 |
-I, --image string | override vm_image/vm_version for selected nodes; environment overrides require 1.2.0 | 1.1.0 |
-M, --mem string | Base memory before scale, minimum 512 MiB; bare integer means MiB; overrides BARN_MEM | 1.2.0 |
--mirror | use the China official repository at repo.pigsty.cc; overridden by --repo | 1.1.0 |
-n, --no-wait | return once QEMU is running, without waiting for the guest to boot | 1.1.0 |
-p, --parallel int | Node concurrency: omitted = max(1, logical CPUs - 2); 0 = all selected nodes; positive = limit | 1.2.0 |
-r, --repo string | image repository URL or directory; overrides --mirror and $BARN_REPO | 1.1.0 |
--rollback | remove safe artifacts from nodes that fail to prepare | 1.1.0 |
-S, --scale string | Integer 1–256 multiplying base CPU and memory only; disk does not scale; overrides BARN_SCALE | 1.2.0 |
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.
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.
| Option | Meaning / default | Available in |
|---|---|---|
-A, --arch string | override deployment vm_arch: native, amd64, or arm64; environment overrides require 1.2.0 | 1.1.0 |
-C, --cpu string | Base vCPUs before scale, integer 1–256; effective CPU count is also limited to 256; overrides BARN_CPU | 1.2.0 |
-D, --disk string | Absolute root capacity, at least the base virtual size; bare integer means GiB; overrides BARN_DISK | 1.2.0 |
-f, --file string | desired inventory; defaults to the discovered inventory, then the applied state | 1.1.0 |
-I, --image string | override vm_image/vm_version for selected nodes; environment overrides require 1.2.0 | 1.1.0 |
-M, --mem string | Base memory before scale, minimum 512 MiB; bare integer means MiB; overrides BARN_MEM | 1.2.0 |
-S, --scale string | Integer 1–256 multiplying base CPU and memory only; disk does not scale; overrides BARN_SCALE | 1.2.0 |
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.
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.
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.
| Option | Meaning / default | Available in |
|---|---|---|
-A, --arch string | override deployment vm_arch: native, amd64, or arm64; environment overrides require 1.2.0 | 1.1.0 |
-C, --cpu string | Base vCPUs before scale, integer 1–256; effective CPU count is also limited to 256; overrides BARN_CPU | 1.2.0 |
-D, --disk string | Absolute root capacity, at least the base virtual size; bare integer means GiB; overrides BARN_DISK | 1.2.0 |
-f, --file string | desired inventory; defaults to the discovered inventory, then the applied state | 1.1.0 |
--force | recreate without the interactive confirmation (required without a terminal) | 1.1.0 |
-I, --image string | override vm_image/vm_version for selected nodes; environment overrides require 1.2.0 | 1.1.0 |
-M, --mem string | Base memory before scale, minimum 512 MiB; bare integer means MiB; overrides BARN_MEM | 1.2.0 |
--mirror | use the China official repository at repo.pigsty.cc; overridden by --repo | 1.1.0 |
-n, --no-wait | return once QEMU is running, without waiting for the guest to boot | 1.1.0 |
-p, --parallel int | Node concurrency: omitted = max(1, logical CPUs - 2); 0 = all selected nodes; positive = limit | 1.2.0 |
-r, --repo string | image repository URL or directory; overrides --mirror and $BARN_REPO | 1.1.0 |
-S, --scale string | Integer 1–256 multiplying base CPU and memory only; disk does not scale; overrides BARN_SCALE | 1.2.0 |
--yes | same as --force | 1.1.0 |
barn status
Use status to check what is running and how each node is configured, from any directory.
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 destroy
Use destroy to remove nodes you no longer need, or the whole Linux lab while keeping persistent data disks for a later rebuild.
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.
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.
| Option | Meaning / default | Available in |
|---|---|---|
--delete-persistent | also delete owned persistent data disks | 1.1.0 |
--force | destroy without the interactive confirmation (required without a terminal) | 1.1.0 |
-p, --parallel int | Node concurrency: omitted = max(1, logical CPUs - 2); 0 = all selected nodes; positive = limit | 1.2.0 |
--purge | terminal disposal: also delete persistent disks, keys, and deployment state | 1.1.0 |
--yes | same as --force | 1.1.0 |
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.
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.
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.
| Option | Meaning / default | Available in |
|---|---|---|
--ask | show the deletion scope and ask for y/yes before purging | 1.1.0 |
-p, --parallel int | Node concurrency: omitted = max(1, logical CPUs - 2); 0 = all selected nodes; positive = limit | 1.2.0 |
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
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 meta -- … | barn exec meta -- … | |
|---|---|---|
| Guest receives | One string, parsed by the guest shell, as with plain ssh | The program and its arguments, with no shell |
Pipes, ;, $VAR | Work; quote them so your local shell leaves them alone | Wrap the command in sh -c '…' |
| Spaces, quotes, empty arguments | Re-parsed by the guest shell | Preserved exactly |
| No command | Opens an interactive login shell | Fails: 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 exits2. 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,execalso accepts one quoted string and hands it to the guest shell. - Exit status: Barn exits with the remote command’s status, so
exit 17in the guest makesbarnexit17. Check whether a nonzero code came from the guest before reading it as a Barn error class.
barn ssh
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 exec
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 logs
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.
| Option | Meaning / default | Available in |
|---|---|---|
-f, --follow | continue streaming appended log data | 1.1.0 |
-s, --source string | log source: serial, qemu, or events (default “serial”) | 1.1.0 |
barn provision
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.
| Option | Meaning / default | Available in |
|---|---|---|
-p, --parallel int | Positive concurrency limit; default 1; zero is invalid | 1.1.0 |
-s, --script string | local Bash script to stream to each selected guest | 1.1.0 |
--sudo | run the guest script through sudo -n | 1.1.0 |
-t, --timeout duration | hard deadline for the operation (default 1h0m0s) | 1.1.0 |
barn ssh-config
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.
| Option | Meaning / default | Available in |
|---|---|---|
-i, --install | install the deployment fragment and one Include in ~/.ssh/config | 1.1.0 |
--name string | SSH Host and fragment prefix (default “barn”) | 1.1.0 |
--remove | remove the Include and fragment Barn installed | 1.1.0 |
barn hosts install
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.
| Option | Meaning / default | Available in |
|---|---|---|
-f, --file string | Inventory nodes, aliases and vm_hosts; usable before VM creation | 1.2.0 |
-y, --yes | apply the displayed privileged plan without confirmation (sudo may still ask for a password) | 1.1.0 |
barn hosts uninstall
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.
| Option | Meaning / default | Available in |
|---|---|---|
-y, --yes | apply the displayed privileged plan without confirmation (sudo may still ask for a password) | 1.1.0 |
Implementation
1.4 - Guest Time Synchronization
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
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.
| Command | Option | Default | Meaning | Available in |
|---|---|---|---|---|
time status [node...] | --timeout | 1m | Total deadline, from 1s to 10m | 1.3.0 |
time sync [node...] | --timeout | 1m | Total deadline, from 1s to 10m | 1.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:
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.
| Host | Scheduler | Job files |
|---|---|---|
| macOS | launchd calendar job | ~/Library/LaunchAgents/com.pgsty.barn.time.plist |
| Linux | systemd 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
1.5 - Image Commands
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
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.
| Option | Meaning / default | Available in |
|---|---|---|
--mirror | use the China official repository at repo.pigsty.cc; overridden by --repo | 1.1.0 |
-r, --repo string | image repository URL or directory; overrides --mirror and $BARN_REPO | 1.1.0 |
barn image list
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.
| Option | Meaning / default | Available in |
|---|---|---|
-r, --repo string | image repository URL or directory; overrides $BARN_REPO | 1.1.0 |
barn image info
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.
| Option | Meaning / default | Available in |
|---|---|---|
-A, --arch string | artifact architecture (defaults to native): native, amd64 (x86_64, x64), or arm64 (aarch64, a64) | 1.1.0 |
-r, --repo string | image repository URL or directory; overrides $BARN_REPO | 1.1.0 |
barn image pull
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.
| Option | Meaning / default | Available in |
|---|---|---|
-A, --arch string | artifact architecture (defaults to native): native, amd64 (x86_64, x64), or arm64 (aarch64, a64) | 1.1.0 |
--mirror | use the China official repository at repo.pigsty.cc; overridden by --repo | 1.1.0 |
-r, --repo string | image repository URL or directory; overrides --mirror and $BARN_REPO | 1.1.0 |
barn image update
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.
| Option | Effect | Available in |
|---|---|---|
-A, --arch string | Select one architecture, including native, amd64 or arm64 | 1.4.0 |
-d, --dry-run | Verify the candidate catalog and preview downloads and requested cleanup without writing local state | 1.4.0 |
--prune | After successful downloads, remove files eligible under the normal pruning rules | 1.4.0 |
--mirror | Select the China official repository | 1.4.0 |
-r, --repo string | Select a repository URL or directory. Takes precedence over --mirror and BARN_REPO | 1.4.0 |
--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
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.
| Option | Meaning / default | Available in |
|---|---|---|
-A, --arch string | Guest architecture recorded with --name; defaults to native; does not convert the image | 1.1.0 |
-b, --boot string | required with --name: bios or uefi | 1.1.0 |
--name string | Immutable local-* alias; requires --boot and --source-user | 1.1.0 |
-s, --sha256 string | optional expected SHA-256 | 1.1.0 |
-u, --source-user string | required with --name: source image login user | 1.1.0 |
barn image sync
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.
| Option | Meaning / default | Available in |
|---|---|---|
--allow-downgrade | activate a catalog older than the newest revision seen so far | 1.1.0 |
-r, --repo string | Repository whose active catalog is replaced | 1.1.0 |
barn image reset
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.
| Option | Meaning / default | Available in |
|---|---|---|
-r, --repo string | Repository whose active catalog is reset to the embedded catalog | 1.1.0 |
barn image prune
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.
| Option | Meaning / default | Available in |
|---|---|---|
-d, --dry-run | show unreferenced images and stale staging files without deleting | 1.1.0 |
-r, --repo string | image repository URL or directory; overrides $BARN_REPO | 1.1.0 |
-y, --yes | Delete the listed unreferenced files; mutually exclusive with --dry-run | 1.1.0 |
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
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
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
Report the state of every qcow2 file without changing anything or needing qemu-img:
| State | Meaning |
|---|---|
tracked | Selected by filename inference or repo.yaml, and present |
missing | Referenced by repo.yaml but absent from images/ |
untracked | Present in images/ but not referenced by repo.yaml |
unsafe | Not 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 repo build
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 verify
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.
Implementation
The self-hosted repository guide gives a two-command example.
1.7 - Host Network Commands
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
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.
| Option | Meaning / default | Available in |
|---|---|---|
-c, --cidr string | Optional expected private /24; otherwise inspect the installed subnet | 1.1.0 |
barn network install
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.
| Option | Meaning / default | Available in |
|---|---|---|
-a, --archive string | macOS: pinned socket_vmnet archive | 1.1.0 |
-c, --cidr string | network: an RFC1918 IPv4 /24 (default “10.10.10.0/24”) | 1.1.0 |
-i, --interface-id string | macOS: persistent vmnet UUID | 1.1.0 |
-m, --mode string | macOS vmnet mode: host or shared (default “host”) | 1.1.0 |
-y, --yes | apply the displayed privileged plan without confirmation (sudo may still ask for a password) | 1.1.0 |
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
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.
| Option | Meaning / default | Available in |
|---|---|---|
-y, --yes | apply the displayed privileged plan without confirmation (sudo may still ask for a password) | 1.1.0 |
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. 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 withmac_vm_limit. - Machine names. A command with an optional
[name]uses the only existing machine, ormac1. With several machines and none namedmac1, pass a name.configure,recreate, anddestroyalways need one.startandstoptake several names or--all, not both. - Sizes.
--memoryand--diskare binary even when writtenGB:16G,16GiB, and16GBall mean 16 GiB, and a bare number is bytes. Linux inventoryGBis decimal. - Confirmation.
recreateanddestroyprint what they will delete and ask you to type the command name.--yesor--forceskips the question and is required without a terminal; neither command has a-yshorthand. Commands that download macOS from Apple (up,setup,image update) ask first;-y/--yesskips that question and is required without a terminal. - State. Machines live under
$BARN_HOME/mac, separate from the Linux inventory. These commands ignore the LinuxBARN_IMAGE/BARN_ARCH/BARN_CPU/BARN_MEM/BARN_SCALE/BARN_DISKoverrides.
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.
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 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.
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.
| Option | Meaning / default | Available in |
|---|---|---|
--clipboard on|off | on/off, true/false, or yes/no; default on, active while the desktop window is focused | 1.1.0 |
--cpu int | vCPUs, default 4; minimum 2, maximum host logical CPU count | 1.1.0 |
--disk size | Base capacity, minimum 32 GiB; default uses the prepared base, or 100 GiB initially | 1.1.0 |
--ipsw string | install macOS from this restore image instead of downloading from Apple | 1.1.0 |
--memory size | Memory, default 8 GiB; a whole MiB from 4 GiB to host RAM | 1.1.0 |
-n, --no-wait | return once the VM runs; first boot may still be initializing | 1.1.0 |
--open | show the desktop as soon as the VM runs | 1.1.0 |
--share [name=]path[:ro] | Repeatable [name=]path[:ro|:rw]; default writable, mounted under /Volumes/My Shared Files | 1.1.0 |
--subnet string | Canonical private /24, or auto; default selects the first free subnet | 1.1.0 |
--user string | Guest administrator; default is the host username, or barn if that name is invalid | 1.1.0 |
-y, --yes | download macOS from Apple without asking (required without a terminal) | 1.1.0 |
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.
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.
| Option | Meaning / default | Available in |
|---|---|---|
--all | start every machine | 1.1.0 |
-n, --no-wait | return once the VM runs, without waiting for SSH | 1.1.0 |
--open | show the desktop as soon as the VM runs | 1.1.0 |
--recovery | boot macOS Recovery and show its desktop | 1.1.0 |
barn mac stop
Use stop to shut machines down cleanly through macOS; disks and settings stay as they are.
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.
| Option | Meaning / default | Available in |
|---|---|---|
--all | stop every machine | 1.1.0 |
--force | Power off immediately instead of requesting shutdown; unsaved guest work is lost | 1.1.0 |
barn mac restart
Use restart to apply settings saved with configure, or to reboot a guest that misbehaves.
It shuts the machine down normally and starts it again. It takes at most one name and has no --all.
| Option | Meaning / default | Available in |
|---|---|---|
-n, --no-wait | return once the VM runs, without waiting for SSH | 1.1.0 |
--open | show the desktop as soon as the VM runs | 1.1.0 |
barn mac configure
Use configure to change a machine’s CPUs, memory, shared folders, network, or clipboard setting without touching its disk or account.
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.
| Option | Meaning / default | Available in |
|---|---|---|
--clipboard on|off | on/off, true/false, or yes/no; omitted retains the setting | 1.1.0 |
--cpu int | vCPUs, minimum 2 and maximum host logical CPU count; omitted retains current value | 1.1.0 |
--memory size | Memory, a whole MiB from 4 GiB to host RAM; omitted retains current value | 1.1.0 |
--share [name=]path[:ro] | Add or replace a named share; repeatable, writable by default, optional :ro or :rw | 1.1.0 |
--subnet string | move to this private /24 network, or auto for the first free one | 1.1.0 |
--unshare stringArray | stop sharing the named folder (repeatable) | 1.1.0 |
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.
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.
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.
| Option | Meaning / default | Available in |
|---|---|---|
--force | skip the confirmation (required without a terminal) | 1.1.0 |
-n, --no-wait | return once the VM runs, without waiting for SSH | 1.1.0 |
--update | use the newest prepared macOS base | 1.1.0 |
--yes | Same as --force; no -y shorthand | 1.1.0 |
barn mac destroy
Use destroy to delete machines you no longer need.
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.
Explicit names are required. Run barn mac image prune afterwards to remove bases that no machine uses.
| Option | Meaning / default | Available in |
|---|---|---|
--force | skip the confirmation (required without a terminal) | 1.1.0 |
--yes | Same as --force; no -y shorthand | 1.1.0 |
barn mac open
Use open to see and use the machine’s desktop; it starts a stopped machine first.
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 ssh
Use ssh for an interactive shell in the machine, or to run a shell command line in it.
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 exec
Use exec in scripts: it runs one program with its arguments passed exactly as given and returns the program’s exit status.
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 password
Use password when the guest desktop asks for the login password, at the lock screen or an administrator prompt.
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.
| Option | Meaning / default | Available in |
|---|---|---|
-c, --copy | copy to the clipboard instead of printing | 1.1.0 |
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.
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.
| Option | Meaning / default | Available in |
|---|---|---|
-i, --install | install the entries as one Include in ~/.ssh/config | 1.1.0 |
--remove | remove the entries Barn installed | 1.1.0 |
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.
--lines/-n must be positive and defaults to 100. Here -n means lines, not no-wait. There is no follow option.
| Option | Meaning / default | Available in |
|---|---|---|
-n, --lines int | number of recent lines (default 100) | 1.1.0 |
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.
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.
| Option | Meaning / default | Available in |
|---|---|---|
--disk size | Base capacity, at least 32 GiB. Defaults to the current base capacity or 100 GiB for the first base | 1.1.0 |
--ipsw string | install macOS from this restore image instead of downloading from Apple | 1.1.0 |
-y, --yes | download macOS from Apple without asking (required without a terminal) | 1.1.0 |
barn mac image ls
Use image ls to see which restore images and bases take up disk space, and which machines use them.
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 update
Use image update to move to Apple’s newest macOS 27 build.
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.
| Option | Meaning / default | Available in |
|---|---|---|
--ipsw string | use this restore image instead of downloading from Apple | 1.1.0 |
-y, --yes | download without asking (required without a terminal) | 1.1.0 |
barn mac image prune
Use image prune to reclaim disk space from bases that no machine uses.
It lists unused bases other than the current default. --installers adds downloaded restore images and partial downloads. Nothing is deleted without --yes.
| Option | Meaning / default | Available in |
|---|---|---|
--installers | include downloaded restore images and partial downloads | 1.1.0 |
-y, --yes | Delete the listed unused images; otherwise only list candidates | 1.1.0 |
barn mac doctor
Run doctor first when something goes wrong, and after installing or upgrading Barn.
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.
Implementation
2 - Configuration
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.
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:
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:
- The path given with
-f. barn.yml,barn.yaml,pigsty.yml, thenpigsty.yamlin 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.- The applied specification stored in
BARN_HOME— only forplan,up,reload,recreate, andresize.
| Commands | Desired 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 install | Uses applied node names by default. An explicit -f reads that inventory and its vm_hosts mappings |
start, stop, restart, status, destroy, purge | Operate 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_*, andnode_packages, are ignored and never cause VM drift. - Inheritance: Values inherit
all.vars→ nestedchildren.<group>.vars→ host variables, deepest wins. A host-level list such asvm_disksreplaces 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_ipinall.varsnames the control node. If it is omitted or matches no managed node, Barn picks the first managed node in traversal order (each group’shostsbefore itschildren). Setadmin_ipso reordering groups cannot move the control role. - Login account: All nodes share one login user matching
[a-z_][a-z0-9_-]{0,31}, defaultdba. Withdba, an explicitnode_admin_uidmust be88; with a custom user,node_admin_uidonly has to be an integer and the guest assigns the UID. - Skipped hosts:
vm_skip: truemarks 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 asmissinginplanwithout destroying it. - Strict
vm_*namespace: Unknownvm_*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
| Variable | Default | Meaning |
|---|---|---|
vm_skip | false | Skip virtualization for this physical or external host |
vm_image | d13 (new lab in 1.5.0) | Image family, :channel reference, or image@version selector; see Image and architecture |
vm_version | unset | Newest numeric version matching this prefix, such as 9 or 9.7 |
vm_arch | native | Deployment-wide guest architecture; follows the host unless set to amd64 or arm64 |
vm_cpu | 1 | Base vCPU count; the effective count after scaling must be 1–256 |
vm_mem | 2048 | Base memory: bare integer in MiB, or a size string such as 8GiB (minimum 512MiB) |
vm_scale | 1 | Positive integer multiplying CPU and memory only |
vm_hosts | [] | Extra host /etc/hosts mappings, declared only in all.vars |
vm_disk | 64 | Root 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:
| Settings | Effective CPU | Effective memory |
|---|---|---|
| None | 1 | 2 GiB |
vm_scale: 3 | 3 | 6 GiB |
vm_cpu: 2, vm_scale: 3 | 6 | 6 GiB |
vm_mem: 4GiB, vm_scale: 3 | 3 | 12 GiB |
vm_cpu: 2, vm_mem: 4GiB, vm_scale: 3 | 6 | 12 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 field | CLI | Environment variable | Default |
|---|---|---|---|
vm_image | --image/-I | BARN_IMAGE | d13 (new lab in 1.5.0) |
vm_arch | --arch/-A | BARN_ARCH | native |
vm_cpu | --cpu/-C | BARN_CPU | 1 |
vm_mem | --mem/-M | BARN_MEM | 2048 MiB |
vm_scale | --scale/-S | BARN_SCALE | 1 |
vm_disk | --disk/-D | BARN_DISK | 64 GiB |
Each field resolves per node; the first source that sets it wins:
- CLI flag
- Non-empty environment variable
- Host variable
- Deepest child group
- Parent groups
all.vars- Default
- CPU and memory are always bases, multiplied once by the final scale.
-S 3replaces the scale rather than multiplying it; add-S 1to set exact CPU and memory. - CLI and environment values override host values on the selected nodes. Put common defaults in
all.varswhen 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 2uses 2. Suggested follow-up commands repeat effective environment overrides as explicit flags.
| Command | Overrides | Effect |
|---|---|---|
init, template-generating setup | All six | Written into the new inventory, defaults included; CPU and memory as bases plus scale |
up that generates an inventory interactively | All six | Saved in the generated inventory |
validate, plan, up, reload, recreate | All six | Change this run’s desired specification only; the YAML is not rewritten, so the next run against the file reports drift |
resize | All six | Applies CPU and memory changes and grows the root disk; -I/-A are only checked for consistency |
setup reusing an inventory | None | Flags are rejected and environment variables ignored |
start, stop, restart, status, destroy, purge | None | Applied 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.
Precedence
| Order | Image (per node) | Architecture (whole deployment) |
|---|---|---|
| 1 | --image/-I, on the selected nodes | --arch/-A |
| 2 | BARN_IMAGE | BARN_ARCH |
| 3 | vm_image and vm_version: host, then groups, then all.vars | vm_arch |
| 4 | Saved deployment default, or the embedded default for a new lab | native: 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.
| Architecture | Aliases | Meaning |
|---|---|---|
native | — | Follow the current host; the default |
amd64 | x86_64, x64 | x86-64 guest |
arm64 | aarch64, a64 | ARM64 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
-IorBARN_IMAGE, the suffix sets the deployment architecture, overridingvm_arch. - In
vm_image, the suffix takes precedence overvm_arch: native, the value generated templates write. A concretevm_archthat names the other architecture fails validation, as do nodes whose suffixes disagree. -AandBARN_ARCHmust agree with every suffix still in effect: naming the other architecture, ornative, fails with exit2. A matching value such asel10a -A arm64is accepted.
Image selection details
vm_archbelongs to the whole deployment: set it once inall.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_imageis omitted, existing labs use their saved default for existing and added nodes. A lonevm_versionselects 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 invm_imagerather than reassigning built-in aliases.
vm_version keeps the family and the version prefix in separate fields:
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, andvalidateapply to that invocation only. To keep them, setall.vars.vm_archand the node or groupvm_image, and remove any supersededvm_version.initand template-generatingsetupwrite both into the new inventory;setuprejects-I/-Awith an existing inventory. - Without an inventory file, lifecycle commands apply overrides on top of the saved specification.
startandrestartalways use applied state. - Existing VMs are never converted. After you edit
vm_archor omit-A,upreports drift; switching the architecture requiresrecreatewith all existing nodes selected.resizecannot change the image or architecture. - A guest whose architecture differs from the host runs under QEMU TCG emulation. On Linux,
barn setupinstalls only the native emulator: install the targetqemu-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.
| Field | Default | Meaning |
|---|---|---|
path | required | Absolute 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 |
size | 128 | Capacity: GiB integer or size string |
fs | auto | auto, 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 |
persistent | false | When 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.
| Field | Default | Meaning |
|---|---|---|
host | required | Absolute 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 |
guest | required | Absolute mount point, normalized; spaces, Unicode, and shell punctuation are accepted, control characters are not |
readonly | true | Set 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
.sshdirectory. Do not put PostgreSQL data directories on 9p. - If the guest user cannot write a
readonly: falseshare, Barn mounts it read-only with a warning and leaves host ownership alone; fix host permissions and re-runbarn upto upgrade the mount. - Changing
vm_shareson an existing node requiresbarn recreate. A missing host directory duringuporstartfails only that node;restart,reload, andrecreateverify 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:
- Each entry needs an
addressand a non-emptynameslist. Addresses must be canonical IPv4 in the inventory’s/24, within.9–.254(.1–.8are 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.upnever publishes them. hosts installwithout-fpublishes only names and aliases from applied state and replaces the whole Barn block, dropping these service names; repeat the-fcommand 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:
| Change | Apply with |
|---|---|
| New node | barn up |
CPU or memory, including vm_scale | barn resize <node>; keeps identity and disks |
Larger vm_disk | barn resize <node>, or barn resize -D <size> <node> without editing; grow-only |
| Image, data disks, shares, or other VM definition | barn recreate <node> |
vm_arch, login user, or the /24 | barn recreate of the whole deployment |
Node removed or set to vm_skip: true | Shown 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
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.
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.
| Mode | stdout | stderr |
|---|---|---|
| Text (default) | Results and follow-up hints (connect:, retry:, next:) | Live progress, prompts, error: lines |
--json or --yaml | One JSON or YAML document: the command’s report or a failure object | Progress and diagnostics |
-v, --verbose | Unchanged | Adds 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.
| Code | error | Meaning |
|---|---|---|
0 | Success (including ready guests with non-fatal warnings[] or repairs[]) | |
1 | runtime | Operation executed and failed (external tool, download, or guest failure) |
2 | usage | Invalid CLI syntax, missing inventory file, or invalid configuration/image selector |
3 | capability | Host lacks a required dependency, active Barn network, or privilege |
4 | conflict | Operation conflicts with current deployment state or another active barn process |
5 | partial | Node-level batch failure; inspect failures[] (successful peer nodes remain intact) |
6 | resource | Host IP address, port, subnet, or disk path is already in use |
7 | integrity | Digest, catalog signature or signed revision, instance identity, or file ownership verification failed |
130 | cancelled | Interrupted by SIGINT/SIGTERM or interactive confirmation declined |
sshandexecreturn the remote command’s exit code verbatim, so text output, JSONexit_code, and the process status agree.255can mean either an OpenSSH transport failure or a remote command that exited255.- Deployment lock: When another
barnprocess holds the deployment, mutating commands wait up to 10 minutes while naming the holder, then exit4withreason: "deployment_busy". Read-only and access commands (status,ssh,exec,ssh-config,hosts) do not wait;statusshows the last committed state and names the active operation innote. - 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 withreason: "catalog_equivocation". Permission and I/O errors while reading a cached signature are runtime failures (exit1).
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:
| Field | Present | Meaning |
|---|---|---|
error | Always | Error class from the exit code table |
message | Always | Human-readable summary |
reason | When known | Stable snake_case cause for automation |
next | When known | Suggested next command |
operation_id | When assigned | Correlates with barn logs --source events |
command | An external program failed | name, argv, exit_status, signal, timed_out, stderr |
failures, rolled_back | Exit 5 from a lifecycle batch | Failed nodes and rolled-back preparations, as in Lifecycle results |
Common reason values on Linux commands:
reason | error | Cause and usual next step |
|---|---|---|
no_inventory | usage | No inventory in the current directory: barn init, or pass -f |
unknown_node | usage | A selector is not a node name in the inventory or deployment |
unknown_image | usage | The image selector is not in the active catalog |
qemu_missing | capability | QEMU is missing or unusable; next names the fix |
network_absent | capability | The Barn network is not installed: barn setup |
sudo_unavailable | capability | sudo failed, or needs a password while stdin is not a terminal |
no_deployment | conflict | BARN_HOME holds no applied deployment: barn up |
node_not_running | conflict | The node is stopped: barn start <node> |
resize_required | conflict | Drift that barn resize applies |
recreate_required | conflict | Drift that needs barn plan, then barn recreate <node> |
nodes_removed | conflict | The inventory omits existing nodes; see Lifecycle results |
deployment_changed | conflict | Applied state changed during recreate preflight; review and retry |
deployment_busy | conflict | Another command held the lock for 10 minutes |
interrupted_transition | conflict | A node is still mid-transition after an interrupted command; run the next command |
hosts_name_taken | conflict | /etc/hosts maps a Barn name outside the Barn-owned block |
disk_full | resource | The host disk ran out of space |
image_integrity | integrity | A 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:
| Command | stdin is a terminal | stdin is not a terminal |
|---|---|---|
recreate, destroy | Lists 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 prompt | Exit 2 unless --yes or --force is given (there is no -y) |
setup | Shows the plan and asks once | Requires --yes, else exit 2; --dry-run previews and cannot be combined with --yes |
network, hosts install/uninstall | Shows the privileged plan and asks (install defaults to yes, uninstall to no); with --json/--yaml it only previews | Prints 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 missing | Shows the host-preparation plan and asks once, as setup does; an interactive up with neither an inventory nor a deployment also generates meta | Reports 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,
-fmeans--file(exceptbarn logs -f, which is--follow),-nmeans--no-wait(barn mac logs -nsets the line count), and-dmeans--dry-run. - Safety and repository flags are long-form only:
--ask,--mirror,--force,--rollback,--remove,--allow-downgrade,--sudo,--delete-persistent,--purge. -yexists only where a command’s option table lists it; ondestroyandrecreate,--yesis the same as--force.- Path arguments such as
-f,--script, a local--repo,image importsources, andreporoots 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:
| Field | Contents |
|---|---|
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_config | Event-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:
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
-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 (
sudoforwards 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
uporstart, a missing host share or a failed new-node preparation affects only that node; independent stopped nodes still start, and the command exits5with 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; astopinterrupted while the VM kept running marks itrunning. After an onlineresizeinterrupted mid-change,statusreportsresize_incomplete: retrybarn resize <node>or runbarn restart <node>. Other interrupted transitions print the recovery command (destroyresolves them directly), and the next run after a failed initialuprolls back uncommitted journal artifacts automatically. - Event log:
setupand the lifecycle run that follows share oneoperation_id. Even if setup fails before a deployment exists,barn logs --source events --jsonshows the bounded phase log, without sensitive arguments or credentials;setup --dry-runwrites none. - Retained persistent disks: Disks left by a previously removed node do not block destroying the remaining nodes; delete them with
destroy --delete-persistentorpurge. - macOS setup:
setupfinishes Homebrew discovery or installation and the pinnedsocket_vmnetdownload before asking for administrator privileges, so a slow download cannot expire an earliersudotoken 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 variable | Purpose |
|---|---|
BARN_HOME | Private 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_DISK | VM specification overrides; CLI takes priority. Read only by commands accepting each field; see specification overrides |
BARN_REPO | Default image repository URL or path; overridden by --mirror and --repo |
BARN_OUTPUT | Default output format (text, json, or yaml); overridden by --json/--yaml |
BARN_VERBOSE | Boolean default for diagnostic output; overridden by -v/--verbose |
BARN_VMNET_ARCHIVE | Path to a local pinned socket_vmnet archive for macOS setup; accepts relative paths, ~/, and symlinks (SHA-256 verification still applies) |
NO_COLOR | Any 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
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.
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 macas the logged-in desktop user. Commands that talk to the runner rejectrootwithmac_root, and a host that is not Apple Silicon on macOS 27 or later withmac_host_unsupported. Disk space and the two-VM limit are under requirements. - On Linux and Intel Macs,
barn --helphidesmac. Commands that only read local state, such asbarn mac image ls, work without the runner. barn macwith no subcommand runsbarn 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 Homebrewlibexeclayouts.BARN_MAC_RUNNERoverrides 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.
| Setting | New machine default | Change it with |
|---|---|---|
| CPUs | 4 | configure --cpu, while stopped |
| Memory | 8 GiB | configure --memory, while stopped |
| Shared folders | none | configure --share / --unshare, while stopped |
| Subnet | first free /24 | configure --subnet, while stopped |
| Clipboard sync | on | configure --clipboard, anytime; applies at the next start |
| Disk capacity | the prepared base’s capacity, or 100 GiB for the first base | fixed |
| Administrator account | your host macOS username, or barn if that is not a valid account name | fixed |
| macOS build | the default base | recreate --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
passwordfile (mode0600) and printed bybarn mac password. - Hostnames: the guest ComputerName is
<name>and LocalHostName isbarn-<name>(reachable asbarn-<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 --sharewith 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_limitand 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.
| Item | Value |
|---|---|
| Subnet | First 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 |
| Reachability | Host-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:
sshjoins the arguments after--into one command string for the guest shell, as plainsshdoes. Without a command it opens an interactive shell.execpasses the program and each argument separately, so spaces, quotes, and empty arguments arrive intact. It requires a command. Wrap pipelines, redirection, and compound commands insh -c '...'. For compatibilityexecalso accepts a single command string as shell shorthand; new scripts should pass separate arguments or an explicitsh -c.
Argument rules for both commands:
- A remote command always follows
--, and its first argument must not be empty. Interactivebarn mac ssh devneeds 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, withbarn mac lsas the next step. --jsonneeds 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).
| Field | Values |
|---|---|
base | The default base for new machines |
machines[].image | The base this machine was cloned from |
state | prepared (created, first boot not completed), starting, running, stopping, stopped, unknown |
ready | true when this check verified guest SSH and passwordless sudo |
ssh | ready, pending (first boot in progress), unavailable, offline, unchecked |
observed | Present when the running guest reports a macOS build different from its base |
window_visible | Present while the desktop window is open |
error, warnings | The last failure recorded for the machine, and SSH issues found during this check |
running, limit | Machines 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.
| Field | Values |
|---|---|
action | created, started, running (already running), restarted, recreated, opened, configured, stopped, powered_off, already_stopped, destroyed, absent |
forced | true 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) |
window | true when the desktop window was opened |
warnings | Non-fatal notices, such as a clipboard change that takes effect at the next start |
Other commands:
exec --json: the same schema as Linuxbarn exec --json(node,exit_code,stdout,stderr).password --json:nameandpassword, or{"name": "mac1", "copied": true}with--copy.ssh-config --json:fragmentwhen printing; installation status with--installor--remove.logs --json:nameandlogs.doctor --json:okandchecks[](name,ok,detail, optionalnext); exits3if 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.
| Reason | Exit | Meaning and next step |
|---|---|---|
mac_host_unsupported | 3 | Host is not Apple Silicon or is running macOS older than 27 |
mac_runner_missing | 3 | Barn.app / native runner is not installed alongside the barn CLI |
mac_runner_protocol | 3 | Installed Barn.app uses a different runner protocol version; reinstall matching CLI and app builds |
mac_root | 2 | Invoked as root; run as the logged-in desktop user without sudo |
mac_download_consent | 2 | Non-interactive macOS download requires --yes (or supply a local file with --ipsw) |
mac_machine_absent | 4 | Named VM does not exist; create it with barn mac up NAME |
mac_not_initialized | 4 | VM has not finished its first boot; complete initialization with barn mac up NAME |
mac_not_running | 4 | ssh or exec called on a stopped VM; run barn mac start NAME |
mac_running | 4 | Requested configuration change requires the VM to be stopped; run barn mac stop NAME |
mac_configuration_conflict | 4 | up flags differ from the existing VM; run the suggested configure or recreate command |
ssh_config_linked | 4 | ~/.ssh/config is a symlink or hard link; add the printed Include line manually |
mac_vm_limit | 6 | Two macOS VMs are already running on this Mac; stop the reported VM first |
mac_subnet_in_use | 6 | A host route overlaps the VM’s subnet; run barn mac configure NAME --subnet auto |
disk_full | 6 | Insufficient free disk space to download or install the macOS base image |
mac_machine_damaged | 7 | An initialized VM slot is missing its disk or identity files (the slot directory is preserved for inspection) |
mac_readiness_interrupted | 130 | barn 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
- ipsw/
- 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
- <name>/
- 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-configmanages~/.ssh/barn-mac_configand a# barn-mac:includeblock in~/.ssh/config, independent of the Linux# barn:includeblock.barn mac ssh-config --removesetsssh_config_offinconfig.json, so lifecycle commands stop re-adding theIncludeblock until you runbarn mac ssh-config --install. - Desktop preferences: window positions live in
~/Library/Preferences/com.pgsty.barn.plist(0.9.0used~/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, setsComputerNameandLocalHostName, and disables idle sleep withpmset.
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
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.
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
| Family | stable in 2026120302 | Family aliases | Architecture aliases (arm64 / amd64) |
|---|---|---|---|
d13 | 20261130.2678.1 | d, debian, debian13, trixie | d13a, da / d13x, d13i, dx, di |
d12 | 20261130.2678.1 | debian12, bookworm | d12a / d12x, d12i |
el7 | 7.9.20221112.0 | c7, centos7, centos79 | — / el7x, el7i, c7x, c7i |
el8 | 8.10.20240528.3 | rocky8 | el8a / el8x, el8i |
el9 | 9.9.20261112.1 | rocky9 (rocky in 1.2.0) | el9a / el9x, el9i |
el10 | 10.3.20261112.1 | e, el, rocky, rocky10 | el10a, ea, ela / el10x, el10i, ex, ei, elx, eli |
u22 | 20261109.0.1 | ubuntu22, ubuntu2204, jammy | u22a / u22x, u22i |
u24 | 20261017.0.1 | ubuntu24, ubuntu2404, noble (ubuntu in 1.2.0) | u24a / u24x, u24i |
u26 | 20261108.0.1 | u, ubuntu, ubuntu26, ubuntu2604, resolute | u26a, 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, andu26are Ubuntu 22.04, 24.04, and 26.04 LTS;d12andd13are Debian 12 and 13. Barn’s image recipe builds them from the distributions’ cloud images: the image ships adbauser (UID/GID 88), XFS userspace tools are present, anden_US.UTF-8is available whileC.UTF-8stays the default locale.el7is CentOS Linux 7.9 (amd64BIOS), andel8,el9, andel10are Rocky Linux (amd64andarm64UEFI). All three Rocky families go through Barn’s recipe (dba, UID/GID 88). The currentel10images also include signed kernel modules required by Docker’s default bridge networking, iptables firewall rules, and overlay filesystem.el7remains the distribution’s unmodified cloud image.cloud-initconfigures 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 recreateoperations resolve the selected image against the active catalog. Catalog rotation tests
| Alias | Distribution | Architectures | Boot | Status |
|---|---|---|---|---|
el7 | CentOS Linux 7.9 / 2211 | amd64 | BIOS | deprecated |
el8 | Rocky Linux 8.10 | amd64, arm64 | UEFI | deprecated |
el9 | Rocky Linux 9.9 | amd64, arm64 | UEFI | supported |
el10 | Rocky Linux 10.3 | amd64, arm64 | UEFI | supported |
d12, d13 | Debian 12 / 13 | amd64, arm64 | UEFI | supported |
u22 | Ubuntu 22.04 LTS | amd64, arm64 | UEFI | deprecated |
u24, u26 | Ubuntu 24.04 / 26.04 LTS | amd64, arm64 | UEFI | supported |
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:
- 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 updateorbarn image sync). - Resolve the selector and architecture — Resolves
image[:channel]orimage@version-prefix(or the active catalog’s default if omitted) and the target architecture. Bare aliases in standaloneimage pulldefault to the host, while architecture-suffixed aliases selectarm64oramd64directly; lifecycle commands usevm_arch(or an architecture-suffixed alias), also defaulting to the host when unset.--arch/-Aoverrides non-pinned choices and rejects conflicting pinned aliases; see configuration precedence. - Verify the local cache — Reuses an existing cached file immediately if its byte size, SHA-256 digest, and
qemu-imgstructural checks all pass. - 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
qcow2header before moving it into the cache. The two official mirrors (https://repo.pigsty.io/barnandhttps://repo.pigsty.cc/barn) can fall back to each other during artifact downloads, while custom--reposources 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).
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 updatefetches, verifies, and activates the current catalog from--repoor--mirror.barn image syncactivates 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 resetreverts 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.
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 andimages/may be shared writable directories.repo.yamlmay link to a non-empty regular file up to 4 MiB. Artifact entries remain regular files;catalog.jsonoutput symlinks are not overwritten. - Boot mode inherits along
variant→family→defaults.boot; status inherits alongvariant→version→unknown. Every family must define the default channel pointing to an existing version, and family/alias names must be unique and cannot start withlocal-. 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): barn repo scanis read-only and does not requireqemu-img; it exits0while reporting anymissing,unsafe, oruntrackedfiles in its output arrays (automation must check thatmissingandunsafeare empty).barn repo buildandbarn repo verifyuseqemu-img. An unchanged rebuild preserves the catalog bytes. If you setrevisionexplicitly, 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:
Import rules:
image importaccepts relative paths,~/, and symlinks to regular files, and requiresqemu-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--sha256verifies an expected digest.image importcopies and validates theqcow2container as-is without modifying guest credentials, installingcloud-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|uefiand--source-user <user>and default to the host architecture.--arch/-Acan record an explicitamd64orarm64architecture, including aliases. The qcow2 metadata cannot identify the guest CPU, and import does not convert architectures. Match inventoryvm_archor the lifecycle command’s-Awhen using the image. Aliases are immutable and can be referenced viavm_image: local-mybase; unnamed imports only pre-populate the cache and cannot accept-A.
Pruning
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
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:
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.
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.
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.
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
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.
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.
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.
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.
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
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;offlinemode also needs workinglibguestfstools (virt-customize,virt-cat). Override them with--qemu-img,--virt-customize, and--virt-cat, or withQEMU_IMG,VIRT_CUSTOMIZE, andVIRT_CAT. - Storage: keep source images, RPM/DEB package caches, and output directories outside the Git working tree, which tracks only recipes and lockfiles.
- Architecture:
--archrecords the target architecture in the metadata; runofflinecustomization wherelibguestfscan execute that architecture.
Modes and profiles
validatecopies and re-hashes the source, checks that it is a single-fileqcow2withqemu-img check, and writes an evidence bundle without touching guest files or credentials.offlinenormalizes guest access on a staged copy withvirt-customize --no-networkandvirt-cat: it confirms UID/GID88is free of unrelated accounts, configures the lockeddba/adminidentity, disables SSH password and root login, strips SSH host keys, shell history, machine-id, andcloud-initcaches, restores SELinux labels, and reads back a deterministic guest marker.
The profile adds distribution-specific steps; build.sh defaults to --profile base:
| Profile | Normalization steps | Package inputs |
|---|---|---|
base | Account, sudo, SSH, and cloud-init normalization only | None (package flags rejected) |
el8 | Base normalization plus Python 3, SSH drop-in include, legacy network cleanup, chronyd, and SELinux relabeling | Locked RPM dependency set |
el9 | Base normalization plus legacy network cleanup and SELinux relabeling | None (package flags rejected) |
el10 | Base normalization plus signed kernel-modules and kernel-modules-extra matching kernel-core, Docker bridge/iptables/overlay module verification, and SELinux relabeling | Locked RPM dependency set |
d12, d13 | Base normalization plus offline XFS userspace tools and en_US.UTF-8 / C.UTF-8 locale setup | Locked 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
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:
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 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:
| File | Purpose |
|---|---|
<name>-<release>-<arch>-<digest-prefix>.qcow2 | Validated read-only candidate qcow2 image |
build-recipe.json | Builder invocation, tool versions, and input digests |
manifest-candidate.json | Unsigned candidate metadata (status: "testing") |
provenance.intoto.json | SLSA build provenance statement |
sbom.spdx.json | SPDX software bill of materials covering declared pipeline inputs and injected packages |
validation.json | Before/after qcow2 checks, normalization marker results, and pending release gates |
checksums.txt | SHA-256 checksums of the other files in the bundle |
package-lock.json | Included 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:
- Run live VM smoke tests across the target host and guest combinations.
- Update
repo.yamlwith the new catalogrevisionandsupportedstatus. - Run
barn repo buildandbarn repo verify. - Sign
catalog.jsonand publish its detached signature ascatalog.json.minisig. - Verify the published repository endpoints.