# Operator mode

In operator mode the CLI still builds and plans on your machine, but the
Kix operator running in the cluster makes the changes. The CLI writes an
Activation record that names the build's store path, then watches the
record's status until the operator finishes. The operator applies with the
same engine as `kix deploy` and, while an activation is Active, re-applies
resources that have drifted and deletes the record's cluster's resources that
the build no longer has. It reads only the resources of the record's Kix
cluster, named by the record's `kix.run/cluster` label (or `spec.cluster` when
the label is missing), found through the
[revisions](/docs/reference/annotations-crds-and-receipts/#packageinstancerevision)
its Activation records name. It keeps a resource another Kix cluster still
deploys, both when it prunes and when a deleted record's
finalizer removes that record's resources.

This page is hand-maintained. Check `cli/kix-cli/src/commands/operator.rs`,
`cli/kix-operator/src/main.rs`, and the command files when in doubt.

## What the operator does today

:::caution[Work in progress]
The Kix operator is a work in progress, and operator mode is currently
push-based. The operator cannot pull and build from a Git repository on its own
yet; pull-based Git sync is planned.
:::

- **Installation:** The release archive includes `kix-operator` alongside
  `kix`, but Kix does not yet provide a package or manifest to deploy
  `kix-operator` in a cluster.
- **What runs where:** You run `kix deploy --operator`,
  `kix rollback --operator`, and `kix gc --operator` on your machine or in CI.
  `kix` evaluates and builds the cluster, shows the plan, and writes an
  Activation record (`activations.kix.run`) whose `spec.source.path` points to
  the build in Kix's local store. Inside the cluster, `kix-operator` watches
  Activation records, reads the built manifests from `spec.source.path`, and
  applies them with the same engine as [`kix deploy`](/docs/reference/cli/deploy/).
  Because the operator never clones a Git repository, evaluates `.nix` files, or
  builds anything, the build at `spec.source.path` must already exist in the
  store the operator reads.
- **Drift repair:** While an Activation is `Active`, `kix-operator` re-applies
  drifted resources and deletes Kix-managed resources removed from the build.
  It checks every 300 seconds by default (override with the
  `KIX_REQUEUE_INTERVAL_SECS` environment variable). It only repairs records
  with `spec.source.path` set, so it ignores records created by `kix deploy`
  without `--operator`. Drift repair pauses while another operator-managed
  Activation for the same Kix cluster is `Queued` or `Deploying`. It decides
  what to repair using the same rules as `kix deploy` (see
  [How a deploy decides what to write](/docs/reference/cli/deploy/#how-a-deploy-decides-what-to-write)),
  except that the operator never forces fields away from another field manager.
  When another manager modified fields set by the build (for example, via
  `kubectl edit`), the operator leaves that resource untouched, emits a
  `DriftNotReverted` Warning Event naming the manager and fields, and continues
  repairing all other resources (including dependents). Run `kix deploy` to
  take those fields back, or list them in `ownership.cede` if the other manager
  should keep owning them. On a resource with no `managedFields` entry for this
  Kix cluster, the operator applies without force, adding its entry when values
  match. Fields listed in `ownership.cede` never count as drift, while changes
  with no owning manager (such as a deleted field or `kubectl scale --replicas=0`)
  are repaired automatically. If an earlier version of Kix last deployed the
  cluster, the first drift repair converts its deployment records to revisions,
  just like `kix deploy`.
- **Deploying from Git today:** Run `kix deploy` (with or without `--operator`)
  from CI after a merge.

## Commands

| Command | With `--operator` |
| --- | --- |
| `kix deploy <CLUSTER> --operator` | Builds, shows the plan, asks for confirmation, and writes the Activation record with the build's store path, the deploy receipt, and a request token (`spec.request`). Waits for the operator to finish that request. If the build is already deployed, the operator redeploys it and keeps the record current. |
| `kix rollback <CLUSTER> --operator` | Selects a `Superseded` Activation record, shows the plan, asks for confirmation, and writes a request token (`spec.request`) to that record. Once the operator finishes applying that build, it restores the record as the current deployment and marks the previous record `Superseded`, matching `kix rollback`. Waits for the operator to finish that request. |
| `kix gc <CLUSTER> --operator` | Deletes the Activation records that retention retires. The operator's finalizer deletes each record's resources; the CLI waits up to 300 seconds per record. |

[`kix status <CLUSTER>`](/docs/reference/cli/status/) takes no `--operator`
flag. It reads the cluster's current Activation record the same way whoever
applied it, and does not need the operator to be running.

`kix deploy --operator` fails with `[K7218]` if you pass flags that operator
mode does not support: `--timeout`, `--on-error continue`, `--reconcile`,
`--skip-orphan-check`, `--force-conflicts`, `--log-format` (other than
`pretty`), or `--group-by` (other than `package`). The operator uses fixed
deploy settings (see below), and `kix deploy --operator` prints a fixed
progress view while waiting. `--prune` is accepted because the operator always
deletes orphaned resources. `--yes`,
`--offline`, and `--accept-migrations` still apply to the local plan. `--dry-run` runs [`kix plan`](/docs/reference/cli/plan/) locally and
does not contact the operator.

## How the operator runs a deploy

The operator fails any resource that goes 300 seconds without progress toward
becoming ready, and stops the deploy at the first failure. It deletes orphaned
resources, never takes over fields owned by another field manager, and leaves
unchanged resources untouched. When deploying a Kix cluster last deployed by an
earlier version of Kix, the operator migrates its deployment records and object
metadata to revisions just like `kix deploy` (see
[The first deploy after upgrading](/docs/explanation/server-side-apply-and-drift/#the-first-deploy-after-upgrading)).

### Retries after a failure

When a deploy fails, the operator keeps the Activation record in `Deploying`,
posts a `DeployRetrying` Warning Event, and retries 30 seconds later. If the
operator pod cannot read `spec.source.path` (for example, because the build is
not in the store the operator reads) or cannot list live cluster resources,
that failure counts toward the same retry limit. When a new record fails there
before the deploy starts, it stays `Queued` while the operator retries. By
default, it retries up to 10 times (11 attempts in total). If every retry
fails, the operator marks the record `Failed`, writes the attempt count and
last error to `status.failure.reason`, and posts a `DeployFailed` Warning
Event.

Set `KIX_DEPLOY_RETRIES` on the operator to change the retry limit, or set it
to `0` to mark the record `Failed` on the first failure (matching `kix deploy`
without `--operator`). The operator stores the count in
`status.failedAttempts` on the Activation record, so restarting the operator
does not reset it.

With the default of 10 retries, a deploy that fails right away (such as a SOPS
file the operator cannot decrypt) reaches `Failed` in about 5 minutes, within
the 600 seconds that `kix deploy --operator` and `kix rollback --operator`
wait. A deploy that hits the 300-second readiness timeout takes over 5 minutes
per attempt, so `kix deploy --operator` times out locally while the operator
keeps retrying in the cluster.

While waiting, `kix deploy --operator` and `kix rollback --operator` print each
failed attempt:

```text
  ✗ Attempt 1 failed. The Kix operator will retry in 30 seconds.
    Secret/db@shop: could not prepare secret values for deployment: cannot decrypt SOPS file db.sops.yaml: `sops` could not get a decryption key
```

If the operator stops retrying before that 600-second wait ends, the command
exits with the failure reason:

```text
Error:   × Operator reconciliation failed for 'shop-mxfi8rx0piys': the Kix operator stopped after 11 failed attempts (KIX_DEPLOY_RETRIES is 10 on the operator) and marked this Activation Failed. Fix the cause below, then run `kix deploy --operator` or `kix rollback --operator` again.
  │
  │   Last failure:
  │     Secret/db@shop: could not prepare secret values for deployment: cannot decrypt SOPS file db.sops.yaml: `sops` could not get a decryption key
  │       ...
```

### What happens to the current deployment

While a new deploy or rollback is `Queued` or `Deploying` (including between
retries), the cluster's existing `Active` or `Degraded` Activation remains
current, and the operator pauses drift repair for it. When the new deploy
finishes, the operator marks the previous Activation `Superseded` and writes
its name to `status.previousActivation` on the new Activation, matching
`kix deploy`.

If the new deploy reaches `Failed`, that Activation remains current,
[`kix status`](/docs/reference/cli/status/) continues to show it, and
`status.failure.reason` names it when the operator stops after exhausting
`KIX_DEPLOY_RETRIES` (records refused before applying anything omit it). Within a few seconds, the operator resumes drift repair
and restores the cluster to that build by deleting resources the failed deploy
added and re-applying resources it changed. To inspect a failing deploy's
resources before the operator reverts them, check them while the operator is
still retrying or increase `KIX_DEPLOY_RETRIES`.

To deploy after a record reaches `Failed`, fix the cause and run
`kix deploy --operator` or `kix rollback --operator` again. Each new deploy or
rollback request resets `status.failedAttempts`.

Redeploying a build that is already `Active` or `Degraded` runs once and does
not count toward `KIX_DEPLOY_RETRIES`. If that run fails, the Activation keeps
its phase, the operator continues repairing drift on later reconciles, and
`kix deploy --operator` exits with the failure recorded in
`status.failedRequest`:

```text
Error:   × Operator reconciliation failed for 'shop-mxfi8rx0piys': the Kix operator could not redeploy the current build. This Activation stays Active, and the operator continues repairing drift for this build. It does not retry a failed redeploy. Fix the cause below, then run `kix deploy --operator` again.
  │
  │   Cause:
  │     Secret/db@shop: could not prepare secret values for deployment: cannot decrypt SOPS file db.sops.yaml: `sops` could not get a decryption key
```

Older versions of the Kix operator do not write `status.failedRequest`. Until
you upgrade the operator, `kix deploy --operator` waits the full 600 seconds
and times out when a redeploy fails.

Submitting a newer deploy or rollback request does not cancel a running deploy.
The operator runs one deploy per cluster at a time, so the new request waits
until the running deploy finishes.

When the operator receives `SIGTERM` (such as when Kubernetes stops its pod) or
`Ctrl-C`, it cancels any running deploy, starts no new ones, and exits. An
interrupted deploy leaves its Activation record `Deploying`. When the operator
starts again, it resumes every `Deploying` record started in operator mode.

## Secrets from SOPS files

The Kix operator decrypts each SOPS file inside the cluster right before it
applies the Secret. It runs the `sops` in the Kix runtime, which reads keys and
credentials from the operator container's environment. Keys on the machine that
runs `kix deploy --operator` never reach the cluster, so the operator pod must
have a key or credentials that can decrypt every SOPS file in the build.

Configure the key on the `kix-operator` container in your operator Deployment:

- **Age identity:** Create a Kubernetes Secret in the operator's namespace from
  your identity file, mount it into the container, and point `SOPS_AGE_KEY_FILE`
  at it:

  <Command
    commands={[
      "kubectl create secret generic kix-operator-sops-age --namespace <operator-namespace> --from-file=age-key.txt",
    ]}
  />

  ```yaml
  # Part of the operator Deployment's pod template
  spec:
    containers:
      - name: kix-operator
        env:
          - name: SOPS_AGE_KEY_FILE
            value: /var/run/kix-sops/age-key.txt
        volumeMounts:
          - name: sops-age
            mountPath: /var/run/kix-sops
            readOnly: true
    volumes:
      - name: sops-age
        secret:
          secretName: kix-operator-sops-age
  ```

- **Cloud KMS or Vault:** Grant the operator pod access to decrypt with that
  key, such as through a cloud workload identity or the environment variables
  `sops` uses for that service.

If the operator cannot decrypt a SOPS file, the deploy stops at that Secret and
leaves the Activation record `Deploying`. The operator posts a `NodeFailed`
Warning Event naming the SOPS file (inspect it with
`kubectl describe activation <name>`) and retries every 30 seconds (up to 10
times by default; see [Retries after a failure](#retries-after-a-failure)). If
you give the operator pod access to the key before those retries run out, the
next retry decrypts the file and finishes the deploy. Once the operator marks
the record `Failed`, give the pod access to the key and run
`kix deploy --operator` or `kix rollback --operator` again.

## When an Activation record is deleted

When an `Active`, `Deploying`, or `Degraded` Activation record is deleted, the
operator deletes that build's resources before removing its `kix.run/operator-gc`
finalizer (keeping Namespaces, CustomResourceDefinitions, and resources still
deployed by another Kix cluster). It deletes dependents before their
dependencies, up to 64 independent resources in parallel, and waits up to 300
seconds (5 minutes) for each resource to disappear from the cluster.

Cleanup is unfinished if any resource belonging to this Kix cluster:

- fails to delete, or changed while being deleted,
- is still on the cluster after the 300-second wait,
- is held back because a resource still on the cluster depends on it, or
- is part of, or depends on, a dependency cycle.

When cleanup is unfinished, the operator keeps `kix.run/operator-gc` on the
Activation record, posts a `DeletionUnfinished` Warning Event naming up to five
remaining resources, and retries 30 seconds after the attempt finishes. Repeated
retries update the count on the same Event; run `kubectl describe activation <name>`
to read it. Because a stuck resource waits out the 300-second limit before the
30-second pause, each retry cycle takes about 5.5 minutes; a delete that fails
immediately, such as a permission error, retries every 30 seconds. If the
operator stops during cleanup, it cancels the active wait and tries again the
next time it starts.

To let cleanup finish, inspect `kubectl describe activation <name>` and the
operator logs, then clear the blocking resources: fix any permission error,
start the controller responsible for a stuck finalizer, follow the log
instructions for built-in Kubernetes protection finalizers, or run the
`kubectl patch` command printed in the operator log to remove a controller
finalizer and skip its external cleanup.

To abandon cleanup instead and let Kubernetes delete the Activation record,
remove `kix.run/operator-gc` from the record:

```sh
kubectl patch activation <name> --type=json -p '[{"op":"test","path":"/metadata/finalizers/0","value":"kix.run/operator-gc"},{"op":"remove","path":"/metadata/finalizers/0"}]'
```

The `test` operation checks that `kix.run/operator-gc` is at index `0`, so the
patch fails safely if another finalizer comes first. If it fails, run
`kubectl get activation <name> -o jsonpath='{.metadata.finalizers}'` and replace
`0` in both paths with the 0-based index of `kix.run/operator-gc`.

Kubernetes deletes the Activation record once no finalizers remain on it. If a
cleanup attempt is already running, it finishes first and may delete a few more
resources. Any resources the operator did not delete stay on the cluster without
an Activation record naming them; run `kix gc <cluster> --full-scan` to find
them.

## The deploy lock

The operator takes each Kix cluster's
[deploy lock](/docs/reference/cli/deploy/#the-deploy-lock) before making
changes: deploying a queued or resumed record, redeploying the active record,
repairing drift, or deleting resources when an `Activation` record is deleted.
It runs at most one operation per Kix cluster at a time. If another run holds
the lock (for example, a direct `kix deploy`), the operator logs the current
holder and retries 5 seconds later.

Drift repair holds the lock with purpose `repair` and yields to other
commands: when another run needs the lock, it writes its ID to
`status.lock.waiting`, and the operator stops repairing before its next write
(or at its next lock renewal) and releases the lock. Drift repair does not
increment the lock generation or update the cluster's last writer.

Because the operator's lock holder ID (`kix-operator/<namespace>`) stays
constant across pod restarts, a restarted pod immediately reclaims any lock
left by its previous pod and resumes deploying the same record. `--operator`
CLI commands only write requests to `Activation` records and do not take the
lock themselves.

## Waiting for the operator

The CLI polls the Activation record every 2 seconds and prints progress as
the operator reports it. It ignores the record's phase until
`status.startedRequest` matches `spec.request`, and treats `Active` or
`Degraded` as complete only after `status.finishedRequest` matches
`spec.request` too. That prevents an earlier phase (such as `Active` when
redeploying the current build) from ending the wait early.

| Record phase | CLI result |
| --- | --- |
| `Active` | Success (exit code `0`) |
| `Degraded` | Error (exit code `1`), after printing the failed resources or `status.failure.reason` |
| `Failed` | Error (exit code `1`), with the record's `status.failure.reason` (or `unknown error` if unset) |
| `Active` or `Degraded` when `status.failedRequest.request` matches `spec.request` | Error (exit code `1`), with `status.failedRequest.reason` |
| `Deploying` or `Queued` after a failed attempt | Prints `Attempt <n> failed. The Kix operator will retry in 30 seconds.` and the first line of the failure reason, then keeps waiting |
| `Superseded` | Error: a newer activation took over |
| No terminal phase after 600 seconds | Error: timed out |

A timeout ends the CLI only. The operator keeps working on the record.

## Requirements

- The operator is running. On startup, it installs any missing Kix
  CustomResourceDefinitions (`activations.kix.run`, `packageinstances.kix.run`,
  `activationheads.kix.run`, and `packageinstancerevisions.kix.run`) and updates
  any CRD definition older than its own. Your Kubernetes account must be able
  to list `Activation` records, and `--operator` commands check this before
  making changes.
- The operator watches the `kix.run` API group.
- The operator runs a matching or newer version of Kix, its Kubernetes account
  can patch CustomResourceDefinition `activations.kix.run`, and your account
  can read that CRD. On startup, the operator writes `requests,head-lock,revisions`
  to the `kix.run/operator-features` annotation on `activations.kix.run`.
  `kix deploy --operator` and `kix rollback --operator` check that annotation
  before changing anything and stop with `[K9557]` if any of the three
  features is missing.
- Upgrade the operator before running an upgraded Kix against its
  clusters. An older operator deploys without taking the deploy lock and writes
  the retired `kix.run/activations` and `kix.run/applied-hash` annotations back
  onto every resource it applies. Every command that modifies a Kix cluster
  (`kix deploy`, `kix rollback`, `kix gc`) stops with `[K9557]` before planning
  if a current, queued, or deploying record for that cluster was submitted to
  the operator and `kix.run/operator-features` lacks `revisions` (including
  operators from Kix 0.9 or earlier, which write no annotation). Other Kix
  clusters on the same Kubernetes cluster are unaffected.
- Because Kix cannot distinguish an older running operator from one that was
  uninstalled, uninstalling an older operator leaves its Kix clusters blocked
  with `[K9557]`. Run `kix deploy <cluster> --operator-removed` once per
  cluster to reclaim it before planning, after which commands need no flag (see
  [Take a cluster back from a removed operator](/docs/reference/cli/deploy/#take-a-cluster-back-from-a-removed-operator)).
  Never pass `--operator-removed` while the operator is still running. Kix
  cannot check this for you, so after taking a cluster back it prints a
  `kubectl` command that looks for operator pods.
- The operator's Kubernetes account must be able to `get`, `create`, `update`,
  and `patch` CustomResourceDefinitions (to install and update Kix's CRDs and
  set `kix.run/operator-features`); `get`, `list`, `create`, and `update`
  `activationheads.kix.run` (for deploy locks); `get`, `list`, `create`, and
  `delete` `packageinstancerevisions.kix.run`; and `patch`
  `packageinstancerevisions/status` (to record applied hashes). For example:

  ```yaml
  - apiGroups: ["apiextensions.k8s.io"]
    resources: ["customresourcedefinitions"]
    verbs: ["get", "create", "update", "patch"]
  - apiGroups: ["kix.run"]
    resources: ["activationheads"]
    verbs: ["get", "list", "create", "update"]
  - apiGroups: ["kix.run"]
    resources: ["packageinstancerevisions"]
    verbs: ["get", "list", "create", "delete"]
  - apiGroups: ["kix.run"]
    resources: ["packageinstancerevisions/status"]
    verbs: ["patch"]
  ```
- The operator can read the store path the CLI wrote. It loads manifests from
  `spec.source.path`, so the build must be present in the store the operator
  reads, not only on the machine that ran the CLI.
- For builds with SOPS-backed Secrets, the operator pod has keys or credentials
  that can decrypt every SOPS file (see [Secrets from SOPS files](#secrets-from-sops-files)).

## Exit status

Operator-mode commands exit `1` on any of the errors above, when confirmation
is needed on a non-interactive terminal, or when a record could not be
deleted. `deploy --operator` and `rollback --operator` also exit `1` when the
operator finishes the Activation as `Degraded`.

:::tip[Use it in a task]
See [Roll back an activation](/docs/how-to/operate-a-cluster/roll-back-an-activation/)
and [Garbage-collect stale resources](/docs/how-to/operate-a-cluster/garbage-collect-stale-resources/)
for the operator variants of those tasks.
:::

:::note[Explanation]
See [The DAG-driven deployment scheduler](/docs/explanation/the-dependency-graph/#dag-driven-deployment-scheduler)
for the record phases.
:::