Velero API 类型详解:通过 YAML 配置 Backup、BackupStorageLocation 与 VolumeSnapshotLocation
2026/9/17 15:33:49 网站建设 项目流程

Velero API 类型详解:通过 YAML 配置 Backup、BackupStorageLocation 与 VolumeSnapshotLocation

【免费下载链接】veleroBackup and migrate Kubernetes applications and their persistent volumes项目地址: https://gitcode.com/GitHub_Trending/ve/velero

导读

在 Velero 中,veleroCLI 只覆盖了常用备份操作的配置面;部分功能(例如备份钩子 hooks)只能通过直接编写 Kubernetes 自定义资源(CRD)的 JSON/YAML 来配置。本文以 Velero 官方文档 site/content/docs/v1.1.0/api-types/README.md 为主体,系统讲解三类核心 API 类型——BackupBackupStorageLocationVolumeSnapshotLocation的完整字段定义、样例 YAML 与各云厂商专属参数,并结合仓库源码(pkg/apis/velero/v1)说明字段的底层实现与取值约束。读完本文,你将具备直接手写这三类 CRD 清单、为不同云厂商配置存储位置、并利用 hooks 定制备份流程的实战能力。

背景:为什么需要直接编写 API 类型 YAML

Velero 的velero backup create等 CLI 命令覆盖了大多数日常操作,但 CLI 并未暴露所有参数。官方文档明确指出:这里列出的 API 类型,是那些具有"只能通过 json/yaml 而非veleroCLI 配置"功能(如 hooks)的类型。因此在以下场景你必须手写 CRD YAML:

  • 需要在备份过程中注入pre/post钩子(在 Pod 容器内执行命令);
  • 需要精细化控制备份的 TTL、存储位置、快照位置等组合参数;
  • 需要在集群中声明对象存储目标(BackupStorageLocation)与卷快照目标(VolumeSnapshotLocation)。

这些 CRD 均在velero.io/v1API 组版本下定义,其 Go 结构体声明集中在 pkg/apis/velero/v1 目录(backup_types.gobackupstoragelocation_types.govolume_snapshot_location_type.go)。


一、Backup API 类型

1.1 用途与 API GroupVersion

Backup类型是请求 Velero Server 执行一次备份的请求对象。一旦创建,Velero Server 会立即启动备份流程(官方文档)。它属于 API 组版本velero.io/v1,在源码中对应 pkg/apis/velero/v1/backup_types.go 定义的Backup结构体,其 kubebuilder 标记(marker)为其声明了短名bak,并通过printcolumnkubectl get backups可直接展示Status/Errors/Warnings/Started等列。

1.2 完整示例与字段逐项说明

下面这段来自官方文档的完整Backup对象示例,包含了每个字段的注释说明,可直接作为编写清单的模板:

# Standard Kubernetes API Version declaration. Required. apiVersion: velero.io/v1 # Standard Kubernetes Kind declaration. Required. kind: Backup # Standard Kubernetes metadata. Required. metadata: # Backup name. May be any valid Kubernetes object name. Required. name: a # Backup namespace. Must be the namespace of the Velero server. Required. namespace: velero # Parameters about the backup. Required. spec: # Array of namespaces to include in the backup. If unspecified, all namespaces are included. # Optional. includedNamespaces: - '*' # Array of namespaces to exclude from the backup. Optional. excludedNamespaces: - some-namespace # Array of resources to include in the backup. Resources may be shortcuts (e.g. 'po' for 'pods') # or fully-qualified. If unspecified, all resources are included. Optional. includedResources: - '*' # Array of resources to exclude from the backup. Resources may be shortcuts (e.g. 'po' for 'pods') # or fully-qualified. Optional. excludedResources: - storageclasses.storage.k8s.io # Whether or not to include cluster-scoped resources. Valid values are true, false, and # null/unset. If true, all cluster-scoped resources are included (subject to included/excluded # resources and the label selector). If false, no cluster-scoped resources are included. If unset, # all cluster-scoped resources are included if and only if all namespaces are included and there are # no excluded namespaces. Otherwise, if there is at least one namespace specified in either # includedNamespaces or excludedNamespaces, then the only cluster-scoped resources that are backed # up are those associated with namespace-scoped resources included in the backup. For example, if a # PersistentVolumeClaim is included in the backup, its associated PersistentVolume (which is # cluster-scoped) would also be backed up. includeClusterResources: null # Individual objects must match this label selector to be included in the backup. Optional. labelSelector: matchLabels: app: velero component: server # Whether or not to snapshot volumes. This only applies to PersistentVolumes for Azure, GCE, and # AWS. Valid values are true, false, and null/unset. If unset, Velero performs snapshots as long as # a persistent volume provider is configured for Velero. snapshotVolumes: null # Where to store the tarball and logs. storageLocation: aws-primary # The list of locations in which to store volume snapshots created for this backup. volumeSnapshotLocations: - aws-primary - gcp-primary # The amount of time before this backup is eligible for garbage collection. If not specified, # a default value of 30 days will be used. The default can be configured on the velero server # by passing the flag --default-backup-ttl. ttl: 24h0m0s # Actions to perform at different times during a backup. The only hook currently supported is # executing a command in a container in a pod using the pod exec API. Optional. hooks: # Array of hooks that are applicable to specific resources. Optional. resources: - # Name of the hook. Will be displayed in backup log. name: my-hook # Array of namespaces to which this hook applies. If unspecified, the hook applies to all # namespaces. Optional. includedNamespaces: - '*' # Array of namespaces to which this hook does not apply. Optional. excludedNamespaces: - some-namespace # Array of resources to which this hook applies. The only resource supported at this time is # pods. includedResources: - pods # Array of resources to which this hook does not apply. Optional. excludedResources: [] # This hook only applies to objects matching this label selector. Optional. labelSelector: matchLabels: app: velero component: server # An array of hooks to run before executing custom actions. Currently only "exec" hooks are supported. pre: - # The type of hook. This must be "exec". exec: # The name of the container where the command will be executed. If unspecified, the # first container in the pod will be used. Optional. container: my-container # The command to execute, specified as an array. Required. command: - /bin/uname - -a # How to handle an error executing the command. Valid values are Fail and Continue. # Defaults to Fail. Optional. onError: Fail # How long to wait for the command to finish executing. Defaults to 30 seconds. Optional. timeout: 10s # An array of hooks to run after all custom actions and additional items have been # processed. Currently only "exec" hooks are supported. post: # Same content as pre above. # Status about the Backup. Users should not set any data here. status: # The version of this Backup. The only version currently supported is 1. version: 1 # The date and time when the Backup is eligible for garbage collection. expiration: null # The current phase. Valid values are New, FailedValidation, InProgress, Completed, PartiallyFailed, Failed. phase: "" # An array of any validation errors encountered. validationErrors: null # Date/time when the backup started being processed. startTimestamp: 2019-04-29T15:58:43Z # Date/time when the backup finished being processed. completionTimestamp: 2019-04-29T15:58:56Z # Number of volume snapshots that Velero tried to create for this backup. volumeSnapshotsAttempted: 2 # Number of volume snapshots that Velero successfully created for this backup. volumeSnapshotsCompleted: 1 # Number of warnings that were logged by the backup. warnings: 2 # Number of errors that were logged by the backup. errors: 0

1.3 关键字段深入解析

命名空间与资源过滤(included/excluded)

includedNamespaces/excludedNamespacesincludedResources/excludedResources两对字段共同决定备份范围。其中:

  • 资源名称既支持 Kubernetes 快捷名(如po代表pods),也支持全限定名(如storageclasses.storage.k8s.io);
  • 未指定时默认包含全部命名空间/全部资源。

对应源码中 backup_types.go 的IncludedNamespacesExcludedNamespacesIncludedResourcesExcludedResources字段,类型均为[]string,且都标注+optional/+nullable

includeClusterResources 的三态语义

该字段取值为truefalsenull(不设置),源码类型为*bool(backup_types.go)。三态行为如下:

取值行为
true备份所有集群级资源(仍受 included/excluded resources 与 labelSelector 约束)
false不备份任何集群级资源
null(默认)当所有命名空间都被包含且无排除命名空间时,备份所有集群级资源;否则仅备份与所包含命名空间级资源相关联的集群级资源。例如备份了某个 PVC,则其关联的 PV(集群级)也会被纳入备份
ttl 与垃圾回收

ttl指定该备份在多长时间后进入可被垃圾回收(GC)的状态。文档注明:若未指定,默认值为 30 天,且该默认值可通过 Velero Server 的--default-backup-ttl启动参数覆盖。这在服务端配置源码 pkg/cmd/server/config/config.go 中可以得到印证:flags.DurationVar(&c.DefaultBackupTTL, "default-backup-ttl", c.DefaultBackupTTL, "How long to wait by default before backups can be garbage collected."),其类型在 config.go 中定义为DefaultBackupTTL time.Durationttl在 Go 结构体中对应 backup_types.go 的TTL metav1.Duration,是一个可被time.Duration解析的字符串(如24h0m0s)。

storageLocation 与 volumeSnapshotLocations
  • storageLocation:备份 tarball 与日志的存储目标,值为一个BackupStorageLocation的名称;不指定时使用默认位置。
  • volumeSnapshotLocations:该备份创建的卷快照的存放位置列表,值为VolumeSnapshotLocation名称。

对应源码字段见 backup_types.go。

hooks:只能通过 YAML 配置的备份钩子

hooks 是本文档强调的"CLI 无法配置"的核心能力。钩子结构分为两层:

  1. 资源级规则hooks.resources[]):通过includedNamespaces/excludedNamespaces/includedResources/excludedResources/labelSelector筛选钩子作用的对象;文档说明当前唯一支持的资源类型是pods
  2. 钩子执行阶段与内容
    • pre:在自定义 action(及附加项)处理之前执行;
    • post:在所有自定义 action 与附加项处理之后执行;
    • 每个阶段目前仅支持exec类型的钩子,即通过pod exec API在 Pod 内指定容器中执行命令。

exec钩子的三个子字段:

字段默认值说明
containerPod 内第一个容器执行命令的目标容器名,可选
command无(必填)以数组形式给出的命令及其参数,如["/bin/uname", "-a"]
onErrorFail命令执行出错时的处理策略,可选值为FailContinue
timeout30s等待命令执行完成的超时时间

从源码看,BackupResourceHookSpec定义了Name、两组 include/exclude 数组、LabelSelectorPreHooksPostHooks(backup_types.go);ExecHookOnError类型HookErrorMode通过 kubebuilder 校验枚举限定为Continue/Fail两个合法值(backup_types.go),Command带有MinItems=1的校验约束(backup_types.go)。错误处理语义为:Continue表示错误可接受、继续执行其余钩子;Fail表示错误严重、停止执行后续钩子——两者最终都会使备份进入PartiallyFailed状态。

status:由控制器维护,用户不应手动设置

status由 Velero Server 的控制器写入,文档明确"Users should not set any data here"。它包含:

  • phase:备份生命周期阶段。v1.1 文档列出的合法值为NewFailedValidationInProgressCompletedPartiallyFailedFailed
  • expiration:该备份可被垃圾回收的时间点;
  • validationErrors:校验错误数组;
  • startTimestamp/completionTimestamp:备份起止时间;
  • volumeSnapshotsAttempted/volumeSnapshotsCompleted:尝试/成功创建的卷快照数;
  • warnings/errors:备份过程中记录的警告与错误计数(详细内容保存在对象存储中的备份日志里)。

从当前仓库源码看,BackupPhase枚举已进一步扩展为New;Queued;ReadyToStart;FailedValidation;InProgress;WaitingForPluginOperations;WaitingForPluginOperationsPartiallyFailed;Finalizing;FinalizingPartiallyFailed;Completed;PartiallyFailed;Failed;Deleting(backup_types.go),并新增了FormatVersionFailureReasonProgressHookStatus等状态字段——这说明随着版本演进,阶段机更细分,但本文所述的 v1.1 基本阶段语义保持一致。


二、BackupStorageLocation API 类型

2.1 概念:对象存储目标

BackupStorageLocation(简称 BSL,kubebuilder 短名为bsl)是 Velero 存储备份归档与日志的对象存储位置。集群中通过该 CRD 表达,源码定义见 pkg/apis/velero/v1/backupstoragelocation_types.go。

Velero 必须至少有一个BackupStorageLocation。默认情况下它被期望命名为default,但也可以通过velero server--default-backup-storage-location参数修改该名称。未显式指定存储位置的备份,将保存到该默认位置。该启动参数在服务端配置源码中同样存在(pkg/cmd/server/config/config.go),并已标注为 DEPRECATED,推荐改用velero backup-location set --default命令管理默认位置。

2.2 示例 YAML

官方文档给出的样例:

apiVersion: velero.io/v1 kind: BackupStorageLocation metadata: name: default namespace: velero spec: provider: aws objectStorage: bucket: myBucket config: region: us-west-2 profile: "default"

2.3 主配置参数

KeyTypeDefaultMeaning
providerString(Velero 原生支持awsgcpazure,其他 provider 可通过外部插件获得)必填实际存储备份的云厂商名称
objectStorageObjectStorageLocation该 provider 对象存储的规格
objectStorage/bucketString必填备份上传到的存储桶
objectStorage/prefixString可选存储桶内用于存放备份的子目录
configmap[string]string(详见各厂商专属配置)无(可选)传给云厂商的对象存储配置键值对
accessModeStringReadWriteVelero 访问该位置的方式,合法值ReadWriteReadOnly

补充源码细节:BackupStorageLocationSpec还包含Credential(引用 Secret 指定该位置使用的凭据)、Default(标记默认位置)、BackupSyncPeriod(从对象存储同步备份 API 对象的频率,0 表示禁用)与ValidationFrequency(对象存储校验频率,0 表示禁用)等字段(backupstoragelocation_types.go);accessMode的合法值在BackupStorageLocationAccessMode中以 kubebuilder 枚举约束为ReadOnly/ReadWrite(backupstoragelocation_types.go)。objectStorage还支持caCert(内联 CA 证书,已废弃)与caCertRef(引用同命名空间内包含 CA 证书的 Secret),且二者不能同时设置——Validate()方法会返回 "cannot specify both caCert and caCertRef in objectStorage" 错误(backupstoragelocation_types.go)。

2.4 AWS(及 S3 兼容存储)专属 config

KeyTypeDefaultMeaning
regionstring"us-east-1";未提供时向 AWS S3 API 查询
s3ForcePathStyleboolfalse使用本地存储服务(如 Minio)时需设为true
s3Urlstring非 AWS 托管存储必填http://minio:9000;可显式指定 AWS S3 URL,Velero 也能由regionbucket自动生成,主要用于 Minio 等本地存储
publicUrlstringhttps://minio.mycluster.com;若指定,生成下载 URL(如日志下载)时优先使用它替代s3Url,主要用于本地存储服务
kmsKeyIdstring"502b409c-4da1-419f-a16e-eif453b3i49f""alias/<KMS-Key-Alias-Name>";指定 AWS KMS key id 或别名以启用 S3 中备份的加密,仅适用于 AWS S3,可能需要显式授予密钥使用权限
signatureVersionstring"4"生成用于 velero CLI 下载备份或拉取日志的签名 URL 时使用的签名算法版本,可选"1""4";通常默认 v4 即可,但 Quobyte 等部分 S3 兼容 provider 仅支持 v1
profilestring"default"凭据文件中用于该存储位置的 AWS profile

2.5 Azure 与 GCP 专属 config

Azure

KeyTypeDefaultMeaning
resourceGroupstring必填包含该备份存储位置存储账户的资源组名称
storageAccountstring必填该备份存储位置的存储账户名称

GCP:不需要任何参数。

2.6 一个可落地的本地实践:Minio 场景

仓库中的 examples/minio/00-minio-deployment.yaml 提供了完整的 Minio 部署示例:在velero命名空间部署 Minio 服务(minio/minio:latest,访问密钥minio/minio123),并通过一个 Job 使用mc客户端创建velero桶。在这种本地 S3 兼容环境下,对应的BackupStorageLocation应配置为:

apiVersion: velero.io/v1 kind: BackupStorageLocation metadata: name: default namespace: velero spec: provider: aws objectStorage: bucket: velero config: region: minio s3ForcePathStyle: "true" s3Url: http://minio:9000 publicUrl: http://minio:9000

注意此处s3ForcePathStyle: "true"s3Url的配合,正是官方参数表中"本地存储服务(Minio)"场景的落地写法。


三、VolumeSnapshotLocation API 类型

3.1 概念:卷快照目标

VolumeSnapshotLocation(简称 VSL,kubebuilder 短名为vsl)是备份所创建的卷快照的存放位置,由provider + location组合描述,源码定义见 pkg/apis/velero/v1/volume_snapshot_location_type.go。

Velero 支持为多个 provider 分别配置卷快照,也允许为同一个 provider 配置多个VolumeSnapshotLocation,但每次备份时每个 provider 只能选择一个位置每个云 provider 至少需要一个VolumeSnapshotLocation

3.2 示例 YAML

官方文档给出的样例:

apiVersion: velero.io/v1 kind: VolumeSnapshotLocation metadata: name: aws-default namespace: velero spec: provider: aws config: region: us-west-2 profile: "default"

3.3 主配置参数

KeyTypeDefaultMeaning
providerString(Velero 原生支持awsgcpazure,其他 provider 可通过外部插件获得)必填实际存储卷(快照)的云厂商名称
config见各厂商专属配置或 provider 文档厂商专属配置键值对

3.4 AWS 专属 config

KeyTypeDefaultMeaning
regionstring"us-east-1"必填
profilestring"default"凭据文件中用于该存储位置的 AWS profile

3.5 Azure 专属 config

KeyTypeDefaultMeaning
apiTimeoutmetav1.Duration2m0sAzure API 请求完成前的等待超时时间
resourceGroupstring可选卷快照的存放资源组名称;若与集群资源组不同,则指定该项

3.6 GCP 专属 config

KeyTypeDefaultMeaning
snapshotLocationstring"us-central1";未指定时快照存放在默认位置
projectstring快照的存放项目 ID;若与 IAM 账户所在项目不同,则指定该项(可选)

3.7 与 Backup 的协作关系

VolumeSnapshotLocation通过Backup.spec.volumeSnapshotLocations被引用(见本文 1.3 节)。当Backup.spec.snapshotVolumesnull时,只要 Velero 配置了持久卷 provider,就会自动执行快照;而快照具体落在哪个位置,则由备份中指定的 VSL 名称决定。这也解释了为什么官方文档要求"每个 provider 至少配置一个 VSL"——它是snapshotVolumes生效的前提条件。


四、三种 API 类型的协作流程与验证方法

4.1 完整配置链条

一次完整的、只依赖 YAML 的备份流程通常按以下顺序配置:

  1. 创建BackupStorageLocation(至少一个,通常命名为default),声明备份 tarball 与日志的对象存储位置;
  2. 按需创建VolumeSnapshotLocation(每个要用到的 provider 至少一个),声明卷快照位置;
  3. 创建Backup,在spec中通过storageLocationvolumeSnapshotLocations引用上述位置,并通过hooks注入备份钩子;
  4. Velero Server 的控制器立即处理该Backup对象并更新其status

4.2 验证方式

创建上述 CRD 后,可用标准 kubectl 命令验证:

kubectl get backups.velero.io -n velero kubectl get backupstoragelocations.velero.io -n velero kubectl get volumesnapshotlocations.velero.io -n velero

由于三类资源都声明了printcolumn标记(见各类型源码),kubectl get会直接输出Status/PhaseErrors/WarningsStarted/Age等关键列,便于快速观察对象状态。

结语

本文以官方 API 类型文档为主体,完整覆盖了BackupBackupStorageLocationVolumeSnapshotLocation三种 CRD 的字段定义、示例 YAML 与云厂商专属参数,并结合 pkg/apis/velero/v1 的 Go 类型声明、pkg/cmd/server/config/config.go 的服务端默认参数以及 examples/minio/00-minio-deployment.yaml 的本地存储示例做了源码级印证。掌握这三类 API 类型后,你将能够摆脱 CLI 的限制,用纯 YAML 精确编排 Velero 的备份范围、存储位置与钩子行为,为生产环境的自定义备份策略打下基础。

【免费下载链接】veleroBackup and migrate Kubernetes applications and their persistent volumes项目地址: https://gitcode.com/GitHub_Trending/ve/velero

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询