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 类型——Backup、BackupStorageLocation、VolumeSnapshotLocation的完整字段定义、样例 YAML 与各云厂商专属参数并结合仓库源码pkg/apis/velero/v1说明字段的底层实现与取值约束。读完本文你将具备直接手写这三类 CRD 清单、为不同云厂商配置存储位置、并利用 hooks 定制备份流程的实战能力。背景为什么需要直接编写 API 类型 YAMLVelero 的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.go、backupstoragelocation_types.go、volume_snapshot_location_type.go。一、Backup API 类型1.1 用途与 API GroupVersionBackup类型是请求 Velero Server 执行一次备份的请求对象。一旦创建Velero Server 会立即启动备份流程官方文档。它属于 API 组版本velero.io/v1在源码中对应 pkg/apis/velero/v1/backup_types.go 定义的Backup结构体其 kubebuilder 标记marker为其声明了短名bak并通过printcolumn让kubectl 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: 01.3 关键字段深入解析命名空间与资源过滤included/excludedincludedNamespaces/excludedNamespaces与includedResources/excludedResources两对字段共同决定备份范围。其中资源名称既支持 Kubernetes 快捷名如po代表pods也支持全限定名如storageclasses.storage.k8s.io未指定时默认包含全部命名空间/全部资源。对应源码中 backup_types.go 的IncludedNamespaces、ExcludedNamespaces、IncludedResources、ExcludedResources字段类型均为[]string且都标注optional/nullable。includeClusterResources 的三态语义该字段取值为true、false或null不设置源码类型为*boolbackup_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.Duration。ttl在 Go 结构体中对应 backup_types.go 的TTL metav1.Duration是一个可被time.Duration解析的字符串如24h0m0s。storageLocation 与 volumeSnapshotLocationsstorageLocation备份 tarball 与日志的存储目标值为一个BackupStorageLocation的名称不指定时使用默认位置。volumeSnapshotLocations该备份创建的卷快照的存放位置列表值为VolumeSnapshotLocation名称。对应源码字段见 backup_types.go。hooks只能通过 YAML 配置的备份钩子hooks 是本文档强调的CLI 无法配置的核心能力。钩子结构分为两层资源级规则hooks.resources[]通过includedNamespaces/excludedNamespaces/includedResources/excludedResources/labelSelector筛选钩子作用的对象文档说明当前唯一支持的资源类型是pods。钩子执行阶段与内容pre在自定义 action及附加项处理之前执行post在所有自定义 action 与附加项处理之后执行每个阶段目前仅支持exec类型的钩子即通过pod exec API在 Pod 内指定容器中执行命令。exec钩子的三个子字段字段默认值说明containerPod 内第一个容器执行命令的目标容器名可选command无必填以数组形式给出的命令及其参数如[/bin/uname, -a]onErrorFail命令执行出错时的处理策略可选值为Fail与Continuetimeout30s等待命令执行完成的超时时间从源码看BackupResourceHookSpec定义了Name、两组 include/exclude 数组、LabelSelector、PreHooks与PostHooksbackup_types.goExecHook的OnError类型HookErrorMode通过 kubebuilder 校验枚举限定为Continue/Fail两个合法值backup_types.goCommand带有MinItems1的校验约束backup_types.go。错误处理语义为Continue表示错误可接受、继续执行其余钩子Fail表示错误严重、停止执行后续钩子——两者最终都会使备份进入PartiallyFailed状态。status由控制器维护用户不应手动设置status由 Velero Server 的控制器写入文档明确Users should not set any data here。它包含phase备份生命周期阶段。v1.1 文档列出的合法值为New、FailedValidation、InProgress、Completed、PartiallyFailed、Failedexpiration该备份可被垃圾回收的时间点validationErrors校验错误数组startTimestamp/completionTimestamp备份起止时间volumeSnapshotsAttempted/volumeSnapshotsCompleted尝试/成功创建的卷快照数warnings/errors备份过程中记录的警告与错误计数详细内容保存在对象存储中的备份日志里。从当前仓库源码看BackupPhase枚举已进一步扩展为New;Queued;ReadyToStart;FailedValidation;InProgress;WaitingForPluginOperations;WaitingForPluginOperationsPartiallyFailed;Finalizing;FinalizingPartiallyFailed;Completed;PartiallyFailed;Failed;Deletingbackup_types.go并新增了FormatVersion、FailureReason、Progress、HookStatus等状态字段——这说明随着版本演进阶段机更细分但本文所述的 v1.1 基本阶段语义保持一致。二、BackupStorageLocation API 类型2.1 概念对象存储目标BackupStorageLocation简称 BSLkubebuilder 短名为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: default2.3 主配置参数KeyTypeDefaultMeaningproviderStringVelero 原生支持aws、gcp、azure其他 provider 可通过外部插件获得必填实际存储备份的云厂商名称objectStorageObjectStorageLocation—该 provider 对象存储的规格objectStorage/bucketString必填备份上传到的存储桶objectStorage/prefixString可选存储桶内用于存放备份的子目录configmap[string]string详见各厂商专属配置无可选传给云厂商的对象存储配置键值对accessModeStringReadWriteVelero 访问该位置的方式合法值ReadWrite、ReadOnly补充源码细节BackupStorageLocationSpec还包含Credential引用 Secret 指定该位置使用的凭据、Default标记默认位置、BackupSyncPeriod从对象存储同步备份 API 对象的频率0 表示禁用与ValidationFrequency对象存储校验频率0 表示禁用等字段backupstoragelocation_types.goaccessMode的合法值在BackupStorageLocationAccessMode中以 kubebuilder 枚举约束为ReadOnly/ReadWritebackupstoragelocation_types.go。objectStorage还支持caCert内联 CA 证书已废弃与caCertRef引用同命名空间内包含 CA 证书的 Secret且二者不能同时设置——Validate()方法会返回 cannot specify both caCert and caCertRef in objectStorage 错误backupstoragelocation_types.go。2.4 AWS及 S3 兼容存储专属 configKeyTypeDefaultMeaningregionstring空如us-east-1未提供时向 AWS S3 API 查询s3ForcePathStyleboolfalse使用本地存储服务如 Minio时需设为trues3Urlstring非 AWS 托管存储必填如http://minio:9000可显式指定 AWS S3 URLVelero 也能由region、bucket自动生成主要用于 Minio 等本地存储publicUrlstring空如https://minio.mycluster.com若指定生成下载 URL如日志下载时优先使用它替代s3Url主要用于本地存储服务kmsKeyIdstring空如502b409c-4da1-419f-a16e-eif453b3i49f或alias/KMS-Key-Alias-Name指定 AWS KMS key id 或别名以启用 S3 中备份的加密仅适用于 AWS S3可能需要显式授予密钥使用权限signatureVersionstring4生成用于 velero CLI 下载备份或拉取日志的签名 URL 时使用的签名算法版本可选1与4通常默认 v4 即可但 Quobyte 等部分 S3 兼容 provider 仅支持 v1profilestringdefault凭据文件中用于该存储位置的 AWS profile2.5 Azure 与 GCP 专属 configAzureKeyTypeDefaultMeaningresourceGroupstring必填包含该备份存储位置存储账户的资源组名称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简称 VSLkubebuilder 短名为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: default3.3 主配置参数KeyTypeDefaultMeaningproviderStringVelero 原生支持aws、gcp、azure其他 provider 可通过外部插件获得必填实际存储卷快照的云厂商名称config见各厂商专属配置或 provider 文档—厂商专属配置键值对3.4 AWS 专属 configKeyTypeDefaultMeaningregionstring空如us-east-1必填profilestringdefault凭据文件中用于该存储位置的 AWS profile3.5 Azure 专属 configKeyTypeDefaultMeaningapiTimeoutmetav1.Duration2m0sAzure API 请求完成前的等待超时时间resourceGroupstring可选卷快照的存放资源组名称若与集群资源组不同则指定该项3.6 GCP 专属 configKeyTypeDefaultMeaningsnapshotLocationstring空如us-central1未指定时快照存放在默认位置projectstring空快照的存放项目 ID若与 IAM 账户所在项目不同则指定该项可选3.7 与 Backup 的协作关系VolumeSnapshotLocation通过Backup.spec.volumeSnapshotLocations被引用见本文 1.3 节。当Backup.spec.snapshotVolumes为null时只要 Velero 配置了持久卷 provider就会自动执行快照而快照具体落在哪个位置则由备份中指定的 VSL 名称决定。这也解释了为什么官方文档要求每个 provider 至少配置一个 VSL——它是snapshotVolumes生效的前提条件。四、三种 API 类型的协作流程与验证方法4.1 完整配置链条一次完整的、只依赖 YAML 的备份流程通常按以下顺序配置创建BackupStorageLocation至少一个通常命名为default声明备份 tarball 与日志的对象存储位置按需创建VolumeSnapshotLocation每个要用到的 provider 至少一个声明卷快照位置创建Backup在spec中通过storageLocation与volumeSnapshotLocations引用上述位置并通过hooks注入备份钩子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/Phase、Errors/Warnings、Started/Age等关键列便于快速观察对象状态。结语本文以官方 API 类型文档为主体完整覆盖了Backup、BackupStorageLocation、VolumeSnapshotLocation三种 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),仅供参考