# Automation and Guest Scripts

> Prepare an unattended lab, check JSON results, and run repeatable scripts inside selected guests.

---

LLMS index: [llms.txt](/v1.5/llms.txt)

---

Barn commands print JSON with `--json` and return documented exit codes, so CI jobs and AI agents can drive a lab without a terminal. This page starts with a complete unattended run, then covers what a script needs to check and how to run commands inside guests. Run every command as the Unix user who owns the deployment, with the same `BARN_HOME` and `-f <inventory>` each time.

## Run a lab end to end {#run-a-lab-end-to-end}

Run this example under a dedicated CI account with one lab job at a time on the host. `BARN_HOME` isolates VM state. Jobs on the same host share the lab network, and jobs under the same account share its SSH aliases.

```bash {title="ci-lab.sh"}
#!/usr/bin/env bash
set -euo pipefail
export BARN_HOME="$HOME/.barn-ci"      # reserved for this CI lab
trap 'barn purge' EXIT                 # discard the lab when the job ends, even on failure

barn validate -f barn.yml              # committed inventory with a pinned vm_image
barn setup -f barn.yml --yes           # install host packages and the Barn network
barn up -f barn.yml --json > up.json   # non-zero exit if any node failed
jq -e '
  ((.warnings // []) | length == 0) and
  (.nodes | length > 0 and all(.ready and
    ((.warnings // []) | length == 0) and
    ((.repairs // []) | length == 0)))
' up.json

barn exec meta -- hostname
barn provision --script ./check-lab.sh --json > provision.json
```

1. `barn setup --yes` accepts the host-preparation plan without asking. It needs `sudo` that works without a password prompt (cached credentials or a `NOPASSWD` rule); what it installs is described in [`barn setup`](../../reference/commands/setup/#barn-setup).
2. `barn up` exits non-zero when a node fails. Barn verifies each ready marker over management SSH. Optional guest warnings can accompany a successful run, so the example checks command-level `warnings` as well as each node’s `warnings` and `repairs`.
3. `barn exec` and `barn provision` run commands and scripts in the guests; see [below](#run-single-commands-or-batch-scripts).
4. `barn purge` deletes the deployment in this `BARN_HOME`, persistent disks and keys included, without asking. The image cache stays, so the next run does not download again. Use `barn destroy --yes` instead to keep persistent disks.
{.steps}

## Prepare a predictable lab {#prepare-a-predictable-lab}

Commit the inventory and pin `vm_image` to an exact version, such as `vm_image: d13@20261123.2671.1`; a channel like `d13:stable` can move to a new image after `barn update`. Always pass `-f`; it also stops first-run `setup` from moving an unedited generated template to a different subnet. With a custom image repository, run `barn update --repo URL` first and pass the same `--repo` to `setup` and `up`.

To write and check an inventory, then preview the host changes:

```bash
mkdir -p ~/barn-lab
cd ~/barn-lab
release=$(barn --json image info d13 | jq -er '.entry.release')
barn init dual -I "d13@$release"
barn version
barn validate -f barn.yml
barn plan -f barn.yml
barn setup -f barn.yml --dry-run
```

`barn init [template] --image <reference>` writes `all.vars.vm_image`, so every node uses the same image; the reference can be an alias (`el9`), a channel (`d13:stable`), or a version (`d13@20261123.2671.1`). `barn init full -I d13 -A amd64` saves both image and architecture. `barn setup [template] --image` works the same way, but only when it generates the template.

On `validate`, `plan`, `up`, `reload`, `recreate`, and `resize`, `--image/-I`, `--arch/-A`, `--cpu/-C`, `--mem/-M`, `--scale/-S`, and `--disk/-D` override the inventory for one invocation. Values come from the flag, then a nonempty `BARN_*` variable, then the inventory, then the default, so give `plan` and the command that applies it the same flags and environment: `barn plan -f barn.yml -I d13 -A arm64 --json`, then `barn up -f barn.yml -I d13 -A arm64`. Existing VMs need `recreate` to change image or architecture ([Image and architecture](../../reference/configuration/#image-and-architecture)).

Without a terminal, `up`, `start`, `restart`, and `reload` never prepare the host themselves; they report what is missing and fail. Run `barn setup --yes` before them.

## Validate JSON output alongside the exit code {#validate-json-output-alongside-the-exit-code}

Barn writes JSON or YAML results to `stdout` and diagnostics to `stderr`. With the default wait, `barn up` checks each selected node’s readiness marker over management SSH. It can exit `0` even if an optional stage such as a secondary data disk, a Virtio-9p share, or peer SSH configuration reported a limitation (`nodes[].warnings`), or Barn [reformatted a damaged test disk](../storage/#when-barn-resets-a-data-disk) (`nodes[].repairs`). A script that needs a fully working lab checks both:

```bash {title="up-check.sh"}
#!/usr/bin/env bash
set -euo pipefail

if barn up -f barn.yml --json > up.json 2> up.stderr; then
  jq -e '
    (.nodes | type == "array" and length > 0) and
    all(.nodes[];
      .state == "running" and .ready == true and
      ((.warnings // []) | length == 0) and
      ((.repairs // []) | length == 0)) and
    ((.warnings // []) | length == 0)
  ' up.json || exit 1
else
  barn_exit=$?
  cat up.stderr >&2
  cat up.json
  exit "$barn_exit"
fi
```

Don't pass `--no-wait` when a later step needs ready guests. `barn status --json` reports the recorded state without probing guest SSH again.

### Exit codes and command-specific payloads {#exit-codes-and-command-specific-payloads}

The full table and the JSON failure object are in [Exit codes](../../reference/cli/#exit-codes) and [Structured failures](../../reference/cli/#structured-failures). The codes scripts most often branch on:

| Exit | `error` | Typical cause in automation |
|---:|---|---|
| `2` | `usage` | Missing inventory on first run, invalid flags, unknown image alias, or `destroy`/`recreate` without `--yes` when stdin is not a terminal |
| `4` | `conflict` | Drift that needs an explicit command (`reason: recreate_required` or `nodes_removed`), state changed during a `recreate` preflight (`deployment_changed`), or another command held the deployment lock for 10 minutes (`deployment_busy`) |
| `5` | `partial` | Some nodes of a multi-node `up` or `provision` failed; read `nodes[]` or `results[]` before retrying |
| `7` | `integrity` | A digest, signature, or identity check failed, including `reason: catalog_signature` or `catalog_equivocation` |
{.wide .expand}

A few commands report success differently:

- `barn doctor --json` exits `0` when host compute checks pass, even if a `class: network` check reports an error. Read `checks[]` and `barn network status --json` before relying on the fixed-IP network.
- `barn ssh` and `barn exec` exit with the remote command's status (`255` can also mean an OpenSSH transport failure); with `--json` they return `success`, `exit_code`, `stdout`, and `stderr`.
- `barn network` and `barn hosts` `install`/`uninstall` only print their plan and exit `0` when `--yes` is missing and stdin is not a terminal or output is `--json`/`--yaml`. Pass `--yes`, or check `applied` in the result.

## Run single commands or batch scripts {#run-single-commands-or-batch-scripts}

Put `--` between the node and the remote command, and Barn flags such as `--json` before it:

```bash
barn exec meta -- hostname
barn exec node-1 -- sh -c 'id; df -h /data'
barn exec meta --json -- uname -a > uname.json
```

`barn exec` passes the program and each argument separately, so use `sh -c` for pipes, redirection, or variables ([Remote commands](../../reference/commands/access/#remote-commands)).

For anything longer, write a local Bash script (a regular file, or a symlink to one, up to 4 MiB):

```bash {title="check-lab.sh"}
#!/usr/bin/env bash
set -euo pipefail
hostname
id
findmnt /data
test -d /data
```

Run it on selected nodes, or on every node when you name none; all targets must be running:

```bash
barn provision --script ./check-lab.sh meta node-1
barn provision --script ./check-lab.sh --parallel 2 --timeout 5m --json > provision.json
```

Barn streams the script to Bash over SSH, so no copy is left in the guest, and records its SHA-256 in the event log and in the result (`script.sha256`).

| Option or limit | Behavior |
|---|---|
| `--parallel` | Positive integer; default `1` (serial). Workers never exceed the number of selected nodes |
| `--timeout` | Deadline for the whole operation; default `1h`, any positive duration |
| `--sudo` | Runs the script through non-interactive `sudo -n` |
| Output | Up to 1 MiB each of `stdout` and `stderr` per node; `stdout_truncated` / `stderr_truncated` mark a cut |
| Exit code | `5` when some nodes succeed and others fail; a single target's own positive exit code other than `255`; `1` otherwise |
{.wide .expand}

A failed run does not undo what already ran in the guests, so write scripts that are safe to run again.

## Pair the lab with Pigsty {#pair-the-lab-with-pigsty}

Barn reads the same Ansible inventory that [Pigsty](https://pigsty.io/docs/) uses, so the VMs come up with the names and fixed IPs Pigsty expects to deploy to. Let Pigsty write the inventory, then create the VMs from it:

```bash
cd pigsty                 # your Pigsty checkout
./configure -c full       # writes the four-node pigsty.yml
barn validate -f pigsty.yml -I d13
barn plan -f pigsty.yml -I d13
barn up -f pigsty.yml -I d13
barn ssh
```

`barn up` creates the admin account in every guest and gives the control node at `admin_ip` the deployment key and an SSH configuration that reaches every peer on its fixed IP, which is what Ansible needs ([Security and Trust](../../about/security/)). `barn ssh` logs in to that control node; run Pigsty's playbooks from there.
