Skip to content

14.14 — Backup and restore with Velero

EKS runs the Kubernetes control plane for you. AWS Backup covers EBS volumes and EKS persistent storage. RDS has point-in-time recovery, and S3 has versioning. Those services each cover one layer. None of them is a restore path for a mangled Helm release, a Kyverno policy that someone kubectl deleted by accident, or a Namespace someone wiped while testing the GitOps reconciler, unless you have checked its Kubernetes scope yourself. Velero is the Kubernetes-shaped backup tool: it snapshots API objects + the PVs those objects reference to S3, on schedule, and can restore a single namespace, a label-selected subset, or the whole cluster — to the same cluster after corruption, or to a new cluster as a migration. Phase 14-R's velero.tf ships the install + the IRSA scoping + the daily 30-day schedule; this chapter walks the architecture, the schedule discipline, the restore drill, and the honest list of what Velero can't back up (cloud-side state — RDS data, S3 buckets, IAM — covered by ch.14.17).

Estimated time: ~30 min read · ~90 min hands-on Prerequisites: Part 08 ch.02 — backup discipline framing · Part 14 ch.04 — EBS volumes whose snapshots Velero coordinates · Part 13 ch.01 — bookstore namespaces that need cluster-shaped backup

You'll know after this: • understand why EBS snapshots + RDS PITR together still leave Kubernetes-shaped state unbacked up · • configure Velero schedules that snapshot API objects + the PVs they reference to S3 · • restore a single namespace, a label-selected subset, or a whole cluster from a Velero backup · • rehearse restore-to-new-cluster as a cluster-migration tool · • know the honest list of what Velero CAN'T back up (RDS data, S3 buckets, IAM) and how Part 14.17 covers it

Why this exists

The bookstore-platform tree at ../examples/bookstore-platform/terraform/ runs CNPG, Strimzi, Argo CD, Kyverno, Falco, OpenCost, the bookstore application namespaces, and a fleet of CRDs that drive all of the above. Phase 14-R shipped Velero in velero.tf gated by var.enable_velero = false — off by default because backup costs (S3 storage + EBS snapshot fees) compound monthly and a production backup story is more than the install.

Three things every Kubernetes team eventually loses without backups:

  • A namespace. A kubectl delete ns bookstore deletes every resource in it: Deployments, Services, ConfigMaps, Secrets, the PVCs too. Argo CD won't replant resources that aren't in Git (auto-prune); the human-error case is irreversible without a backup.
  • A PV's data. A helm uninstall on a chart that owns CNPG with reclaimPolicy: Delete destroys the EBS volume. The data is gone. EBS snapshots taken by AWS Backup outside Kubernetes catch this if the schedule is right; Velero's snapshot integration captures it from inside Kubernetes.
  • A CRD instance. A kubectl delete kyvernopolicy require-labels deletes the policy. The cluster is now permitting unlabeled workloads. AWS-side EBS and RDS backups don't hold CRD instances. Velero captures them. EKS runs etcd for you, so there is no etcdctl snapshot to take.

Part 08 ch.02 introduced Velero in the abstract: the three state layers (etcd / app desired state / PV data), the three corresponding backups, the restore-test discipline. That chapter ran Velero against a kind cluster with MinIO as the object store. This chapter is the EKS-specific overlay: IRSA wires Velero to S3 + EBS without a static credential, the AWS plugin handles the EBS volume side, and the schedule discipline sits alongside the AWS-side billing reality.

In production: A backup that has never been restore-tested is a hypothesis, not a backup. Phase 14-R ships the install; the production discipline is the quarterly fire-drill where you destroy a namespace + restore it from Velero + verify the workload comes back. Teams that skip this learn at 3am that the backup they relied on was missing a CRD, or had a Secrets-encryption mismatch, or referenced an EBS snapshot in a region that no longer matched the cluster.

Mental model

Three Velero concepts compose the backup story: the BackupStorageLocation (where to write — an S3 bucket via IRSA), the VolumeSnapshotLocation (how to snapshot PVs — via CSI or AWS EBS snapshots), and the Schedule (when to run + what to include). Backups are additive snapshots: an API-object dump in JSON + EBS-volume snapshots referenced by snapshot ID; restores reverse the operation.

The four concepts:

  • BackupStorageLocation (BSL) — where backup metadata + objects live. A namespaced CR pointing at an object-storage bucket. The example configures one BSL named default against the <cluster>-velero-backups-<account-suffix> S3 bucket (created by Terraform, encrypted with a customer-managed KMS key, versioned, lifecycle-managed). Velero writes one prefix per backup: backups/<NAME>/. Inside it: velero-backup.json (the backup manifest), <NAME>.tar.gz (every object the backup includes, Secrets among them, as JSON), <NAME>-resource-list.json.gz (the resources selected), <NAME>-volumesnapshots.json.gz (the EBS snapshot IDs), and <NAME>-logs.gz. File-system backup data goes under kopia/ when enabled.
  • VolumeSnapshotLocation (VSL) — how PV snapshots are taken. Also a namespaced CR. The example configures the AWS provider VSL pointing at the cluster's region. For each EBS-backed PV in a backup, the AWS plugin calls ec2:CreateSnapshot with Velero's IRSA role and records the snapshot ID in the backup's volumesnapshots file. Restore calls ec2:CreateVolume from that ID. This is the native path, not the CSI path, which needs the EnableCSI feature flag and a VolumeSnapshotClass labelled velero.io/csi-volumesnapshot-class. The example sets neither.
  • Schedule — when to back up. A CR with a cron-string + a BackupSpec template. The example's default Schedule is nightly-cluster-backup, runs at 02:00 UTC daily, retains 30 days, includes every namespace except the EKS-managed ones (kube-system, kube-public, kube-node-lease), snapshot volumes with the AWS plugin. The Schedule controller materialises a Backup CR each time the cron fires.
  • Restore — apply a backup back to a cluster. A CR identifying a backup name and (optionally) selectors (namespaces, label selector, resource types). The Restore controller reads the backup's S3 prefix, recreates the API objects (with optional remapping like namespace-mapping), recreates PVCs, and the AWS plugin creates EBS volumes from the recorded snapshot IDs.

The native snapshot path vs the file-level backup path. Velero on EKS has two ways to back up PV data:

  1. Native EBS snapshot (the example's default). The AWS plugin snapshots EBS volumes itself, through the VSL. Snapshots are incremental (only changed blocks are billed after the first) and region-scoped. The plugin handles EBS volumes only. For a PV on another CSI driver, such as EFS, it logs Unable to handle CSI driver and takes no snapshot.

  2. File-system backup with Kopia (opt-in via defaultVolumesToFsBackup: true or the pod annotation backup.velero.io/backup-volumes). A Velero node-agent DaemonSet mounts each PV's files and copies them into a deduplicated repository under kopia/ in the same S3 bucket. This works for any PV, EFS included. The node-agent runs as root with host paths, which restricted forbids, so the example does not deploy it. Turning it on needs a namespace exception with its reason.

Trade-offs:

Path Speed Cost Coverage When to use
Native EBS snapshot Done by EBS, no file scan EBS snapshot pricing (see the EBS pricing page) EBS PVs only Default in the example.
Kopia file backup Slower: file scan and upload S3 storage for the repository Any mounted PV EFS-backed PVs, or one deduplicated repository. Needs a node-agent that runs as root.
CSI snapshot (not configured) Block-store snapshot EBS snapshot pricing Snapshot-capable CSI drivers Needs EnableCSI and a labelled VolumeSnapshotClass.

The example's default is the native EBS snapshot (defaultVolumesToFsBackup: false in the Schedule). The Bookstore Platform's stateful workloads (CNPG, Loki, Tempo, Prometheus) run on EBS-backed gp3 PVs (gp3-storageclass.tf), which the native path snapshots.

Backup retention math (the 23-backup pattern). One common retention scheme:

- 7 daily backups  (one per day for the last week)
- 4 weekly backups (one per week for the last month)
- 12 monthly backups (one per month for the last year)
─────────────────────
= 23 backup objects retained at any time

The point: 23 backups, not 365. A daily-only-with-365-day-TTL policy holds 365 backups, for marginal extra recovery granularity. The 23-backup scheme is a cost-aware choice. The example assumes a 200 GB base, 5 GB changed per day, and the EBS list price of $0.05 per GB-month (checked 2026-10-31 on the EBS pricing page, so check your region). The figures are illustrative, not measured:

First daily snapshot:        200 GB unique blocks * $0.05/GB-mo  = $10.00/mo
6 incremental dailies:       ~5 GB delta each * 6 * $0.05/GB-mo  =  $1.50/mo
4 weekly snapshots:          ~20 GB delta each * 4 * $0.05/GB-mo =  $4.00/mo
12 monthly snapshots:        ~40 GB delta each * 12 * $0.05/GB-mo = $24.00/mo
─────────────────────
                                                       Total      ~$39.50/mo

Under the same assumptions, a daily-only scheme with a 365-day TTL keeps 364 deltas: 200 + 364 × 5 = 2,020 GB, about $101/mo, roughly 2.6 times the 23-backup scheme. velero.tf keeps one 30-day Schedule. Section 7 shows the three-Schedule form.

The hooks pattern (application-consistent backups). A naive PV snapshot is crash-consistent: the snapshot captures the volume's state at the snapshot moment, but in-flight database writes may or may not be in it. For Postgres, that's usually fine (Postgres recovers via WAL on restart); for some databases, snapshotting mid-transaction is genuinely lossy. Velero supports hooks — pre- and post-backup commands run inside the target Pod via kubectl exec. The canonical pattern:

metadata:
  annotations:
    pre.hook.backup.velero.io/command: '["/bin/sh","-c","psql -U postgres -c CHECKPOINT"]'
    post.hook.backup.velero.io/command: '["/bin/sh","-c","echo done"]'

For CNPG specifically, the better answer is CNPG's own Backup CRD (which uses pg_basebackup + WAL streaming for proper PITR); Velero handles the surrounding Kubernetes API objects + the EBS snapshot for crash-consistent insurance.

What Velero CAN'T back up — the honest list. Velero backs up Kubernetes API objects + the PVs Kubernetes manages. It does NOT back up:

  • RDS database content. RDS lives outside the cluster; Velero doesn't have RDS API access (and shouldn't). RDS Automated Backups
  • Manual Snapshots are the answer; AWS Backup orchestrates them centrally.
  • S3 bucket contents. Backups of S3 objects = S3 versioning + Cross-Region Replication (CRR). Same as RDS — outside the cluster.
  • IAM roles + policies. Terraform state IS the IAM backup; the S3 backend (Phase 14a, ch.14.01) is what protects this. Velero has no IAM API access.
  • EKS cluster control-plane state itself. EKS runs the control plane and its etcd. Velero backs up the API objects in your namespaces, not the control plane.
  • EFS file content. EFS is not block storage, so the native EBS snapshot cannot see it. Use Kopia file backup mode for EFS PVs, OR an EFS backup through AWS Backup.
  • EBS volumes attached to Pods that Velero doesn't know about. Manually-attached volumes (via kubectl run with explicit volumeMounts not backed by a PVC) are invisible.

The complete production-grade backup story is: Velero (cluster state + EBS PVs) + AWS Backup (RDS + EFS + cross-region snapshot copy) + Terraform state (IAM + cluster config) + S3 versioning + CRR (object store) + CNPG ScheduledBackup (database PITR). Each catches a different layer; the union is what gets you sleeping through the night. Chapter 14.17 ties them together.

The trap to keep in view: the namespace exclusion list. Phase 14-R's Schedule excludes kube-system, kube-public, kube-node-lease for good reason — these are EKS-managed; restoring their objects causes weird state (a restored CoreDNS config might conflict with the running one). The exclusion list is correct as shipped; the trap is adding to it carelessly. Excluding bookstore because "we don't need to back up the app, it's in GitOps anyway" loses the bookstore-managed CRDs (the Kyverno exceptions, the OpenCost Allocations) that aren't in GitOps. Audit the exclusion list with eyes-on; default to inclusion.

Threats and controls

Threat Control in this chapter Goes deeper
Backup objects hold Secret values as JSON, so reading the objects reads the Secrets Customer-managed KMS key; the Velero role gets decrypt; the bucket refuses plain HTTP and public access 08.02
A Restore copies another namespace's Secrets into one the restorer can read RBAC on the velero namespace, where Velero reconciles Restores; Restore create for platform admins only 08.02
The Velero server runs as cluster-admin, so compromising it reads every Secret Restricted pod in its own namespace; no static AWS key (IRSA, credentials.useSecret = false) 14.03
Someone with bucket rights deletes or overwrites backups Versioning on; Object Lock not set (see below) 08.02
The Velero role deletes EBS volumes or snapshots it did not create Delete conditioned on the velero.io/backup tag key, and create only with that key in the request, so the role deletes only what it made 14.03
The Velero role reads the data of any EBS volume by snapshotting it Not narrowed in this tree: the create statement names every volume in the account. The trust policy admits only the Velero ServiceAccount, and the role is reviewed as a data-read grant 14.03

The chart's cluster-admin binding stays on, because restores create any kind. Limit who can reach the velero namespace and who can create Backup or Restore objects instead.

What a backup holds, and who can read it. Each backup stores the Secrets it selects, in plain JSON inside <NAME>.tar.gz. Three rules decide who can read them:

  • Read needs two grants. Reading an object needs s3:GetObject and kms:Decrypt on the key. velero.tf grants both to the Velero role. Any principal that IAM grants kms:Decrypt on that key can read the backups too, so review that grant the way you review access to a Secret.
  • A restore is a read. A user who can create a Restore can have Velero copy a backed-up namespace's Secrets into another namespace, with --namespace-mappings. Velero writes with its own ServiceAccount, so the user's RBAC does not stop the copy. Velero reconciles Restore objects only in its own namespace, so the boundary is RBAC on velero.
  • Encryption at rest, and TLS in transit. SSE-KMS encrypts the objects at rest, and the bucket policy refuses requests that are not TLS. The example's EBS volumes use the EBS key, so restores need KMS grants on that key, which velero.tf adds.

Object Lock is not set. Versioning keeps the old version of an overwritten or deleted object, but a version can still be deleted for good. Object Lock adds a retention period. In compliance mode, no user, including the account root user, can delete a version before its retain-until date (S3 Object Lock). Whether a backup owner needs that is a decision to record, because it also blocks your own cleanup.

Diagrams

Diagram A — Velero backup flow (Mermaid)

flowchart TB
    sched["Schedule:
nightly-cluster-backup
cron: 0 2 * * *
ttl: 30d"] cron["Schedule controller
cron fires at 02:00 UTC"] bk["Velero creates a Backup CR
backup-202605200200"] velero["Velero server pod
(velero ns)
reads Backup CR"] api["For each included namespace,
list resources via K8s API
(Deployments, ConfigMaps, ...)"] s3meta["S3: backups/backup-.../
velero-backup.json
backup-....tar.gz
(API objects, Secrets included)"] csi["For each EBS-backed PV,
AWS plugin calls
ec2:CreateSnapshot
(via Velero IRSA role)"] snap["EBS snapshot
snap-0123abc
(region-scoped)"] s3snapref["S3: backups/backup-.../
backup-...-volumesnapshots.json.gz
(snapshot IDs recorded)"] pd["Backup phase: InProgress -> Completed
(or Failed; PartiallyFailed)"] obs["BackupStatus visible via
kubectl get backup -n velero
or velero backup describe"] sched --> cron --> bk --> velero velero --> api --> s3meta velero --> csi --> snap --> s3snapref s3meta --> pd s3snapref --> pd pd --> obs note["TTL expiry:
at backup_created + 30d,
Velero deletes the backup +
(via IRSA ec2:DeleteSnapshot)
deletes the EBS snapshot."] obs -.-> note

Diagram B — Backup retention math (ASCII)

RETENTION SCHEME           BACKUPS HELD   STORAGE (200 GB base)      $/mo
─────────────────────────  ──────────────  ─────────────────────────  ────────
Daily, 7-day TTL                   7        ~230 GB                  $11.50
Daily, 30-day TTL                 30        ~345 GB                  $17.25
Daily, 365-day TTL               365        ~2,020 GB                $101.00
23-backup scheme                  23        ~790 GB                  $39.50
─────────────────────────  ──────────────  ─────────────────────────  ────────

23-BACKUP SCHEME BREAKDOWN (Velero + 3 Schedule CRs):

  Schedule A: nightly-daily   cron "0 2 * * *"       ttl "168h"   keeps 7
  Schedule B: weekly          cron "0 3 * * 0"       ttl "672h"   keeps 4
  Schedule C: monthly         cron "0 4 1 * *"       ttl "8760h"  keeps 12
                                                                  total 23

EBS SNAPSHOT INCREMENTAL MATH:
  First snapshot:       200 GB unique blocks    * $0.05/GB-mo  = $10.00/mo
  6 incremental daily:  ~5 GB delta each * 6   * $0.05/GB-mo  =  $1.50/mo
  4 weekly (older):     ~20 GB delta each * 4  * $0.05/GB-mo  =  $4.00/mo
  12 monthly (oldest):  ~40 GB delta each * 12 * $0.05/GB-mo  = $24.00/mo
                                                              ─────────
                                                       Total:   $39.50/mo

  Compare: daily-365-day = $101.00/mo for marginal extra granularity.
  Assumptions: 5 GB changed per day; illustrative, not measured.
─────────────────────────  ──────────────  ─────────────────────────  ────────

Hands-on with the Bookstore Platform

Output blocks in this section are illustrative. They were not captured from a run.

0. Prerequisites

  • The bookstore-platform tree applied with enable_velero = true.
  • kubectl configured for the cluster.
  • velero CLI installed (brew install velero or grab a release from https://github.com/vmware-tanzu/velero/releases; this chapter uses Velero 1.18.x, the app version of the chart velero.tf pins (velero_chart_version 12.2.2).
  • AWS CLI configured to inspect the S3 bucket + EC2 snapshots.

The Terraform shipping this is in ../examples/bookstore-platform/terraform/velero.tf. Read it end-to-end — the IRSA scoping, the bucket lifecycle, and the schedule comments are all there.

1. Confirm Velero is running + the BackupStorageLocation is available

kubectl -n velero get pods

Expected:

NAME                      READY   STATUS    RESTARTS   AGE
velero-7fc8c4d5d8-xyz12   1/1     Running   0          5m
velero backup-location get

Expected:

NAME      PROVIDER   BUCKET                                ACCESS MODE   DEFAULT
default   aws        bookstore-eks-velero-backups-abc123   ReadWrite     true

If the default BSL is Unavailable (status under velero backup-location get -o yaml), the most common causes:

  1. IRSA misconfigured. The Velero Pod's ServiceAccount lacks the eks.amazonaws.com/role-arn annotation (or the role lacks s3:ListBucket). Phase 14-R wires this correctly; if it broke, verify kubectl -n velero get sa velero -o yaml | grep role-arn.
  2. Region mismatch. The BSL's config.region doesn't match the bucket's region. Phase 14-R takes var.region for both; if you've cross-region'd the bucket, the BSL config needs updating.
velero snapshot-location get

Expected:

NAME      PROVIDER
default   aws

2. Take an on-demand backup of a single namespace

The bookstore namespace is a natural target. Take a backup:

velero backup create bookstore-test-$(date +%Y%m%d-%H%M) \
  --include-namespaces=bookstore \
  --snapshot-volumes \
  --wait

Watch progress:

Backup request "bookstore-test-..." submitted successfully.
Waiting for backup to complete. You may safely press ctrl-c to stop waiting...
.....................
Backup completed with status: Completed.

Inspect:

velero backup describe bookstore-test-... --details

Key fields:

  • Phase: Completed — happy path. Failed or PartiallyFailed needs investigation.
  • Total items to be backed up: NNN — every resource the K8s API returned for this namespace.
  • Volume snapshots: N of N completed: every EBS-backed PV in the namespace got an EBS snapshot.
  • Backup format version: 1.1.0 — Velero's metadata version.

3. Inspect what landed in S3

BUCKET=$(aws s3 ls | awk '/velero-backups/ {print $3}' | head -1)
aws s3 ls "s3://$BUCKET/backups/" | head -5

You'll see one prefix per backup, including the one you just took. Drill in:

BACKUP_NAME=$(velero backup get -o json | jq -r '.items[0].metadata.name')
aws s3 ls "s3://$BUCKET/backups/$BACKUP_NAME/"

Files you'll see:

  • velero-backup.json — the backup manifest (which namespaces, which resources, the time, the status).
  • <NAME>.tar.gz: every object the backup includes, as JSON. Secrets are in this file.
  • <NAME>-resource-list.json.gz: the resources the backup selected.
  • <NAME>-volumesnapshots.json.gz: the EBS snapshot IDs for the PVs.

For the curious, list the contents tarball. It holds the Secrets too, so copying it to a laptop puts plaintext Secret values on disk. Delete the copy when you are done.

aws s3 cp "s3://$BUCKET/backups/$BACKUP_NAME/$BACKUP_NAME.tar.gz" /tmp/backup.tar.gz
tar tzf /tmp/backup.tar.gz | head -5
rm /tmp/backup.tar.gz

4. Inspect the EBS snapshots Velero created

aws ec2 describe-snapshots \
  --owner-ids self \
  --filters "Name=tag-key,Values=velero.io/backup" \
  --query 'Snapshots[].[SnapshotId,VolumeId,VolumeSize,State,Tags[?Key==`velero.io/backup`].Value | [0]]' \
  --output table

Expected:

-------------------------------------------------------------
|                     DescribeSnapshots                      |
+---------------+-------------+------+------------+---------+
| SnapshotId    | VolumeId    | Size | State      | Backup  |
+---------------+-------------+------+------------+---------+
| snap-0abc...  | vol-0xxx... |  10  | completed  | <NAME>  |
| snap-0def...  | vol-0yyy... |   5  | completed  | <NAME>  |
+---------------+-------------+------+------------+---------+

Two things to confirm:

  • Snapshots carry a velero.io/backup tag whose value is the backup name, plus velero.io/pv. velero.tf checks the key, not the value, before it allows a delete.
  • State: completed: the snapshot is complete.

5. Run a restore drill — destroy + restore

The fire drill is destroy bookstore's payments namespace, then restore from the backup. Pick a namespace that's safely restorable — for the bookstore platform, bookstore itself is the right target.

# Snapshot current Pod count for the verify step:
kubectl -n bookstore get pods --no-headers | wc -l
# expected: N pods

WARNING — this destroys data: run only on a test/staging cluster.

# Delete the namespace. This destroys every workload in it.
kubectl delete namespace bookstore --wait

# Verify it's gone:
kubectl get namespace bookstore
# Expected: Error from server (NotFound): namespaces "bookstore" not found

Restore from the backup:

velero restore create restore-bookstore-$(date +%Y%m%d-%H%M) \
  --from-backup "$BACKUP_NAME" \
  --include-namespaces=bookstore \
  --wait

Watch:

Restore request "restore-bookstore-..." submitted successfully.
Waiting for restore to complete. You may safely press ctrl-c to stop waiting...
......
Restore completed with status: Completed.

Verify:

kubectl get namespace bookstore
kubectl -n bookstore get pods
kubectl -n bookstore get pvc

Pods should be present (some may be ContainerCreating while the restored PVs are attaching). PVCs should be Bound to new PVs (the old PV UID is rewritten; the data inside is the snapshot's).

Wait for everything to come up:

kubectl -n bookstore wait --for=condition=Ready pod --all --timeout=300s

Verify the data is the snapshot data (not empty volumes):

# Find a CNPG pod and query for a known row:
CNPG=$(kubectl -n bookstore get pod -l cnpg.io/cluster=bookstore-db,cnpg.io/instanceRole=primary -o jsonpath='{.items[0].metadata.name}')
kubectl -n bookstore exec "$CNPG" -- psql -U postgres -d bookstore \
  -c "SELECT count(*) FROM books;"
# Expected: the row count from before deletion.

The restore drill is the single most important Velero exercise. Run it quarterly in production. The first run discovers all the issues (CRD-not-restored, namespace-mapping mistake, missing Cluster-scoped resource); subsequent runs are smooth.

6. Inspect the daily Schedule

velero schedule get

Expected:

NAME                       STATUS    CREATED                        SCHEDULE      BACKUP TTL   LAST BACKUP   SELECTOR
nightly-cluster-backup     Enabled   2026-05-15 12:00:00 +0000 UTC  0 2 * * *     720h         8h ago        <none>

This is the Phase 14-R-installed schedule. To inspect:

kubectl -n velero get schedule nightly-cluster-backup -o yaml | head -40

The schedule spec mirrors the Terraform velero.tf's schedule config — excludedNamespaces, snapshotVolumes: true, ttl: 720h (30 days).

7. Implement the 23-backup retention scheme

The default schedule is daily-with-30-day-TTL (30 backups). To implement 23-backup, replace it with three Schedules. Save as velero-23-scheme.yaml:

---
apiVersion: velero.io/v1
kind: Schedule
metadata:
  name: daily-cluster-backup
  namespace: velero
spec:
  schedule: "0 2 * * *"        # daily 02:00 UTC
  template:
    ttl: "168h"                # 7 days
    includedNamespaces: ["*"]
    excludedNamespaces:
      - kube-system
      - kube-public
      - kube-node-lease
    snapshotVolumes: true
    storageLocation: default
    volumeSnapshotLocations: [default]
---
apiVersion: velero.io/v1
kind: Schedule
metadata:
  name: weekly-cluster-backup
  namespace: velero
spec:
  schedule: "0 3 * * 0"        # Sunday 03:00 UTC
  template:
    ttl: "672h"                # 28 days
    includedNamespaces: ["*"]
    excludedNamespaces:
      - kube-system
      - kube-public
      - kube-node-lease
    snapshotVolumes: true
    storageLocation: default
    volumeSnapshotLocations: [default]
---
apiVersion: velero.io/v1
kind: Schedule
metadata:
  name: monthly-cluster-backup
  namespace: velero
spec:
  schedule: "0 4 1 * *"        # 1st of month 04:00 UTC
  template:
    ttl: "8760h"               # 365 days
    includedNamespaces: ["*"]
    excludedNamespaces:
      - kube-system
      - kube-public
      - kube-node-lease
    snapshotVolumes: true
    storageLocation: default
    volumeSnapshotLocations: [default]
# First delete the default schedule:
kubectl -n velero delete schedule nightly-cluster-backup

# Apply the three-tier:
kubectl apply -f velero-23-scheme.yaml

# Confirm:
velero schedule get

For the bookstore-platform reference, the better answer is to extend Phase 14-R's velero.tf to materialise three Schedule CRs from kubectl_manifest resources; the YAML above is the manual / GitOps path.

8. Test an application-consistent backup (CNPG hook example)

CNPG's own Backup CRD is the production-grade backup; Velero's pre-backup hook is the lightweight companion for the cases where you want a CHECKPOINT before snapshotting.

Set the hook as inherited metadata on the Cluster. CNPG passes spec.inheritedMetadata to the objects it creates for the Cluster, Pods included. Velero reads the hook from the Pod:

kubectl -n bookstore patch cluster bookstore-db --type=merge -p '{
  "spec": {
    "inheritedMetadata": {
      "annotations": {
        "pre.hook.backup.velero.io/container": "postgres",
        "pre.hook.backup.velero.io/command": "[\"/bin/sh\",\"-c\",\"psql -U postgres -c CHECKPOINT\"]",
        "pre.hook.backup.velero.io/timeout": "1m"
      }
    }
  }
}'

Take a backup; Velero will exec the CHECKPOINT into the Pod before snapshotting its PVs.

velero backup create bookstore-consistent-$(date +%Y%m%d-%H%M) \
  --include-namespaces=bookstore \
  --snapshot-volumes \
  --wait

The hook's default on-error is Fail, so a failing command marks the backup as failed or partially failed. Check the phase. For CNPG specifically, the canonical answer is CNPG's Backup/ScheduledBackup CRDs, which manage WAL streaming for true PITR; this hook pattern is the lightweight insurance for other stateful workloads where you don't have a built-in backup CRD.

9. Clean up the test backups

# Delete old test backups. Velero also deletes their EBS snapshots,
# through the ec2:DeleteSnapshot permission scoped to the
# velero.io/backup tag key. The shell cannot expand the backup names,
# so filter them with jq.
velero backup get -o json | jq -r '.items[].metadata.name | select(startswith("bookstore-test-") or startswith("bookstore-consistent-"))' | xargs -n1 velero backup delete --confirm

To remove Velero entirely, set enable_velero = false and terraform apply. The S3 bucket has force_destroy = false in Phase 14-R — backups won't auto-delete on uninstall (this is intentional). To fully tear down, run the pre-destroy cleanup documented in terraform/cleanup-pre-destroy.sh.

How it works under the hood

The Velero server architecture. Velero is a single Deployment in the velero namespace, running the velero/velero image with the velero-plugin-for-aws initContainer. The init container copies a shared plugin binary (velero-plugin-for-aws) into a shared volume; the main velero server process dynamically loads plugins from that volume. The plugin model decouples AWS-specific code from the core Velero binary — there's a plugin for GCP, Azure, AWS, MinIO, etc.

The Velero server's controllers reconcile a set of CRDs:

  • Backup controller — watches Backup CRs; when one appears (created manually or by a Schedule), it walks the included namespaces, lists resources, writes them to S3 as tarballs, and triggers the AWS plugin to snapshot the EBS-backed PVCs. On the native path this chapter configures, no Kubernetes VolumeSnapshot object is created.
  • Restore controller — watches Restore CRs; reads the backup from S3, applies the API objects (with namespace remapping, label filtering, name remapping as configured), and triggers PV provisioning from the recorded snapshot IDs.
  • Schedule controller — watches Schedule CRs; on cron firing, creates a Backup CR (which the Backup controller then handles).
  • GarbageCollectionController — periodically scans Backup CRs; deletes the ones whose age exceeds ttl, then deletes the underlying snapshots via the AWS plugin.

The native snapshot path in detail. For each PV the backup selects, Velero's backup controller calls the AWS plugin's volume snapshotter. The plugin copies the volume's tags to the snapshot, adds Velero's tags (velero.io/backup, velero.io/pv) and the backup's labels, and calls ec2:CreateSnapshot. It returns the snapshot ID, which Velero writes to the backup's volumesnapshots file. No Kubernetes VolumeSnapshot object is created on this path.

Restore from a native snapshot. Restore reads the snapshot ID from the backup. The plugin describes the snapshot and calls ec2:CreateVolume with the snapshot ID, copying the snapshot's tags to the new volume. The volume is attached and the Pod's container starts with the data. An encrypted volume also needs the KMS grants described below.

The IRSA permissions in velero.tf. The aws_iam_policy.velero document scopes the role to:

  • S3: s3:GetObject, s3:DeleteObject, s3:PutObject, s3:AbortMultipartUpload, s3:ListMultipartUploadParts on the bucket's objects, and s3:ListBucket on the bucket.
  • EC2 Describe: ec2:DescribeVolumes and ec2:DescribeSnapshots on *.
  • EC2 Lifecycle: ec2:DeleteSnapshot and ec2:DeleteVolume only when the target has a velero.io/backup tag key, whatever its value.
  • EC2 Create: ec2:CreateSnapshot and ec2:CreateVolume only when the request carries that key, so everything the role creates can be deleted by the statement above.
  • EC2 Tagging: ec2:CreateTags only when ec2:CreateAction names a snapshot or volume create, so the role cannot tag existing resources.
  • KMS: decrypt and data-key actions on the backup bucket key, and on the EBS key for restores from encrypted snapshots. CreateGrant is allowed only for grants AWS creates on the role's behalf.

The tag scoping limits what the role can delete. It does not limit what the role can read. The create statement does not name a source volume, so the role can snapshot any EBS volume in the account. The threats table lists that as a residual risk: treat the Velero role as able to read every EBS volume. The trust policy names only the Velero ServiceAccount, which limits who can assume it. These conditions were checked against the tag names in the plugin source. This example has not been run against an AWS account.

Backup garbage collection. Velero's GC controller scans Backup CRs every hour by default; backups past their TTL are deleted (the Backup CR is removed, then the AWS plugin deletes the underlying S3 prefix + EBS snapshots). The S3 bucket has its own lifecycle (Phase 14-R's aws_s3_bucket_lifecycle_configuration.velero) — backup objects transition to GLACIER_IR after 30 days, non-current versions expire after 180 days. Velero's TTL is the primary retention mechanism; the S3 lifecycle is the safety net for backups that for some reason weren't garbage-collected (e.g., a broken Velero install).

The Kopia file-system backup path (if enabled). When a backup includes defaultVolumesToFsBackup: true (not the example's default), Velero's node-agent DaemonSet mounts each PV's filesystem and runs kopia snapshot against it. Kopia is a deduplicated, encrypted file-backup tool; its repository lives in the same S3 bucket as Velero's metadata (under a kopia/ prefix). A restore via Kopia path reverses the operation — Velero asks the node-agent to mount a fresh PV, runs kopia restore, and the data is in the new volume. Slower than the native snapshot (file scan and S3 write per file), but it works on any PV.

Production notes

In production: The restore drill is the operation that matters. Quarterly: pick a non-critical namespace, destroy it, restore it, verify. The drill exposes (a) Velero misconfig you didn't notice, (b) CRDs that the Backup didn't capture, (c) the exact restore time on real-data scale. Teams that skip this learn the gap at 3am. Bookstore-platform's production fork should add a Cronjob named velero-restore-drill that targets a dedicated restore-test-<DATE> namespace, runs a velero restore, verifies a known-good query, and tears down.

In production: Cross-region backup copy is not in the example. The bucket is single-region, so a region-loss event (AWS region down for the duration of the recovery you need) makes the backup unreachable. Closing that takes S3 Cross-Region Replication (CRR) onto a peer-region bucket. The CRR config goes into the bucket's replication-configuration; the destination bucket lives in a second region (e.g., us-east-1 primary + us-west-2 DR). The cost is cross-region data transfer and duplicate storage, both billed. Chapter 14.17 covers the cross-region DR pattern in detail.

In production: Backup retention math. The example's default (daily-30d, 30 backups) is the simple starting point. The 23-backup scheme (7-daily + 4-weekly + 12-monthly) is the cost-aware option: 23 backups, about $40/mo under the illustrative assumptions above. For compliance regimes (HIPAA, PCI-DSS, GDPR) that require 7-year retention, the math changes. The EBS pricing page lists an archive tier at $0.0125 per GB-month (list price, checked 2026-10-31), but check its restore time before you rely on it. Plan retention against the compliance regime, not against gut feel.

In production: Velero is one of three backup layers. The full production-grade backup story is Velero (K8s + EBS PVs) + AWS Backup (RDS + EFS + cross-region snapshot copy) + Terraform state in S3 backend (IAM + cluster config) + S3 versioning + CRR (object stores) + CNPG ScheduledBackup (database PITR). Each layer catches a different class of state. Velero alone isn't "your backup" — Velero plus the others is.

In production: Application-consistent backups via hooks are the right answer for any stateful workload that has a built-in checkpoint mechanism (Postgres CHECKPOINT, Redis BGSAVE, MongoDB fsync+lock). The annotations (pre.hook.backup.velero.io/command) attach to the Pod (or deployment template, propagated to Pods); the command runs via kubectl exec before the volume snapshot. The CNPG-specific answer is CNPG's own Backup CR; the Velero hook is the general-purpose pattern.

In production: Restore granularity is Velero's superpower. velero restore create --from-backup <NAME> --include-namespaces=bookstore restores just one namespace. velero restore create --from-backup <NAME> --selector app=catalog restores all label-matched resources. velero restore create --from-backup <NAME> --include-resources configmaps,secrets restores only specific resource types. The production runbook uses selective restore for surgical recovery — e.g., restore just the catalog's ConfigMaps to undo a config rollout without touching the rest.

Quick Reference

# List Velero backups.
velero backup get

# Take an on-demand backup of a namespace.
velero backup create <NAME> --include-namespaces=<NS> --snapshot-volumes --wait

# Describe a backup (status + warnings + size).
velero backup describe <NAME> --details

# Stream the backup log (Velero server side).
velero backup logs <NAME>

# List backups in S3 directly.
BUCKET=$(aws s3 ls | awk '/velero-backups/ {print $3}' | head -1)
aws s3 ls "s3://$BUCKET/backups/"

# Restore a backup to its original namespace.
velero restore create <RESTORE-NAME> --from-backup <BACKUP-NAME> --wait

# Restore to a different namespace (namespace-mapping).
velero restore create <RESTORE-NAME> --from-backup <BACKUP-NAME> \
  --namespace-mappings bookstore:bookstore-restored --wait

# Restore only specific resource types.
velero restore create <RESTORE-NAME> --from-backup <BACKUP-NAME> \
  --include-resources configmaps,secrets --wait

# List schedules.
velero schedule get

# Delete a backup (also deletes the EBS snapshot via IRSA).
velero backup delete <NAME> --confirm

# List EBS snapshots Velero created.
aws ec2 describe-snapshots --owner-ids self \
  --filters "Name=tag-key,Values=velero.io/backup" \
  --query 'Snapshots[].[SnapshotId,VolumeSize,State]'

# Check the BackupStorageLocation status.
velero backup-location get

Backup checklist (the production setup is right when all seven are yes):

  • Velero installed via enable_velero = true; BSL default is Available.
  • Schedule nightly-cluster-backup exists, status Enabled, last backup within the last 24h. (Or the 23-backup scheme is in effect.)
  • Restore drill executed within the last 90 days; documented in a runbook with the verified-good query result.
  • S3 bucket has versioning + a customer-managed KMS key + lifecycle to Glacier-IR + DenyInsecureTransport policy.
  • Object Lock decision recorded: set, or left off with a reason.
  • EBS snapshots carry the velero.io/backup tag; AWS account has EBS snapshot quota headroom for the expected backup count.
  • Cross-region replication configured: the bucket replicates to a peer-region bucket; recovery is possible from a region-loss event.

Test your understanding

Try each before opening the answer drawer. The act of trying is the exercise; the answer is the check.

  1. EKS runs the control plane, AWS Backup snapshots EBS volumes, RDS has PITR, S3 has versioning. What does Velero add that none of those provide?

    Show answer Velero snapshots **Kubernetes API objects**: ConfigMaps, Secrets, Deployments, CRDs (Kyverno policies, Argo CD Applications, OpenCost Allocations). EBS snapshots and RDS point-in-time recovery do not cover those. EKS runs the control plane, so there is no etcd backup of your own to restore from. Velero ties API objects + the PVs they reference into a backup unit, so you can restore a namespace, a label-selected subset, or the whole cluster. AWS Backup has EKS support too; check its scope yourself, since this chapter does not test it.

  2. Someone runs kubectl delete ns bookstore at 03:00. You discover at 09:00. Your Velero schedule runs nightly at 02:00 UTC and the bookstore had RDS data behind it. What can Velero restore and what's outside its scope?

    Show answer Velero restores: the Kubernetes API objects in the bookstore namespace (Deployments, Services, ConfigMaps, the bookstore-managed CRDs like Kyverno policies and OpenCost Allocations), plus any in-cluster PVs (CNPG data, if not on RDS) snapshotted at 02:00. **Outside Velero's scope**: the RDS database content — RDS lives outside the cluster, Velero has no RDS API access. The fix for the RDS side is **RDS Automated Backups + Manual Snapshots** (covered by AWS Backup); the chapter's "honest list" explicitly calls this out. The complete restore is Velero (cluster state + EBS PVs) + RDS PITR (database content), executed together; either alone leaves you with half a working system.

  3. A team excludes the bookstore namespace from the backup Schedule because "it's all in GitOps anyway." Three months later they need to restore. What's missing and why does the chapter call this the canonical exclusion-list trap?

    Show answer GitOps stores the *desired* state: the Application manifests, Helm values, Kustomize overlays. It does **not** store cluster-managed state that the controllers create dynamically: Kyverno PolicyExceptions, OpenCost Allocations, Velero's own Backup CRs, any CR a controller creates but doesn't put back in Git. Excluding the namespace skips all of these. The chapter's discipline: default to inclusion, audit the exclusion list with eyes-on, and remember that "we have GitOps" doesn't replace backup. It covers a different layer.

  4. Hands-on extension: take a Velero backup with defaultVolumesToFsBackup: false (native snapshot path), then attach an EFS-backed PVC and try the same. Observe.

    What you should see The native path snapshots the EBS-backed PVCs through the AWS plugin. For the EFS-backed PVC, the plugin logs `Unable to handle CSI driver` and takes no snapshot, so that PVC's data is not in the backup. The fix is file-system backup for that pod: the annotation `backup.velero.io/backup-volumes` naming the EFS volume. That needs a node-agent, which the example does not deploy, and which runs as root with host paths. Adding it means a namespace exception with its reason. The lesson: pick the path per storage driver.

  5. A developer has create on restores.velero.io in the velero namespace, where Velero reconciles Restores. The backup holds a payments namespace. They run velero restore create --from-backup <NAME> --include-namespaces=payments --namespace-mappings payments:team-x. What can they read afterwards, and what stops it?

    Show answer The `payments` Secrets are restored into `team-x`, where the developer already reads Secrets. Velero performs the write with its own cluster-admin ServiceAccount, so the developer's RBAC never applies to the copy. What stops it is policy: create on Restore objects belongs to platform admins. Restore rights are read rights on every Secret in the backup, so keep them there, and keep Backup creation there too.

Further reading