Scripting and Automation

Observable Anka CLI behavior, exit codes, streams, file durability, and shutdown patterns for CI and automation scripts.

Use this page when you write CI pipelines or host scripts around the Anka CLI. It covers JSON output, command execution, stream behavior, file transfers, VM shutdown, and checks your script needs to run on the host.

For the full list of commands, options, and environment variables, see the Command-line Reference and Modifying the Global Configuration.

One of the most common problems when getting started is the usage of sudo for anka commands. Anka will run for all users on a machine, but they will have isolated environments. If you create an Anka VM Template/Tag as UserA, sudo/root will not be able to see or use them. Also, the Anka Build Cloud Controller will start VMs as root, so be sure to clean up any VM Templates and Tags you have under UserA or else the disk space will become a problem. It’s suggested to just run all anka commands as root.

Machine-readable output (-j)

Pass -j / --machine-readable (or set ANKA_MACHINE_READABLE=1) to get JSON on stdout instead of formatted tables:

{
  "status": "OK",
  "code": 0,
  "body": {}
}

When a command fails with -j, status is "ERROR", code is the numeric status code, and message holds the error text:

{
  "status": "ERROR",
  "code": 2,
  "body": {},
  "message": "my-vm: not found"
}
anka run passes guest stdout and stderr directly through to the host, so -j does not wrap guest output in JSON. Parse guest output directly or write structured results to a file.

Querying VM lists and properties

❯ anka list                        
+----------------------+--------------------------------------+---------------------+---------+
| name                 | uuid                                 | creation_date       | status  |
+----------------------+--------------------------------------+---------------------+---------+
| 12.2.0-arm (vanilla) | a6f24306-2af7-45ed-9d70-3a3c1ee7f03a | Jan 6 12:34:52 2022 | stopped |
+----------------------+--------------------------------------+---------------------+---------+
| test_vm1             | 565e47ce-a9f9-4ac8-81bc-645d48473de1 | Jan 6 12:34:52 2022 | stopped |
+----------------------+--------------------------------------+---------------------+---------+

❯ anka --machine-readable list | jq
{
  "status": "OK",
  "body": [
    {
      "name": "12.2.0-arm",
      "uuid": "a6f24306-2af7-45ed-9d70-3a3c1ee7f03a",
      "creation_date": "2022-01-06T12:34:52Z",
      "version": "vanilla",
      "status": "stopped"
    },
    {
      "name": "test_vm1",
      "uuid": "565e47ce-a9f9-4ac8-81bc-645d48473de1",
      "creation_date": "2022-01-06T12:34:52Z",
      "status": "stopped"
    }
  ]
}

❯ anka --machine-readable list --field name --field version | jq
{
  "status": "OK",
  "body": [
    {
      "name": "12.2.0-arm",
      "version": "vanilla"
    },
    {
      "name": "test_vm1"
    }
  ]
}

Starting in Anka 3.7.0, you can filter anka list output by appending =value to a field name, and choose which columns appear:

❯ anka list --field name,status=stopped
+-----------------------------+---------+
| name                        | status  |
+-----------------------------+---------+
| 15.1.1-xcode-16_16.1_16.2RC | stopped |
+-----------------------------+---------+
| 15.3.2                      | stopped |
+-----------------------------+---------+

❯ anka list --field name=15.3,status
+--------+---------+
| name   | status  |
+--------+---------+
| 15.3.2 | stopped |
+--------+---------+

❯ anka list --field name,status,uuid,ip,vnc_port

❯ anka -j list --field name,status,uuid,ip,vnc_port | jq
❯ anka show 12.2.0-arm                   
+---------+--------------------------------------+
| uuid    | a6f24306-2af7-45ed-9d70-3a3c1ee7f03a |
+---------+--------------------------------------+
| name    | 12.2.0-arm (vanilla)                 |
+---------+--------------------------------------+
| created | Jan 6 12:34:52 2022                  |
+---------+--------------------------------------+
| vcpu    | 4 ARM                                |
+---------+--------------------------------------+
| ram     | 4G                                   |
+---------+--------------------------------------+
| display | 1024x768                             |
+---------+--------------------------------------+
| disk    | 128GiB (17.72GiB on disk)            |
+---------+--------------------------------------+
| addons  | 3.0.0.135.13568747                   |
+---------+--------------------------------------+
| network | shared                               |
+---------+--------------------------------------+
| status  | stopped Jan 6 18:10:17 2022          |
+---------+--------------------------------------+

❯ anka --machine-readable show 12.2.0-arm | jq
{
  "status": "OK",
  "body": {
    "uuid": "a6f24306-2af7-45ed-9d70-3a3c1ee7f03a",
    "name": "12.2.0-arm",
    "version": "vanilla",
    "creation_date": "2022-01-06T12:34:52Z",
    "cpu_cores": 4,
    "cpu_frequency": 0,
    "cpu_htt": false,
    "arch": 2,
    "ram": "4294967296",
    "ram_size": 4294967296,
    "frame_buffers": 1,
    "hard_drive": 137438953472,
    "encrypted": false,
    "image_size": 19035295744,
    "addons_version": "3.0.0.135.13568747",
    "stop_date": "2022-01-06T18:10:17Z",
    "status": "stopped"
  }
}

❯ anka --machine-readable show 12.2.0-arm --tag v2 | jq                     
{
  "status": "OK",
  "body": {
    "uuid": "a6f24306-2af7-45ed-9d70-3a3c1ee7f03a",
    "name": "12.2.0-arm",
    "version": "v2",
    "creation_date": "2022-01-14T12:18:31Z",
    "cpu_cores": 4,
    "cpu_frequency": 0,
    "cpu_htt": false,
    "arch": 2,
    "ram": "4294967296",
    "ram_size": 4294967296,
    "frame_buffers": 1,
    "hard_drive": 137438953472,
    "encrypted": false,
    "image_size": 19528679424,
    "addons_version": "3.0.0.135.13568747",
    "stop_date": "2022-01-14T17:19:08Z",
    "status": "stopped"
  }
}

Running commands and handling streams (anka run)

> anka run --help
usage: run [options] vmid

   Run a command inside of a VM

arguments:
  vmid                     VM name or identifier (will be started if needed)

options:
  -D,-w,--workdir <val>    Working directory inside the VM
  -E                       Inherit the entire environment in non-overriding mode
  -e <val>                 Provide an environment variable in overriding mode
  -f,--env-file <val>      Provide environment variables from file
  -q,--quiet               Suppress the stdout from the command
  -b,--background          Background the command inside of VM, returning inner VM PID
anka run executes the guest command directly and does not read shell startup files for that command. ankarun, from Anka Addons inside the VM, imports the VM user’s login-shell environment when ankarun starts. To read startup files for one command, run bash -lc, bash -ic, zsh -lc, or zsh -ic.

Run exit codes, signals, and streams

When the guest command finishes, anka run returns its exit code. For CLI and launch errors, anka run returns:

  • 125 if Anka cannot start or connect to the VM
  • 126 if the guest command cannot be executed due to permissions
  • 127 if the guest command is not found or waiting for the process fails

While a foreground command runs, anka run forwards SIGHUP, SIGINT, SIGQUIT, SIGTERM, SIGINFO, SIGUSR1, and SIGUSR2 to the guest process. To launch a command without blocking, pass -b / --background to print the guest PID immediately, then wait on one or more PIDs later with anka run <vm> wait [pid...].

anka run runs without a TTY over standard POSIX stdin, stdout, and stderr. stdout and stderr stay separate, so you can redirect them to different files or pipes on the host. Closing host stdin sends EOF to the guest process’s stdin. Host stdout and stderr both close when the guest command exits, not separately mid-command; if the guest closes stdout early while keeping stderr open, host readers will not see stdout EOF until the command exits. If writing stdout or stderr on the host fails (for example, when a host pipe closes early), anka run drops the remaining output and still returns the guest command’s exit code.

If a guest command writes files inside the VM that you plan to read back or keep across a shutdown, run sync inside the guest before exiting the command or stopping the VM. If a host-redirected output file must survive a host crash right after anka run exits, flush it on the host with fsync or sync.

Capturing stdout and stderr separately

Because anka run keeps stdout and stderr separate, redirect each stream to its own host file or pipe:

anka run my-vm bash -lc "your-build-command" \
  > /tmp/build.stdout.log \
  2> /tmp/build.stderr.log
RUN_EXIT=$?

If a host pipe reader needs to know when output finishes before the guest command exits, print a sentinel line from the guest command instead of waiting for an early EOF.

Shell Configuration Files / Environment

anka run executes the guest command directly. That command does not read shell startup files.

Anka Addons run inside the VM and provide anka run. Their ankarun program reads the VM user’s login shell when ankarun starts, and it imports that environment into later anka run commands. On Apple Silicon the user shell is /bin/zsh, so ankarun imports ~/.zshenv, ~/.zprofile, and ~/.zlogin. It does not import ~/.zshrc. Edits to these files apply after the next VM start, when ankarun starts again. When the user shell is bash, ankarun imports the bash login files instead: /etc/profile, then the first file that exists among ~/.bash_profile, ~/.bash_login, and ~/.profile.

SHELL in the imported environment is that user shell. On Apple Silicon, printenv SHELL prints /bin/zsh.

This example writes four files while the VM is already running. ankarun has already started, so anka run env does not show the new variables yet. bash -lc and zsh -lc read their own login files for that one command.

❯ anka run "${VM_NAME}" bash -c "echo 'export TEST_ZSHRC=yes' >> ~/.zshrc"
anka run "${VM_NAME}" bash -c "echo 'export TEST_ZPROFILE=yes' >> ~/.zprofile"
anka run "${VM_NAME}" bash -c "echo 'export TEST_PROFILE=yes' >> ~/.profile"
anka run "${VM_NAME}" bash -c "echo 'export TEST_BASH_PROFILE=yes' >> ~/.bash_profile"

❯ anka run "${VM_NAME}" /usr/bin/printenv SHELL
/bin/zsh

❯ anka run "${VM_NAME}" env | grep TEST_

❯ anka run "${VM_NAME}" bash -c "env | grep TEST_"

❯ anka run "${VM_NAME}" bash -ic "env | grep TEST_"

❯ anka run "${VM_NAME}" bash -lc "env | grep TEST_"
TEST_BASH_PROFILE=yes

❯ anka run "${VM_NAME}" zsh -c "env | grep TEST_"

❯ anka run "${VM_NAME}" zsh -ic "env | grep TEST_"
TEST_ZSHRC=yes

❯ anka run "${VM_NAME}" zsh -lc "env | grep TEST_"
TEST_ZPROFILE=yes

❯ anka stop "${VM_NAME}"

❯ anka run "${VM_NAME}" env | grep TEST_
TEST_ZPROFILE=yes

❯ anka run "${VM_NAME}" bash -c "env | grep TEST_"
TEST_ZPROFILE=yes

❯ anka run "${VM_NAME}" bash -ic "env | grep TEST_"
TEST_ZPROFILE=yes

❯ anka run "${VM_NAME}" bash -lc "env | grep TEST_"
TEST_ZPROFILE=yes
TEST_BASH_PROFILE=yes

❯ anka run "${VM_NAME}" zsh -c "env | grep TEST_"
TEST_ZPROFILE=yes

❯ anka run "${VM_NAME}" zsh -ic "env | grep TEST_"
TEST_ZPROFILE=yes
TEST_ZSHRC=yes

❯ anka run "${VM_NAME}" zsh -lc "env | grep TEST_"
TEST_ZPROFILE=yes

~/.profile is absent from every result above. Bash reads ~/.bash_profile and does not continue to ~/.profile when ~/.bash_profile exists. Zsh does not read ~/.profile.

zsh -c reads ~/.zshenv immediately, including before the next VM start. This example does not write ~/.zshenv, so zsh -c prints no TEST_ variables. After the next VM start, variables exported from ~/.zshenv and ~/.zlogin are present in every command, together with ~/.zprofile.

InvocationStartup files that command reads
anka run <command>None. The process receives the environment ankarun imported at its start.
bash -cNone.
bash -ic~/.bashrc
bash -lcThe first existing file of ~/.bash_profile, ~/.bash_login, and ~/.profile.
zsh -c~/.zshenv
zsh -ic~/.zshenv and ~/.zshrc
zsh -lc~/.zshenv, ~/.zprofile, and ~/.zlogin. Not ~/.zshrc.

To pass host environment variables into the guest:

  • anka run -E adds host variables that are not already set in the VM. A variable that already exists in the VM stays unchanged. Host variables whose names start with ANKA_ are not passed.
  • anka run -e NAME=VALUE sets NAME and replaces an existing VM variable with the same name. anka run -e NAME uses the host value of NAME.
  • anka run --env-file environment.txt reads NAME=VALUE lines and replaces an existing VM variable with the same name. Put one variable on each line. A line that starts with ; is a comment.

Do not combine -E with -e or --env-file.

Transferring files and verifying durability (anka cp)

> anka cp --help
usage: cp [options]

   Copy files in/out of the Anka VM and host:
       cp [options] <vmid>:path/inside </path/on/host>
       cp [options] </path/on/host> <vmid>:[path/inside]

options:
  -R                       copy the src and its entire subtree to the dst
  -L                       all symbolic links are followed
  -H                       symbolic links in the command are followed
  -P                       do not follow a symbolic links (default)
  -f                       remove and create the dst file on open failure
  -n                       do not overwrite an existing file.
  -p                       preserve the source file attributes
  -a                       same as -pPR options
  -v                       cause cp to be verbose, showing files as they are copied

Copy behavior and durability

anka cp <vm>:<src> <host_dst> reads the file from the guest and writes it to the host before returning. Flush the destination file on the host if it must survive a host crash right after anka cp exits.

anka cp <host_src> <vm>:<dst> returns exit code 1 if the guest parent directory is missing or the target volume is already full. If a write fails mid-transfer (for example, when the guest volume fills up during the copy), anka cp can exit 0 and leave a truncated file in the guest.

When a script copies files into a VM and needs to confirm the full file landed, check the file size or shasum inside the VM via anka run, and run sync in the guest if you stop the VM right afterward. On Apple Silicon, consider sharing host directories with anka mount instead of copying files back and forth.

Verifying file integrity across host and guest

# Host -> Guest with checksum verification
EXPECTED_SHA=$(shasum -a 256 /path/on/host/input.tar.gz | awk '{print $1}')
anka cp /path/on/host/input.tar.gz my-vm:/tmp/input.tar.gz
anka run my-vm bash -lc "
  sync
  ACTUAL_SHA=\$(shasum -a 256 /tmp/input.tar.gz | awk '{print \$1}')
  test \"\${ACTUAL_SHA}\" = \"${EXPECTED_SHA}\"
"

# Guest -> Host with guest sync before copy
anka run my-vm bash -lc "your-command > /tmp/result.json && sync"
anka cp my-vm:/tmp/result.json /tmp/result.json
❯ time anka cp ~/VirtualBox\ VMs/cloud-client-side-ha-1/cloud-client-side-ha-1.vdi 10.15.6:/Users/anka/
anka --debug cp  10.15.6:/Users/anka/  0.86s user 20.60s system 4% cpu 8:53.85 total

Compare the ~9 minutes it takes for anka cp to how much it takes to transfer the same file with scp:

❯ time scp -P 10000 -v ~/VirtualBox\ VMs/cloud-client-side-ha-1/cloud-client-side-ha-1.vdi [email protected]:/Users/anka/
scp -P 10000 -v  [email protected]:/Users/anka/  110.61s user 60.88s system 22% cpu 12:46.30 total

Sharing host directories (anka mount)

On Apple Silicon, you can mount host directories into a running VM instead of copying files with anka cp. Check the sync rules below before sharing mutable files between host and guest scripts.

Due to limitations in the way Apple allows us to mount host directories inside of the VM, we cannot guarantee that the host and guest will always have the same file contents.

Host ⇄ Guest shared folder sync limitations

OperationDirectionSupportedNotes
Create new file/folderHost → Guest✅ YesNew paths appear in the guest
Create new file/folderGuest → Host✅ YesNew paths appear on the host
Read existing contentsHost → Guest✅ YesContents present at mount time are visible
Modify file in placeGuest → Host✅ YesGuest edits are written through to the host
Modify file in placeHost → Guest❌ NoGuest keeps stale contents for already-accessed files (macOS virtiofs caching)
Delete file/folderGuest → Host✅ YesRemoval is reflected on the host
Delete file/folderHost → Guest❌ NoGuest still sees the path after the host deletes it (cached)
Replace via temp + rename() (atomic)Host → Guest✅ YesNew inode/dentry; recommended way to update files from the host

Why the host → guest gaps exist

  • The in-guest mount at /Volumes/My Shared Files is performed by macOS’s own automounter.
  • Apple’s Virtualization.framework exposes no API to tune virtiofs caching (attr_timeout, cache=, DAX), so the guest caches dentries/attributes and does not re-validate when the host changes an already-seen path.
  • This is a platform limitation, not specific to Anka — any tool built on Virtualization.framework behaves the same way.

Recommendation for users

  • Best practice: make changes inside the guest when you need them reflected on the host (fully bidirectional).
  • When changing files on the host, prefer creating new files or atomic replace (write to a temp file, then mv/rename() over the target) instead of editing in place, so the guest picks up the change.

For full usage and examples, see Sharing Host Directories.

Stopping VMs (anka stop and anka show)

> anka stop --help
usage: stop [options] [vmid...]

   Shut down a VM(s)

arguments:
  vmid                     VMs to stop

options:
  -a,--all                 Shutdown all running VMs
  -f,--force               Forcefully stop the VM(s)

Stop behavior and timeouts

anka stop <vm> requests an orderly macOS shutdown inside the guest and waits in the foreground until the VM exits. anka stop --force <vm> stops the VM right away without waiting for macOS to shut down, so in-flight guest disk writes are not flushed. Use --force only when a VM does not respond.

Graceful shutdown waits up to operations_timeout seconds (default 300, set via anka config operations_timeout or ANKA_OPERATIONS_TIMEOUT). If the guest does not power off before the timeout, or if guest addons are not connected, anka stop falls back to a forced stop.

A few behaviors matter in scripts:

  • Interrupting anka stop (SIGINT or SIGTERM) stops the CLI from waiting, but it does not cancel a shutdown request that was already sent to the guest.
  • anka stop returns exit code 0 even after a timeout fallback or when guest addons are not connected. Check anka -j show <vm> after anka stop returns if your script needs to confirm the VM stopped.
  • If a graceful anka stop <vm1> <vm2> hits operations_timeout, earlier VMs in the list can stay running while the command still exits 0. Stop one VM per anka stop <vm> call and check each VM’s status afterward.

Stop examples

# Graceful shutdown (waits up to operations_timeout, default 300s)
❯ anka stop my-vm

# Graceful shutdown with a shorter timeout for one command
❯ ANKA_OPERATIONS_TIMEOUT=120 anka stop my-vm

# Forceful stop when a VM is unresponsive
❯ anka stop --force my-vm

# Stop all running VMs
❯ anka stop --all

# Machine-readable output
❯ anka -j stop my-vm
{"status":"OK","code":0,"body":{}}

VM status values

anka show and anka list report one of three status values:

StatusMeaning
runningThe VM is started and accepting CLI requests.
stoppedThe VM is stopped.
suspendedThe VM has saved state (see anka suspend).
If your automation accesses VM disk or state files directly on the host after a stop, confirm that anka -j show <vm> reports status: "stopped" and verify no host process holds open handles on the VM directory before reading or copying VM storage.

CLI guarantees vs. external host checks

The table below shows what the Anka CLI handles and what your script needs to check on its own:

RequirementCovered by Anka CLIWhat to check in your script
Guest command exit statusYes (anka run returns guest exit code, or 125/126/127 on CLI/exec errors)Check $? after anka run.
Separate stdout and stderr captureYes (streams stay separate over POSIX descriptors)Redirect > and 2> independently.
Detecting host stdout/stderr write errors during anka runNo (anka run drops remaining bytes on host write failure and still returns the guest exit code)Verify expected output files or markers on the host after anka run exits.
Independent per-stream EOF before process exitNo (both streams close when anka run exits)Print a sentinel line if a pipe reader needs mid-run boundaries.
Crash-durable host output filesNot guaranteed by CLIFlush host output files (fsync or sync) after anka run or anka cp if they must survive a host crash.
Detecting mid-transfer host-to-guest anka cp truncationNo (path/open errors exit 1, but filling the guest volume mid-write can exit 0 with a truncated file)Verify file size or shasum inside the VM via anka run.
Confirming graceful stop vs. forced fallbackPartial (anka stop waits up to operations_timeout, then falls back and exits 0; multi-VM timeout stops can leave earlier VMs running)Stop one VM per anka stop <vm> call and check status == "stopped" with anka -j show <vm>.
Confirming host VM file handles are closed before accessing VM storage directlyConfirm status == "stopped" via anka -j show <vm>If accessing host VM storage directly, check with lsof against the VM directory under vm_lib_dir / img_lib_dir.

Relevant global configuration options

Check or set these values with anka config, or override them for one command with ANKA_<UPPERCASE_NAME>:

SettingDefaultPurpose in automation
operations_timeout300Maximum seconds anka stop waits for graceful guest shutdown before falling back to a forced stop.
ANKA_MACHINE_READABLE0Set to 1 to enable JSON output globally (same as -j).

End-to-end automation example

This script runs a build inside a VM, splits stdout and stderr into separate logs, copies out a result file, and stops the VM:

#!/usr/bin/env bash
set -euo pipefail

VM_NAME="my-build-vm"
STDOUT_LOG="/tmp/${VM_NAME}.stdout.log"
STDERR_LOG="/tmp/${VM_NAME}.stderr.log"
ARTIFACT_HOST="/tmp/build-result.json"

cleanup() {
  anka stop "${VM_NAME}" >/dev/null 2>&1 || true
}
trap cleanup EXIT

# 1. Start the VM
anka start "${VM_NAME}"

# 2. Run the workload, separating stdout/stderr and syncing guest files
set +e
anka run "${VM_NAME}" bash -lc '
  set -euo pipefail
  echo "Starting build..."
  echo "{\"ok\": true}" > /tmp/build-result.json
  sync
' > "${STDOUT_LOG}" 2> "${STDERR_LOG}"
RUN_STATUS=$?
set -e

if [[ "${RUN_STATUS}" -ne 0 ]]; then
  echo "Guest command failed with status ${RUN_STATUS}" >&2
  cat "${STDERR_LOG}" >&2
  exit "${RUN_STATUS}"
fi

# 3. Copy the artifact back to the host and verify it is non-empty
anka cp "${VM_NAME}:/tmp/build-result.json" "${ARTIFACT_HOST}"
test -s "${ARTIFACT_HOST}"

# 4. Stop the VM gracefully and confirm status
anka stop "${VM_NAME}"
VM_STATUS=$(anka -j show "${VM_NAME}" | jq -r '.body.status')
if [[ "${VM_STATUS}" != "stopped" ]]; then
  echo "Expected VM status 'stopped', got '${VM_STATUS}'" >&2
  exit 1
fi