# Describe your servers in a file

Instead of clicking or typing one command per server, you can write down what you want in one file, `apidly.yaml`, and let the [command-line tool](/docs/cli) make your account match it. This is often called "infrastructure as code". It helps when you want the same setup again next week, want a teammate to start exactly what you start, or keep the setup next to your code in Git.

There are three commands:

- `apidly plan` reads the file, compares it with your account and prints what would be created, changed or left alone, with the hourly price of what is new. It changes nothing.
- `apidly apply` shows the same plan, asks you to confirm and then makes the changes.
- `apidly export` writes your current servers, volumes and SSH keys as a file, so you do not have to start from an empty page.

You need the `apidly` command (see [Command-line tool](/docs/cli)), signed in with an [API key](/docs/api-keys) that may deploy servers.

## A first file

Save this as `apidly.yaml` in an empty folder:

```yaml
# yaml-language-server: $schema=https://apidly.com/schemas/apidly.schema.json
version: 1
stack: my-project

ssh_keys:
  - name: laptop
    public_key_file: ~/.ssh/id_ed25519.pub

servers:
  - label: notebook
    template: pytorch
    gpu:
      min_memory_gb: 24
      max_hourly_usd: 1.00
    disk_gb: 80
    ssh_keys: [laptop]
    env:
      MODE: train
    secrets:
      HF_TOKEN: HF_TOKEN
    auto_stop:
      after_hours: 4
    tags: [experiments]
```

What it says:

- `version: 1` and `stack: my-project` are required. The stack name is how the tool recognizes its own servers again: every server it creates gets the tag `apidly-stack:my-project`.
- `ssh_keys` names the SSH keys the servers use. If you have no key called `laptop` yet, it is added from the public key file. Keys are never removed.
- `servers` lists the servers, each found again by its `label`. `template` is a slug from `apidly templates`.
- `gpu` lets the tool choose: the cheapest plan in stock whose GPU has at least `min_memory_gb` of memory and that costs at most `max_hourly_usd` per running hour, disk included. `max_hourly_usd` is your own limit: put the most you want to pay. If you prefer a fixed plan, write `plan:` with a slug from `apidly plans` instead of `gpu:`.
- `env` holds ordinary settings. `secrets` maps a variable to the name of a [stored secret](/docs/secrets); the value stays in your account and never appears in the file.
- `auto_stop` stops the server after 4 hours of running. The disk is kept, so you can start it again. `idle_minutes` stops it when the GPU has been idle that long instead (or as well).

The first line is optional. It tells editors such as VS Code (with a YAML extension) where the schema is, so they underline mistakes and suggest keys while you type.

## Preview, then apply

```bash
apidly secrets set HF_TOKEN      # once: the value is read from a hidden prompt
apidly plan
apidly apply
```

`plan` prints one line per thing in the file:

```text
Stack my-project (apidly.yaml), servers tagged apidly-stack:my-project

  + create       ssh key   laptop    from ~/.ssh/id_ed25519.pub
  + create       server    notebook  ...  $X.XX/h

Plan: 2 to create, 0 to change, 0 to leave, 0 would be deleted with --prune.
Price of what would be created: $X.XX per hour (servers while running, disk included), from the prices the API lists now.
```

`+ create` is new, `~ change` is changed in place, `= leave` already matches, and `- would delete` belongs to the stack but is no longer in the file (see the safety rules below). The price comes from the same price list as the console; the tool never estimates one itself.

`apply` prints the same plan and asks before it does anything. Type `y` to go ahead. In a script, add `--yes`. Run `apidly apply` again and it says there is nothing to do: running it twice never creates a second server.

If your organization [reviews new servers](/docs/why-was-my-request-reviewed), the plan shows the request as waiting and apply does not ask for another one.

## Start from what you already have

```bash
apidly export > apidly.yaml
apidly plan
```

`export` writes your servers, volumes and SSH keys. Servers that are not in a stack yet show up in the plan as `~ change` with "take into this stack": apply adds the stack tag to them and nothing else. Use `--stack NAME` to choose the stack name (the default is `main`).

The values of variables and secrets cannot be read back from a running server, so the exported file has none. They only matter when a server is created; add them before you create new servers from the file.

## What apply changes, and what it never does

On a server that already exists, apply changes only what can change without starting over:

- its tags (the file's list becomes the server's list, plus the stack tag),
- its automatic stop (`auto_stop`).

The plan, template, disk size, pricing and variables of an existing server are never changed. If they differ from the file, the plan shows them as "not changed" and explains why. To get the new setup, destroy that server and run apply again, or change the file to match.

## Volumes

```yaml
volumes:
  - name: datasets
    size_gb: 100
    plan: PLAN_SLUG

servers:
  - label: notebook
    template: pytorch
    plan: PLAN_SLUG
    volume:
      name: datasets
      mount_path: /data
```

Replace `PLAN_SLUG` with a slug from `apidly plans`. A volume lives on one machine, so it is made on a machine that offers the plan you will use with it. The plan shows its price per hour from the volume offer the API quotes. A volume cannot be resized, and apply never deletes one. See [Storage](/docs/storage).

## Serverless endpoints

```yaml
endpoints:
  - name: chat-api
    plan: PLAN_SLUG
    template: TEMPLATE_SLUG
    min_workers: 0
    max_workers: 2
    idle_seconds: 300
    max_hourly_spend_usd: 5
```

Endpoints are found again by name. Apply creates them and changes their workers, idle time, spending limit, template and disk (changing the template or disk replaces the workers one by one). It never deletes an endpoint. The price shown is for the minimum workers; for `--max-hourly-usd` an endpoint counts at its most workers, or its spending limit if that is lower. See [Serverless endpoints](/docs/endpoints).

## Safety rules

- **Nothing is deleted unless you ask twice.** A server of the stack that you removed from the file is only listed. `apidly apply --prune` destroys it, and only if it still carries this stack's tag when apply gets to it. Servers without the tag, servers of other stacks, volumes, endpoints and SSH keys are never deleted.
- **A price ceiling.** `--max-hourly-usd 2.50` makes apply refuse, before it creates anything, when what it would create costs more than that per hour. `plan` takes the same option and says whether the file fits.
- **No secrets in the file.** Store them with `apidly secrets set NAME` and list them under `secrets:` by name. A variable whose name looks like a password, token or key (`HF_TOKEN`, `DB_PASSWORD`, `API_KEY` ...) with a value under `env:` is refused, so it cannot end up in Git by mistake. `public_key_file` must point at the public `.pub` file; a private key is refused.
- **Safe retries.** Every request that creates something carries an `Idempotency-Key`, so a retry after a dropped connection cannot create it twice. If apply stops halfway (for example because the balance ran out), what was done stays done; fix the cause and run apply again.
- **Problems are found before anything starts.** A wrong key, a template or secret that does not exist, or a `gpu` block that no plan in stock fits stops `plan` and `apply` with the line number in the file, and nothing is sent.

## Use it in CI

The commands need no terminal, so a CI pipeline can run them: `apidly plan` on every pull request, and `apidly apply` once the change is merged and a person has approved it. What the command-line tool does for that:

- **The key comes from the secret store.** Set `APIDLY_API_KEY` in the job from your CI service's secrets; nothing is saved on the runner. Give the plan job a key with the `read` scope: plan only reads, so that key cannot change anything. Such a key cannot list secret names, so plan does not check the ones the file uses; apply checks them when it creates. The apply job needs the `servers` scope (`full` if the file adds SSH keys). See [API keys](/docs/api-keys).
- **An exit code for changes.** `apidly plan --detailed-exitcode` exits with `0` when apply would have nothing to do and with `3` when it would change something. `1` is still a failure and `2` a typing mistake, so a script can tell them apart.
- **Output for programs.** `apidly plan --json` prints the plan as JSON: every action with its `kind`, `op`, `name` and `summary`, the hourly price of what is new as `createHourlyUsd`, and `hasChanges`. Errors go to stderr, also as JSON.
- **Apply never asks there and never goes ahead by itself.** When stdin is not a terminal, or the `CI` variable is set (the common CI services set it), apply asks nothing: without `--yes` it stops with exit code `1` and changes nothing. Put `--yes` only in the job that runs after the approval, and keep `--max-hourly-usd` on it, so an edit to the file cannot start more than you meant to pay for.

Install the CLI in the job as on your own computer, with the checksum check. These lines read the newest version from `latest.json`; write a fixed version instead if you want repeatable runs:

```bash
version="$(curl -fsSL https://apidly.com/downloads/latest.json | node -e 'let s="";process.stdin.on("data",(d)=>{s+=d}).on("end",()=>{process.stdout.write(JSON.parse(s).files.find((f)=>f.kind==="cli").version)})')"
file="apidly-cli-${version}.tgz"
curl -fsSLO https://apidly.com/downloads/SHA256SUMS
curl -fsSLO "https://apidly.com/downloads/${file}"
grep -F "$file" SHA256SUMS | sha256sum -c -
npm install -g "./${file}"
apidly --version
```

A GitHub Actions workflow, saved as `.github/workflows/apidly.yml`, that posts the plan as the job summary and applies on `main` after an approval:

```yaml
name: apidly
on:
  pull_request:
    paths: ["apidly.yaml"]
  push:
    branches: [main]
    paths: ["apidly.yaml"]
permissions:
  contents: read
env:
  APIDLY_MAX_HOURLY_USD: "5"

jobs:
  plan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
      - name: Install the apidly CLI
        run: |
          # the install lines above
      - name: Plan
        env:
          APIDLY_API_KEY: ${{ secrets.APIDLY_PLAN_API_KEY }}
        run: |
          set +e
          apidly plan --detailed-exitcode --max-hourly-usd "$APIDLY_MAX_HOURLY_USD" > plan.txt 2>&1
          code=$?
          set -e
          cat plan.txt
          { echo '~~~text'; cat plan.txt; echo '~~~'; } >> "$GITHUB_STEP_SUMMARY"
          if [ "$code" -ne 0 ] && [ "$code" -ne 3 ]; then exit "$code"; fi

  apply:
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'
    needs: plan
    runs-on: ubuntu-latest
    environment: apidly-production
    concurrency:
      group: apidly-apply
      cancel-in-progress: false
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
      - name: Install the apidly CLI
        run: |
          # the install lines above
      - name: Apply
        env:
          APIDLY_API_KEY: ${{ secrets.APIDLY_API_KEY }}
        run: apidly apply --yes --max-hourly-usd "$APIDLY_MAX_HOURLY_USD"
```

Before the first run, open **Settings > Environments** in the repository, create the environment `apidly-production`, add the people who approve under **Required reviewers**, and store the apply key there as the secret `APIDLY_API_KEY`: GitHub hands it to the job only after the approval. Store the `read` key as the repository secret `APIDLY_PLAN_API_KEY`. Pull requests from forks get no secrets, so their plan stops with "Not signed in".

In GitLab CI/CD, run the plan lines in a merge request pipeline and keep `plan.txt` as an artifact (`expose_as` links it from the merge request). The apply job waits until someone starts it:

```yaml
apidly-apply:
  stage: apply
  image: node:22
  needs: [apidly-plan]
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
      changes: [apidly.yaml]
      when: manual
  allow_failure: false
  environment:
    name: apidly-production
  resource_group: apidly-apply
  # before_script: the install lines above
  script:
    - apidly apply --yes --max-hourly-usd "$APIDLY_MAX_HOURLY_USD"
```

Store both keys under **Settings > CI/CD > Variables**, masked; protect the apply key and limit it to the environment `apidly-production`. On any other CI service, run the install lines, then `apidly plan --detailed-exitcode` on every change and `apidly apply --yes` behind that service's own manual approval step.

## The file, key by key

| Key | Meaning |
| --- | --- |
| `version` | Always `1`. |
| `stack` | Name of the stack: 1 to 19 characters, `a-z`, `0-9` and `-`. |
| `ssh_keys[]` | `name`, and `public_key_file` to add a key that is not in your account yet. |
| `volumes[]` | `name`, `size_gb` (10 to 2000), `plan`. |
| `servers[]` | `label`, `template`, then `plan` or `gpu` (`min_memory_gb`, `max_hourly_usd`, `count`, `model`), `disk_gb`, `ssh_keys`, `env`, `secrets`, `volume` (`name`, `mount_path`), `auto_stop` (`after_hours`, `idle_minutes`, `idle_below_pct`), `tags` (up to 9). |
| `servers[].pricing` | `on_demand` (the default) or `interruptible`, see [Interruptible servers](/docs/interruptible). |
| `endpoints[]` | `name`, `plan`, `template`, `disk_gb`, `env`, `secrets`, `min_workers`, `max_workers`, `idle_seconds`, `max_hourly_spend_usd`, `http_port`, `health_path`. |

The full schema is published at `https://apidly.com/schemas/apidly.schema.json` and inside the CLI package (`schema/apidly.schema.json`). The file may also be JSON with the same keys (`-f apidly.json`).

The YAML reader is deliberately strict and small: it understands keys, lists, quoted and unquoted values, one-line lists such as `[a, b]`, and `#` comments. It refuses tabs, anchors (`&`, `*`), multi-line text blocks (`|`, `>`) and repeated keys, with the line number, rather than guess. `yes` and `no` are text, not true and false; write `true` or `false`.
