# Deploy Velero

Use the `velero` package to deploy the Velero server and node agent, connect
them to S3-compatible object storage, and schedule recurring backups.

The package deploys Velero 1.18.4 with the AWS object-store plugin 1.14.4 and
installs Velero's custom resource definitions itself. It assumes you have an
existing bucket and credentials that can read, write, list, and delete objects
in it.

A cluster runs one Velero instance. The CRDs, the server's cluster-wide
permissions, and the node agent are cluster singletons, so a second instance
fails evaluation.

## Create the Secrets

Velero needs two Secrets in its namespace: the object-store credentials and
the key that encrypts the file-system backup repositories.

Create a local file named `credentials-velero` in the format expected by the
AWS plugin:

```ini title="credentials-velero"
[default]
aws_access_key_id=<access-key-id>
aws_secret_access_key=<secret-access-key>
```

Create the namespace and both Secrets before deploying Velero:

<Command
  commands={[
    "kubectl create namespace velero-system",
    "kubectl create secret generic velero-credentials --namespace velero-system --from-file=cloud=./credentials-velero",
    "kubectl create secret generic velero-repo-credentials --namespace velero-system --from-literal=repository-password=\"$(openssl rand -base64 32)\"",
  ]}
/>

Keep the credentials file and the repository key out of version control, and
store the repository key somewhere you can recover it: a restore of a
file-system backup needs the key the backup was written with. If your platform
already creates Kubernetes Secrets, use it to create the same Secrets and
keys.

Velero reads the repository key only from a Secret named
`velero-repo-credentials` with the key `repository-password`. When that Secret
is missing, Velero creates one with a key compiled into every Velero binary,
so the package refuses to build without it while the node agent is on.

## Configure Velero

Add the two Secret references and the Velero instance to the cluster:

<Snippet {...veleroInstance} />

The `cloudCredentials` and `repositoryPassword` aliases are how the package
finds the two Secrets. Kix checks at evaluation that each reference declares
the key the package reads.

Replace `example-cluster-backups` and the region with values for your bucket.
The location's `config` is the plugin's settings map. For an S3-compatible
service with a custom endpoint, set `s3Url` and `s3ForcePathStyle`. For one
that rejects the AWS SDK's checksums, set `checksumAlgorithm = ""`. To trust a
private certificate authority, set `backupStorageLocation.objectStorage.caCertRef`
to a Secret key in the same namespace.

When the object store runs in the same cluster, wire it as the
`objectStorage` dependency. The package then sets `s3Url` to that Service and
`s3ForcePathStyle` to `"true"`, and the network policy for Velero's pods
follows the dependency. With the dependency wired, an `s3Url` in `config`
fails evaluation, because Velero would dial that address and no policy would
open it.

To reach the store through a proxy, set `server.env` and `nodeAgent.env`
(for example `HTTPS_PROXY` and `NO_PROXY`). The pods Velero launches copy
these variables.

The `daily` schedule backs up the `applications` namespace at 02:00 UTC,
retains each backup for 30 days, and uses the node agent for volume data.
Change the namespace selection, schedule, and retention period to match your
recovery policy. A schedule accepts five cron fields, a descriptor such as
`@every 6h`, and an optional `CRON_TZ=<zone>` or `TZ=<zone>` prefix; anything
else fails evaluation.

### Volume policies

`volumePolicies` decides per volume whether a backup skips it, snapshots it,
or copies its files through the node agent. The package writes the list to a
ConfigMap that Velero applies to every backup, scheduled or not:

```nix
volumePolicies = [
  {
    conditions.storageClass = [ "local-path" ];
    action.type = "fs-backup";
  }
];
```

The condition names are Velero's (`capacity`, `storageClass`, `nfs`, `csi`,
`volumeTypes`, `pvcLabels`, `pvcPhase`, `pvcVolumeMode`, `pvcAccessModes`).
Velero refuses a policy file with an unknown key, which would fail every
backup, so Kix rejects one at evaluation.

To choose volumes per workload instead, annotate the pod with
`backup.velero.io/backup-volumes` (or `backup.velero.io/backup-volumes-excludes`).
To leave a resource out of every backup, label it
`velero.io/exclude-from-backup=true`.

### CSI snapshots

Add `features = [ "EnableCSI" ]` to snapshot CSI volumes. Velero picks the
VolumeSnapshotClass for a driver by the label
`velero.io/csi-volumesnapshot-class: "true"`, so label the class you want it
to use.

## Check the generated configuration

Evaluate the cluster:

<Command {...check} />

Inspect the backup location and schedule that Kix will apply:

<Command expandable {...backupConfiguration} />

The backup location names the `velero-credentials` Secret. Its contents are
not part of the rendered manifests.

## Deploy and verify

Deploy Velero, then check the server, backup location, and schedule:

<Command
  commands={[
    "kix deploy how-to-package-velero",
    "velero backup-location get --namespace velero-system",
    "velero schedule get --namespace velero-system",
  ]}
  cwd="kix-examples/"
/>

`kix deploy` waits for the backup location to report `Available`, so a bucket
Velero cannot reach fails the deploy. Confirm the complete path by starting a
backup and waiting for it to finish:

<Command
  commands={[
    "velero backup create initial-applications-backup --include-namespaces applications --wait --namespace velero-system",
    "velero backup describe initial-applications-backup --details --namespace velero-system",
  ]}
/>

If the location is unavailable, inspect it and the server logs:

<Command
  commands={[
    "kubectl describe backupstoragelocation default --namespace velero-system",
    "kubectl logs deployment/velero --namespace velero-system --since=10m",
  ]}
/>

## Declare backups and restores

Velero reads its custom resources only in its own namespace. The package's
builders create a Backup or a Schedule there from any instance and wait for
the location to be `Available`:

```nix
backup = velero.out.mkBackup scope {
  name = "before-migration";
  spec.includedNamespaces = [ scope.namespaceName ];
  requires = [ self.deployment ];
};
```

`velero.out.mkSchedule` takes the same arguments. List at least one resource
of the calling instance in `requires`, such as the workload it backs up. The
location the builder waits for belongs to the velero instance, and
`kix check` refuses a resource that references nothing in its own
instance. For another kind, such as
a Restore or a second backup location, build the resource in Velero's
namespace with `(scope.forService velero).mkCR velero.out.crds.Restore { ... }`.
A resource built in any other namespace is never processed, and the deploy
waits for it until it times out.

`kix deploy` waits for each declared Backup and Restore to finish. One that
ends `Failed` or `PartiallyFailed` never reports `Completed`, so the deploy
waits until it times out; run `velero backup describe` or
`velero restore describe` on it.

A Backup runs once. Velero deletes the Backup when its `ttl` expires (30 days
unless set), and the next `kix deploy` creates it again, which runs a new
backup under the same name. Use a schedule for recurring backups and a
declared Backup for a one-off backup you remove from the cluster definition
afterwards.

## What the package sets up

- **Permissions.** The server reads every kind for a backup and recreates any
  kind on a restore, including custom resources installed later, so its
  ServiceAccount is bound to `cluster-admin`. The package declares the
  [`cluster-admin`](/docs/reference/package-anatomy/#meta) grant, which the scorecard
  lists.
- **Pod security.** The node agent reads pod volumes from the host as root, so
  the namespace gets the `privileged` Pod Security level.
- **Network policy.** With network policy on, the package writes a policy for
  the pods Velero launches itself (file-system backups and restores, the CSI
  data mover, and repository maintenance Jobs) that allows DNS and the API
  server. It labels those pods through the node agent and maintenance
  settings, so `podLabels` there may not override the labels the policy
  selects on. For a store outside the cluster, a second policy lets every
  Velero pod connect to addresses outside the cluster on the port of `s3Url`
  (443 when it is unset), and on 443 when a snapshot location is set. A
  backup location you add on another port needs its own policy.
- **Metrics.** With a `prometheus` dependency, the package adds metrics
  Services for the server and the node agent, a ServiceMonitor for each, and
  three alerts: a failed or partially failed backup, a schedule with no
  successful backup within its threshold, and a server Prometheus cannot
  scrape. The missing-backup threshold comes from
  `metrics.maxBackupAge.<schedule>` (default `{ }`); unlisted schedules in
  `schedules` derive their threshold from `kix.schedules.staleAfter` (two
  periods plus two hours, such as `50h` for a daily schedule and `338h` for a
  weekly schedule, failing evaluation if the cron period cannot be read), and
  schedules created with `out.mkSchedule` use `metrics.otherSchedulesMaxAge`
  (default `50h`).

## Use a cloud identity instead of keys

On EKS, GKE, or AKS, Velero can authenticate to cloud storage with its
Kubernetes ServiceAccount instead of a stored key. Pass a cloud identity to
`deps.cloudCredentials` in place of the `velero-credentials` Secret reference.
You still need the `velero-repo-credentials` Secret for the backup repository
encryption key.

Kix binds the identity to the `<instance>-server` ServiceAccount, which is
shared by the server, the node agent, and the pods Velero launches for
file-system backups, the CSI data mover, and repository maintenance. Kix omits
the credentials file mount and leaves `credential` unset on the backup and
snapshot locations, so Velero's plugins authenticate with the pod's cloud
identity through their cloud SDKs.

Match the identity to `backupStorageLocation.provider`: `kix.cloudIdentity.aws`
for `velero.io/aws`, `kix.cloudIdentity.gcp` for `velero.io/gcp`, and
`kix.cloudIdentity.azure` for `velero.io/azure`. If `volumeSnapshotLocation` is
set and its provider is one of those three Velero cloud plugins, it must use the
same cloud; Kix does not check snapshot providers from other plugins. Evaluation
fails if the clouds do not match, or if you combine a cloud identity with
`deps.objectStorage` (in-cluster object stores require Secret credentials).

For AWS S3 on EKS, pass `kix.cloudIdentity.aws`:

<Snippet {...veleroEksIdentity} />

For Google Cloud Storage on GKE, add the GCP plugin in `extraPlugins`, pass
`kix.cloudIdentity.gcp`, and set `backupStorageLocation.config.serviceAccount`
to a Google service account email. Without a JSON key file, the GCP plugin uses
`config.serviceAccount` to sign URLs for `velero backup download` and
`velero backup logs`, and fails to start if it is unset. If you set
`serviceAccount` in `kix.cloudIdentity.gcp { serviceAccount = "..."; }`, pass
the same email here. If you grant IAM roles directly to the Kubernetes
ServiceAccount (`kix.cloudIdentity.gcp { }`), pass a Google service account on
which the Kubernetes ServiceAccount has `roles/iam.serviceAccountTokenCreator`:

<Snippet {...veleroGkeIdentity} />

For Azure Blob Storage on AKS, add the Azure plugin in `extraPlugins` and pass
`kix.cloudIdentity.azure`. Without a credentials file, the Azure plugin reads
storage account details from `backupStorageLocation.config`. Set
`storageAccount`, plus either `useAAD = "true"` (grant the identity the
`Storage Blob Data Contributor` role on the storage account) or both
`resourceGroup` and `subscriptionId` (grant the identity permission to list the
storage account keys):

<Snippet {...veleroAksIdentity} />

On AKS, Kix adds `azure.workload.identity/use: "true"` to the server and node
agent pods, and includes it in `nodeAgent.settings.podLabels` and
`repositoryMaintenance.settings.podLabels` so the pods Velero launches receive
the identity too. Velero copies that label automatically only when `podLabels`
is empty, and this package always sets network-policy labels there.

Velero's Azure volume snapshot plugin reads the disk subscription and resource
group only from a credentials file, so Kix rejects an Azure
`volumeSnapshotLocation` when `deps.cloudCredentials` is a cloud identity. Back
up AKS volumes with [CSI snapshots](#csi-snapshots) (`features = [ "EnableCSI" ]`)
or file-system backups instead.

Kix does not create cloud IAM resources. In your cloud account, grant bucket
access and allow the ServiceAccount `<namespace>/<instance>-server`
(`system:serviceaccount:<namespace>:<instance>-server`) to use the identity
through an AWS IAM role trust policy (or EKS Pod Identity association), a Google
Cloud IAM binding, or an Azure federated credential. See
[Cloud identities](/docs/reference/instances-and-composition/#cloud-identities)
for per-flavor details and self-managed clusters.

When you change the cloud identity, Kix restarts the server and node agent pods
on the next deploy. Any backup, restore, or maintenance pod that Velero started
before the deploy finishes with the previous identity.

## Upgrades

Velero supports upgrading to 1.18 only from 1.17 and supports no downgrade.
The vendored CRDs match Velero 1.18, so the package refuses an `image.tag` from
another minor release.