Modify cluster resources during application restoration so that a backed-up application runs correctly in a different cluster environment, such as when you remap namespaces or change the image registry in a hybrid cloud scenario.
How resource modification works
When you back up cluster resources, by default, Backup Center performs a full backup of the runtime configuration at the time of the backup. During restoration, you might need to manually modify specific fields or configurations. For example, in a hybrid cloud scenario, different clusters might pull images from different image registries, so you must adjust the image address in the image field when you restore the application.
Resource modifications during restoration fall into three types, depending on how they are applied:
Default modifications — Applied automatically by the migrate-controller add-on during restoration. No configuration is required.
Common modifications — Applied by configuring specific fields in the restore task.
Custom modifications — Applied through the Resource Modifier feature of Velero. You create a ConfigMap that supports JSON Patch operations such as
add,delete, andreplaceto change specified fields.
Use the following table to choose a modification method based on what you need to change:
What you need to modify | Modification method |
Remove temporary information such as resource UIDs; convert Flexvolume to CSI when restoring volumes; upgrade API versions; apply known cross-cloud compatibility fixes | Default modifications |
Remap namespaces; map StorageClass and image registry addresses; override Service and Ingress annotations for network plugin compatibility | Common modifications |
Change other fields, such as a volume mount path or node affinity | Custom modifications |
Limitations
Before you modify resources during restoration, review the following constraints of the Resource Modifier feature:
Permissions — The Resource Modifier feature is available only to users with cluster role-based access control (RBAC) administrator permissions, and it does not support modifying security-sensitive resource groups or fields. For more information about cluster RBAC administrator authorization, see Authorize operations on in-cluster resources with RBAC.
Volumes — By default, volume data uses dynamic volume provisioning during backup and restoration. The Container Storage Interface (CSI) plugin creates a new volume based on the specified StorageClass. Therefore, the Resource Modifier feature does not support modifying volumes in this scenario. If you need to modify volume configurations, consider changing the target StorageClass.
Cluster version — To modify resources by using the Resource Modifier feature, make sure that the restore cluster runs Kubernetes 1.20 or later and uses the CSI storage plugin.
Prerequisites
The migrate-controller add-on of version 1.8.1 or later is installed in both the backup cluster and the restore cluster. For more information, see Install migrate-controller and configure permissions.
A backup vault is created in the backup cluster. For more information, see Create a backup vault. The backup vault used in this topic has the following configuration:
Name | OSS bucket name | OSS bucket subdirectory | OSS bucket region | Scope |
vault | cnfs-oss-test | subpath | China (Beijing) | Does not affect queries |
If the backup cluster, restore cluster, and backup vault are not in the same region, you must enable public network access for both the backup cluster and the restore cluster.
Example scenario
In this example, you back up an NGINX application and restore it to a different namespace and cluster. During restoration, you remap the namespace and image registry address through common modifications, and you use the Resource Modifier feature to change a volume mount path and remove node affinity.
A StatefulSet is deployed in the default namespace of the backup cluster. The image registry is provided by the OpenAnolis community at anolis-registry.cn-zhangjiakou.cr.aliyuncs.com/openanolis. The application uses the volumeClaimTemplates field to automatically create cloud disk volumes with the alicloud-disk-topology-alltype StorageClass.
The following YAML shows the application configuration:
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: web
namespace: default
labels:
app: nginx
spec:
replicas: 2
selector:
matchLabels:
app: nginx
serviceName: nginx
template:
metadata:
labels:
app: nginx
spec:
affinity:
nodeAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- preference:
matchExpressions:
- key: node-role.kubernetes.io/control-plane
operator: Exists
weight: 1
containers:
- image: anolis-registry.cn-zhangjiakou.cr.aliyuncs.com/openanolis/nginx:1.14.1-8.6
imagePullPolicy: IfNotPresent
name: nginx
ports:
- containerPort: 80
name: web
protocol: TCP
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
volumeMounts:
- mountPath: /usr/share/nginx/html/
name: www
volumeClaimTemplates:
- apiVersion: v1
kind: PersistentVolumeClaim
metadata:
labels:
app: nginx
name: www
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 20Gi
storageClassName: alicloud-disk-topology-alltype
volumeMode: FilesystemRun the following command to verify that the application and volumes are in a normal state:
kubectl get pod && kubectl get pvcExpected output:
NAME READY STATUS RESTARTS AGE
web-0 1/1 Running 0 39s
web-1 1/1 Running 0 30s
NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS VOLUMEATTRIBUTESCLASS AGE
www-web-0 Bound d-2zefofsg0uzoiaxxxxxx 20Gi RWO alicloud-disk-topology-alltype <unset> 3m18s
www-web-1 Bound d-2zedgdlghw2oudxxxxxx 20Gi RWO alicloud-disk-topology-alltype <unset> 30sStep 1: Back up the application in the backup cluster
Create an Instant Backup task by using either kubectl or the ACK console.
kubectl
Create a file named
applicationbackup.yamlin the backup cluster with the following content:apiVersion: csdr.alibabacloud.com/v1beta1 kind: ApplicationBackup metadata: # If this backup vault has already been used in the cluster, the csdr.alibabacloud.com/backuplocations annotation can be omitted. annotations: csdr.alibabacloud.com/backuplocations: '{"name":"<backuplocationName>","region":"<bucketRegion>","bucket":"<bucketName>","prefix":"<path>","provider":"alibabacloud"}' name: <backupName> namespace: csdr spec: backupType: AppAndPvBackup includedNamespaces: - default pvBackup: defaultPvBackup: true storageLocation: <backuplocationName> ttl: 720h0m0sRun the following command in the backup cluster to deploy the
ApplicationBackuptask:kubectl apply -f applicationbackup.yamlRun the following command to check the backup task status and confirm that the status is
Completed:kubectl -ncsdr get applicationbackup <backupName> --watchExpected output:
NAME PHASE AGE <backupName> Completed 18s
Console
Log on to the ACK console. In the left navigation pane, click Clusters.
On the Clusters page, click the cluster name. In the left-side navigation pane, choose Operations > Application Backup. If prompted, install the backup service component. For registered and dedicated clusters, also configure permissions.
On the Application Backup page, click Back up Now. In the Back up Now panel, configure the parameters for the backup, and then click OK. For more information about advanced configuration parameters, see Back up and restore applications in a cluster.
Parameter
Description
Example
Name
The name of the Instant Backup task. This parameter is required.
backup
Backup Vaults
(Required) The vault to store the backup in.
cnfs-oss-test
Backup Type
Application Backup or Data Protection. See the backup plan table above for details.
application backup
Backup Namespaces
(Required) One or more namespaces to back up. The
kube-system,kube-publish,kube-node-lease, andcsdrnamespaces cannot be backed up.default
Backup Volume
Specifies whether to back up data in the volumes used by the application. Mounted Volumes backs up to ECS snapshots (disk volumes) or Cloud Backup (other types). Disable skips volume data and restores YAML only.
Selected
On the Application Backup page, go to the Backup Records tab. The Status column of the backup task shows Completed, which indicates that the backup was successful.
(Optional) Step 2: View the JSON files of backed-up resources in the OSS console
The JSON files of backed-up resources contain information about all backed-up resources, including the resource names, types, sizes, and creation dates. Check these files to verify that the backup includes the resources you want to restore. The following procedure uses the backup vault created in Prerequisites as an example to describe how to view the JSON files of backed-up resources in the Object Storage Service (OSS) console.
Log on to the OSS console.
In the left-side navigation pane, click Buckets, and then click the target bucket
cnfs-oss-test.In the left-side navigation pane, choose Object Management > Objects.
Navigate to the
/subpath/backups/<backupName>/path, find the compressed package named<backupName>.tar.gz, and then download and decompress the package to view the JSON files of all backed-up resources. Confirm that the extracted files include the resources you plan to restore.
Step 3: Initialize the backup vault in the restore cluster
Before you restore the application, initialize the backup vault in the restore cluster so that the cluster can access the backup data. Use the following backuplocation.yaml example to initialize the backup vault.
If the backup vault is already initialized, skip this step.
apiVersion: csdr.alibabacloud.com/v1beta1
kind: BackupLocation
metadata:
name: <backupVaultName>
namespace: csdr
spec:
backupSyncPeriod: 0s
# The following configuration must match the one used when the backup vault was created. You can also initialize the backup vault in the restore cluster console.
config:
network: internal
region: <ossBucketRegion>
objectStorage:
bucket: <ossBucketName>
prefix: <ossBucketSubpath>
provider: alibabacloudStep 4: Define a custom resource modification policy in the restore cluster
A custom resource modification policy consists of two parts: conditions, which specifies the resources to modify, and patches, which specifies the fields and modification methods. In this example, the policy modifies both StatefulSet and Pod resources: it removes the node affinity configuration and changes the volume mount path in the container to /data.
Create a file named
resourcemodifier.yamlin the restore cluster with the following content:apiVersion: v1 data: modifier: | version: v1 resourceModifierRules: - conditions: groupResource: statefulsets.apps namespaces: - default labelSelector: matchLabels: app: nginx patches: - operation: remove path: "/spec/template/spec/affinity/nodeAffinity" - operation: replace path: "/spec/template/spec/containers/0/volumeMounts/0/mountPath" value: "/data" - conditions: groupResource: pods resourceNameRegex: "^web.*$" namespaces: - default labelSelector: matchLabels: app: nginx patches: - operation: remove path: "/spec/affinity" - operation: replace path: "/spec/containers/0/volumeMounts/0/mountPath" value: "/data" kind: ConfigMap metadata: name: <backupName>-resource-modifier namespace: csdrRun the following command to create the ConfigMap in the restore cluster:
kubectl apply -f resourcemodifier.yamlRun the following command to confirm that the ConfigMap exists in the restore cluster:
kubectl -n csdr get configmap <backupName>-resource-modifierThe following table describes the conditions field:
Field | Description | Required | Example |
| The Kubernetes resource group. Custom resource types defined by a CustomResourceDefinition (CRD) are supported. Format: | Yes |
|
| The namespace of the resources to modify. If this field is left empty, the modification applies to resources in all namespaces. If namespace mapping is enabled, the original namespace applies. | No |
|
| The Kubernetes objects to modify. This field supports | No |
|
| The regular expression that resource names must match. If this field is specified, the modification applies only to resources whose names match the expression. | No |
|
The following table describes the patches field:
Field | Description | Required | Example |
operation | The modification operation, such as | Yes |
|
path | The path of the field to modify. | Yes |
|
value | The new value after the modification. This field is supported only for | No |
|
Step 5: Restore the modified application in the restore cluster
Create a restore task in the restore cluster to restore the modified application. The task includes the Step 4 defined in the previous step, and uses the namespaceMapping and imageRegistryMapping fields to configure mappings for namespaces and image registry addresses. Both fields use the Map format.
Create a restore task file named
applicationrestore.yamlbased on the following example. In this example, resources (including volume data) backed up in thedefaultnamespace are restored to thedefault1namespace. The OpenAnolis community image registry address is changed to a Container Registry (ACR) image registry address. Make sure that images are synchronized between the two registries before you change the registry address.apiVersion: csdr.alibabacloud.com/v1beta1 kind: ApplicationRestore metadata: name: <restoreName> namespace: csdr spec: backupName: <backupName> namespaceMapping: default: default1 # Restore to the default1 namespace. imageRegistryMapping: anolis-registry.cn-zhangjiakou.cr.aliyuncs.com/openanolis: registry.cn-beijing.aliyuncs.com/<acrRegistry> # Make sure that images are synchronized between the two registries before the change. resourceModifier: kind: ConfigMap name: <backupName>-resource-modifierRun the following command in the restore cluster to deploy the
ApplicationRestoretask:kubectl apply -f applicationrestore.yamlRun the following command to check the status of the restore task:
kubectl -n csdr get applicationrestore <restoreName> --watchExpected output:
NAME PHASE AGE
<restoreName> Completed 18hThe status of the restore task can also be checked in the console. For more information, see Restore applications and volumes.
Step 6: Verify that the application is restored as expected
Run the following command to retrieve the configuration of the restored StatefulSet:
kubectl -n default1 get sts web -oyamlExpected output:
apiVersion: apps/v1
kind: StatefulSet
metadata:
annotations:
kubectl.kubernetes.io/last-applied-configuration: |
{"apiVersion":"apps/v1","kind":"StatefulSet","metadata":{"annotations":{},"labels":{"app":"nginx"},"name":"web","namespace":"default"},"spec":{"replicas":2,"selector":{"matchLabels":{"app":"nginx"}},"serviceName":"nginx","template":{"metadata":{"labels":{"app":"nginx"}},"spec":{"affinity":{"nodeAffinity":{"preferredDuringSchedulingIgnoredDuringExecution":[{"preference":{"matchExpressions":[{"key":"node-role.kubernetes.io/master","operator":"Exists"}]},"weight":1}]}},"containers":[{"image":"anolis-registry.cn-zhangjiakou.cr.aliyuncs.com/openanolis/nginx:1.14.2","imagePullPolicy":"IfNotPresent","name":"nginx","ports":[{"containerPort":80,"name":"web","protocol":"TCP"}],"terminationMessagePath":"/dev/termination-log","terminationMessagePolicy":"File","volumeMounts":[{"mountPath":"/usr/share/nginx/html/","name":"www"}]}]}},"volumeClaimTemplates":[{"apiVersion":"v1","kind":"PersistentVolumeClaim","metadata":{"labels":{"app":"nginx"},"name":"www"},"spec":{"accessModes":["ReadWriteOnce"],"resources":{"requests":{"storage":"20Gi"}},"storageClassName":"alicloud-disk-topology-alltype","volumeMode":"Filesystem"}}]}}
creationTimestamp: "2024-10-09T08:32:50Z"
generation: 1
labels:
app: nginx
velero.io/backup-name: <backupName>
velero.io/restore-name: <restoreName>
name: web
namespace: default1
resourceVersion: "119622"
uid: d23878ea-0b9f-40ba-b61b-1ff6bb77eb43
spec:
persistentVolumeClaimRetentionPolicy:
whenDeleted: Retain
whenScaled: Retain
podManagementPolicy: OrderedReady
replicas: 2
revisionHistoryLimit: 10
selector:
matchLabels:
app: nginx
serviceName: nginx
template:
metadata:
creationTimestamp: null
labels:
app: nginx
spec:
affinity: {}
containers:
- image: registry.cn-beijing.aliyuncs.com/<acrRegistry>/nginx:1.14.1-8.6
imagePullPolicy: IfNotPresent
name: nginx
ports:
- containerPort: 80
name: web
protocol: TCP
resources: {}
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
volumeMounts:
- mountPath: /data
name: www
dnsPolicy: ClusterFirst
restartPolicy: Always
schedulerName: default-scheduler
securityContext: {}
terminationGracePeriodSeconds: 30
updateStrategy:
rollingUpdate:
partition: 0
type: RollingUpdate
volumeClaimTemplates:
- apiVersion: v1
kind: PersistentVolumeClaim
metadata:
creationTimestamp: null
labels:
app: nginx
name: www
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 20Gi
storageClassName: alicloud-disk-topology-alltype
volumeMode: Filesystem
status:
phase: Pending
status:
availableReplicas: 0
collisionCount: 0
currentRevision: web-7b454646b4
observedGeneration: 1
replicas: 2
updateRevision: web-7b454646b4In the expected output, the container image registry address, the mount path in the container, and the namespace have all been adjusted as specified. The node affinity configuration has been removed. Some new fields in the YAML output are automatically populated by Kubernetes.
The kubectl.kubernetes.io/last-applied-configuration annotation retains the original configuration from before the restore, so the values inside it can differ from the modified live specification.