# Environments and deploys

> Deploy safely on Latchkey CI: name an environment in a job, approve or reject its runs, limit it to branches, give it secrets, and read its settings from the CLI.

Source: https://latchkey.dev/documentation/environments-and-deploys

## Summary

- A job that names an environment with `environment:` waits for an owner or admin to approve its run, unless the environment is set to need no approval.
- Approve or reject on the run page's **Approval for** panel, or with `POST /jobs/{id}/approval` and a key allowed to approve. If nobody decides within 24 hours, the waiting jobs end without starting, and their wait is never billed.
- In [Settings, Environments](https://latchkey.dev/documentation/settings#environments), an owner or admin sets the branches whose runs may use an environment, and whether its jobs wait for an approval on them.
- Only an approved job, or one whose environment needs no approval, is handed the secrets set for its environment.
- `latchkey environments list --repository <owner/name>` reads each environment's branches and approval setting; no workflow file and no API key can change them.

Video: [Deploys with rules](https://www.youtube.com/watch?v=zZImb3L8uno) (0:59)

## How an environment guards a deploy

An environment is a name a job writes after `environment:`, such as `production`. There is nothing to create first: writing the name in a workflow file is enough. A job that names one waits, in every run that reaches it, until an owner or admin of the workspace approves or rejects that run for that environment, unless the environment's settings say otherwise (see Branches and approval below) or the job is held in a trial run. That includes runs Latchkey starts itself, such as the run that checks a fix self-heal proposed. The run's other jobs go on meanwhile, and a job that needs a waiting job waits with it.

- **An approval.** An owner or admin decides each run, on the run page or through the Jobs API.
- **Branches.** An owner or admin can limit an environment to the branches whose runs may use it, and let its jobs start without an approval on those branches.
- **Secrets.** The secrets set for an environment reach only a job whose run was approved for it, or a job in a run on its branches when it needs no approval.

## Name an environment in a job

`environment:` takes one of three forms. The first is one plain name, such as `environment: production`: it starts with a letter or a digit and then uses letters, digits, `.`, `_` and `-` only, up to 64 characters, and case counts, so `Production` and `production` are two environments. The second is a whole `${{ matrix.<axis> }}`, so each leg of a matrix names its own environment from its value. The third is a map of branches, which chooses the name by the run's branch. The GitHub Actions mapping with `name:` and `url:`, a list and any other expression are each refused by name.

`.latchkey/workflows/deploy.yml`
```yaml
on:
  push:
    branches: [main]
jobs:
  test:
    runs-on: small
    steps:
      - run: npm ci && npm test
  deploy:
    needs: test
    runs-on: small
    environment: production
    steps:
      - run: ./deploy.sh
```

On a push to `main`, `deploy` starts only after `test` passes, and then waits for a decision for `production`. In a trial run, a job that names an environment and writes no `advisory:` is held and runs nothing; [Workflow files](https://latchkey.dev/documentation/workflow-files) says how `advisory: run` gives it a dry run instead.

## Choose the environment by branch

yaml:
```yaml
on:
  push:
jobs:
  deploy:
    runs-on: small
    environment:
      main: production
      "**": staging
    steps:
      - run: ./deploy.sh
```

Each key of a map of branches is one branch pattern, as `branches:` under `on: push` takes them but never starting with `!`, and each value is a plain name. The first key, in the file's order, that matches the run's branch chooses. A push chooses by its own branch, a pull request and a merge group by the branch they target, a scheduled run by the default branch, and a manual run by the branch it was started on. In the example, a push to `main` deploys to `production` and a push to any other branch to `staging`.

So `"**"` as the last key covers every branch the keys above it do not. A key naming one branch in full that a key above it already matches, and any key after `"**"`, is refused, since it could never be chosen. Patterns that overlap are not refused: with `release/**` above `release/beta*`, the upper key wins on every branch both match. A tag push keys on no branch, so it matches no key. The same map chooses an input's value under a Latchkey step's `with:` (see [Latchkey steps](https://latchkey.dev/documentation/steps)).

## When no key matches

When a job would run on a branch that no key of its map matches, the whole run is refused before any job starts. For a run a push, a pull request or a merge group started, the Latchkey check names the file, the job, the key and the branch, and the commit runs nothing more for four days, on any branch, with the exceptions [Workflow files](https://latchkey.dev/documentation/workflow-files) lists for the default branch and for pull requests from forks. A scheduled run or a manual run refused this way writes no check and holds back no other run. A job needs no key when its own `if:` is false for the run, or when a job it needs, directly or through others, is skipped when the run is planned.

To clear the refusal, add a key for the branch or a last `"**"` key, or move the job into a file whose `on:` names only the map's branches, and push a new commit. The branch self-heal pushes to verify a fix, `latchkey/heal-*`, is a branch like any other: in a file whose `on: push` takes every branch, a job with a map and no key for it refuses that verification run, and the Latchkey check on the heal pull request's commit says so.

## Approve or reject a run

One decision covers every job of the run attempt that names that environment, every leg of a matrix included. A matrix whose `environment:` is `${{ matrix.<axis> }}` asks one decision for each environment its legs name. Only an owner or admin of the workspace can decide, and the person who pushed the commit can decide like any other owner or admin. A decision cannot be taken back, and a re-run asks again.

On the run page, each environment the run's jobs name gets an **Approval for** panel above the jobs, with the jobs the decision covers. While the run waits, the panel says since when, and by when the jobs end without starting if nobody decides. An owner or admin presses **Approve** or **Reject**, and confirms in a dialog that names the environment, such as "Approve this run for production?"; **Keep waiting** closes the rejection's dialog without deciding. A member sees the same panel without the buttons. Once the run is decided, the panel says who approved or rejected it and when, or, when the environment needed no approval, who set it so and when.

An approval sends the jobs on to run, with the secrets set for the environment. A rejection ends each of them without starting it, and the jobs that need them are skipped. A run nobody decides within 24 hours ends the same way. Neither is billed, and neither counts as a failure of your code: the jobs read Stopped, and a run with no failing job concludes neutral, so its Latchkey check does not block a merge.

An approval is refused when the branches the environment accepts changed after the run started and no longer accept it. Reject the run, or change the branches in [Settings, Environments](https://latchkey.dev/documentation/settings#environments).

## Approve through the Jobs API

An agent or a script decides with `POST /jobs/{id}/approval` on any of the run's waiting jobs, with the body `{"decision": "approve"}` or `{"decision": "reject"}` and nothing else. It needs a key with the `jobs:approve` scope: one created with the **Approve runs** or **Full access** preset, or with **Allow approving runs for an environment** under **Customize access**, in Settings, API keys and agents. The key works only while the person who created it is an owner or admin. An agent that holds such a key and can also push to a repository can approve the runs of its own changes, with no other person deciding.

A recorded decision answers with `job_id`, `run_id`, `attempt`, `environment`, `decision`, and the counts of jobs it `released` and `rejected`. The other answers, besides a 401 for a missing or invalid key:

| Status | When |
| --- | --- |
| 400 | The body is not exactly one of the two decisions. |
| 403 | The key lacks the `jobs:approve` scope, the person who created it is not an owner or admin now, or the workspace has no active subscription or trial. |
| 404 | The workspace has no such job. |
| 409 | The job is not waiting for an approval, the run was already approved or rejected for that environment, or the environment's branches no longer accept the run. |
| 503 | Latchkey could not record the decision just then. Send it again. |

## Branches and approval in Settings, Environments

In [Settings, Environments](https://latchkey.dev/documentation/settings#environments), an owner or admin presses **Set branches and approval**, picks the repository, writes the environment's name and its branches, one pattern per line, and picks the approval: **An owner or admin approves each run**, or **Jobs start without an approval in runs on these branches**. The table lists each environment with branches set, by repository, with its branches, its approval (Required or Not required), who set it (at the Pro level) and when, and **Replace** and **Clear** for each row. A member reads the table and cannot change it.

The patterns are the ones `branches:` under `on: push` takes: `main`, `release/*`, and `!release/old` after it to leave one out. A job that names an environment with branches set goes on only in a run on one of those branches. In any other run, including a run of a tag and one Latchkey started for a pull request's own ref, it ends without starting and without asking for an approval, and the jobs that need it are skipped. It is not billed, and it never fails the run's Latchkey check. A scheduled run is judged by the default branch it runs on. Each run and each re-run reads the branches when it starts, and again when an approval would release one of its jobs. An environment with no branches set accepts every branch, and its jobs always wait for an approval.

Only an environment with branches set can be set to need no approval. Its jobs then start as soon as a run on one of its branches reaches them, with its secrets and an identity token in the environment form, and nobody is asked. A job already waiting on one of those branches starts within about a minute, and setting approval back never stops a job already released. Its branches cannot be cleared until it requires an approval again.

> **Warning**
>
> Without an approval, a job that names the environment starts as soon as a run on its branches reaches it, with the environment's secrets and an identity token your cloud roles trust as this environment, and nobody is asked. Those branches are then its only guard.

No workflow file and no API key can change these settings: a job's own command can hold a key, and a rule a job could widen would protect nothing.

## Environment secrets

An owner or admin sets a secret for one environment of one repository in [Settings, Secrets](https://latchkey.dev/documentation/settings#secrets); a member can set workspace and repository secrets but not environment ones, and no API key can set one. A step reads it like any other secret, by writing `${{ secrets.NAME }}` as the whole value of a variable in its `env:`. Only a job in that repository that names the environment is handed it, once its run is approved for the environment, or in a run on the environment's branches when the environment needs no approval.

yaml:
```yaml
jobs:
  deploy:
    runs-on: small
    environment: production
    steps:
      - run: ./deploy.sh
        env:
          DEPLOY_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
```

An environment secret wins over a repository secret of the same name, and a repository secret wins over a workspace one. A name set at none of the levels its job can see refuses the run before any job starts. A run of a pull request from a fork is handed no secrets, and a value shorter than 28 bytes is never delivered, because the log could not hide it.

To sign in to a cloud without a stored key, a job's identity token carries its environment once its run is approved for it, or when the environment needs no approval, and your cloud's trust can match that. Until then the job has no token, and it never has one in a run on a branch the environment does not accept. [Cloud identity](https://latchkey.dev/documentation/cloud-identity) shows the subject to trust.

## Pull requests and merge groups

For a pull request, a map of branches and an environment's branches read different refs. A pull request into `main` takes the key for `main`, but the environment's branches are judged against the pull request's own ref: if they are `main` alone, that job ends without starting, and if the environment has no branches set, its approval is asked to run the pull request's code. A merge group is judged the same way: it takes the key for the branch it targets, and the environment's branches are judged against its queue branch, so a job of a group runs in an environment only when the environment's branches include the queue, such as `gh-readonly-queue/main/*`.

To keep pull requests off a deploy job, gate it on the event:

yaml:
```yaml
jobs:
  deploy:
    if: env.LATCHKEY_CI_EVENT_CLASS == 'branch_push'
    runs-on: small
    environment: production
    steps:
      - run: ./deploy.sh
```

## Not supported yet

Reviewer lists and wait timers are not supported yet. An environment is the name a workflow file writes, with its secrets set in [Settings, Secrets](https://latchkey.dev/documentation/settings#secrets) and its branches and its approval in [Settings, Environments](https://latchkey.dev/documentation/settings#environments), and every owner or admin of the workspace can decide its runs.

A job whose environment Migrate carries from GitHub Actions keeps it, so on Latchkey CI the job waits for an approval once its pipeline runs live, whether or not its GitHub environment requires a reviewer, unless that environment's settings in Settings, Environments say otherwise. The Plan step says so under each such job.

## From the CLI

Video: [latchkey environments list](https://www.youtube.com/watch?v=h_dbTU_Oc2k) (0:39)

terminal:
```console
$ latchkey environments list --repository acme/api
$ latchkey environments list --repository acme/api --output json
```

`latchkey environments list --repository <owner/name>` lists each environment of one repository that has branches set, with the columns Environment, Branches, Approval (Required or Not required) and Set at. An environment it does not list accepts every branch, and its jobs always wait for an approval. With `--output json` it prints `repository` and `environments`, each with `environment`, `branches`, `requires_approval` and `set_at`. The key needs the `jobs:read` scope, and the MCP tool `list_environments` reads the same settings. The command needs CLI 0.6.0 or later, and the Approval column CLI 0.9.0 or later. It only reads: the settings change in the dashboard alone.

`latchkey workflows rerun <run-id> --repository <owner/name>` (CLI 0.17.0 or later, with a key that has `runs:control`) starts a new attempt of a run, and that attempt asks for its approvals again. The command names on stderr the environments the attempt waits for, and with `--output json` it lists them in `waits_for_approval`. The CLI has no command that approves: decide on the run page or through the Jobs API.

---

Latchkey runs CI/CD that repairs its own failures. Agent entry points: https://latchkey.dev/agent.txt, https://latchkey.dev/openapi.json, https://latchkey.dev/llms.txt
