All Products
Search
Document Center

Object Storage Service:Copy data from a bucket in a region within an account to another bucket in another region within another account

Last Updated:Jun 05, 2025

You can use cross-region replication (CRR) across accounts to replicate Object Storage Service (OSS) objects from a bucket in a region within Alibaba Cloud account A to another bucket in another region within Alibaba Cloud account B.

Prerequisites

  • Bucket A, which works as the source bucket of a CRR task, is created in a region within Account A. Record the UID of Account A, the name of Bucket A, and the region in which Bucket A is located.

  • Account A must have the following permissions: oss:PutBucketReplication, oss:GetBucketReplication, oss:DeleteBucketReplication, oss:GetBucketReplicationLocation, and oss:GetBucketReplicationProgress. For more information, see Grant custom permissions to a RAM user.

  • Bucket B, which works as the destination bucket of the CRR task, is created in another region within Account B. Record the UID of Account B, the name of Bucket B, and the region in which Bucket B is located.

Role authorization

Two buckets that belong to different Alibaba Cloud accounts are required for data replication across accounts. The following items describe the trust policy and minimum permissions required by the RAM role for data replication across accounts:

  1. Use Account A to perform the following operations:

    1. Create a service role.

      Important

      You can use a RAM user to create a role. The RAM user must have the following permissions: ram:CreateRole, ram:GetRole, ram:ListRoles, ram:ListPoliciesForRole, and ram:AttachPolicyToRole. However, granting a RAM user permissions such as ram:CreateRole and ram:GetRole poses high risks. You can use the Alibaba Cloud account associated with the RAM user to create a RAM role and grant permissions to the RAM role. Then, the RAM user can assume the RAM role that is created by the Alibaba Cloud account.

      When you create a role, select Alibaba Cloud Service for Trusted entity type and Object Storage Service for Select trusted service. For more information, see Create a service role.

      Note

      After the role is created, record the RAM role ARN in the Basic Information section for subsequent permission granting.

    2. Grant the RAM role the permissions to perform CRR on the source bucket.

      You can use one of the following methods to grant permissions to the RAM role:

      Grant a system policy to the RAM role

      Warning

      You can grant the AliyunOSSFullAccess system policy to the RAM role. AliyunOSSFullAccess grants permissions to perform all operations on all buckets in the current account. Exercise caution when you use this policy.

      Grant a custom policy to the RAM role

      You can use a RAM policy to grant the RAM role the minimum permissions required to perform CRR on the source bucket (src-bucket).

      Note

      Replace src-bucket with the name of the source bucket based on your business requirements.

      {
         "Version":"1",
         "Statement":[
            {
               "Effect":"Allow",
               "Action":[
                  "oss:ReplicateList",
                  "oss:ReplicateGet"
               ],
               "Resource":[
                  "acs:oss:*:*:src-bucket",          	
                  "acs:oss:*:*:src-bucket/*"
               ]
            }
         ]
      }

      If you want to replicate objects encrypted based on KMS from the source bucket to the destination bucket, you must also grant the AliyunKMSFullAccess system policy to the role. For more information, see Grant permissions to a RAM role.

  2. Use Account B to grant the RAM role the permissions to receive the objects that you want to replicate to the destination bucket.

    (Recommended) Method 1: Add a policy by using the graphical editor

    1. Log on to the OSS console.

    2. In the left-side navigation pane, click Buckets, and then click the name of the destination bucket dest-bucket.

    3. In the left-side navigation pane, choose Permission Control > Bucket Policy.

    4. On the Bucket Policy page, click the Add in GUI tab, and then click Receive Objects to Replicate.

    5. In the Receive Objects to Replicate panel, select Obtain From Source Replication RAM Role ARN for Obtain UID and RAM Role From, select the ARN of the role created in Step 1 for Source RAM Role ARN for Replication, and select CRR Across Accounts for Authorization Purpose.

    6. Click Generate Policy.

    Method 2: Add a policy by specifying policy statements

    1. In the left-side navigation pane, choose Permission Control > Bucket Policy.

    2. On the Bucket Policy page, click the Add by Syntax tab, and then click Edit.

    3. In the code editor, enter the following bucket policy.

      Important
      • If you configure a bucket policy by specifying policy statements to grant the RAM role the required permissions, the new bucket policy overwrites the existing bucket policy. Make sure that the new bucket policy contains the content of the existing bucket policy. Otherwise, the authorization of the existing bucket policy may fail.

      • Replace the custom role name (If the custom role name contains uppercase letters, you must convert the uppercase letters to lowercase letters. For example, if the created role name is AliyunOssDrsRole, you need to convert AliyunOssDrsRole to aliyunossdrsrole), the name of the destination bucket (dest-bucket), the UID of the account to which the source bucket belongs (137918634953xxxx), and the UID of the account to which the destination bucket belongs (111933544165xxxx).

      {
         "Version":"1",
         "Statement":[
            {
              "Effect":"Allow",
              "Action":[
                  "oss:ReplicateList",
                  "oss:ReplicateGet",
                  "oss:ReplicatePut",
                  "oss:ReplicateDelete"			
               ],
              "Principal": [
                  "arn:sts::137918634953xxxx:assumed-role/aliyunossdrsrole/*"		 
      		 ],
               "Resource":[
                  "acs:oss:*:111933544165xxxx:dest-bucket",          	
                  "acs:oss:*:111933544165xxxx:dest-bucket/*"
               ]
            }
         ]
      }
    4. Click Save.

Replicate objects encrypted based on KMS

Note

Objects encrypted by using SSE-KMS can be replicated to buckets in the following regions: China (Hangzhou), China (Shanghai), China (Shenzhen), China (Heyuan), China (Guangzhou), China (Qingdao), China (Beijing), China (Zhangjiakou), China (Hohhot), China (Ulanqab), China (Chengdu), China East 2 Finance, China (Hong Kong), Singapore, Malaysia (Kuala Lumpur), Indonesia (Jakarta), Philippines (Manila), Thailand (Bangkok), Japan (Tokyo), US (Silicon Valley), US (Virginia), Germany (Frankfurt), and UK (London).

If you want to copy objects encrypted by using SSE-KMS from a source bucket that belongs to Account A to a destination bucket that belongs to Account B, use Account B to perform the following steps:

  1. Log on to the Instance Management page of the Key Management Service console. Purchase and enable a KMS instance in the same region as the destination bucket. When you purchase a KMS instance, make sure that Number Of Access Control is set to a value greater than or equal to 2. Retain the default values for other parameters. For more information, see Purchase and enable a KMS instance.

  2. Create a key in the KMS instance. The key type cannot be Default. We recommend that you use software keys. For more information, see Create a software key.

    Note

    After the key is created, record the key ARN in the Basic Information section for subsequent creation of replication rules.

  3. Configure a policy for the key. When you configure a key policy, select Other Account Users and specify the ARN of the role created in the preceding steps for Other Account Users. For more information, see Configure a key policy.

    Important

    To replicate encrypted data across accounts, the key policy must include at least the decryption (kms:Decrypt) and data key generation (kms:GenerateDataKey) permissions. When you configure a key policy in the KMS console, the preceding permissions are added by default. If you configure a custom key policy by using OpenAPI, make sure that the policy includes at least the kms:Decrypt and kms:GenerateDataKey permissions.

Procedure

Use the OSS console

Create a CRR rule for the source bucket by using Account A.

  1. Log on to the OSS console.

  2. Click Buckets, and then click the name of the source bucket.

  3. In the left-side navigation pane, choose Data Management > CRR.

  4. On the CRR tab, click CRR.

  5. In the CRR dialog box, configure the following parameters.

    Section

    Parameter

    Description

    Configure Destination Bucket

    Source Region

    The region and name of the source bucket are displayed.

    Destination Bucket

    Select Specify A Bucket In Another Account, select the region in which the destination bucket is located from the drop-down list, and then manually enter the name of the destination bucket.

    Configure Replication Policy

    Objects to Replicate

    Select the objects that you want to replicate to the destination bucket.

    • Synchronize all files: All objects in the bucket are replicated to the destination bucket.

    • Files With Specified Prefixes: Objects whose names contain the specified prefixes are replicated to the destination bucket. You can specify up to 10 prefixes by default. If you want to increase the number of prefixes, contact technical support to submit a ticket. You can specify up to 30 prefixes.

    Replication Policy

    Configure the operations that you want to replicate from the source bucket to the destination bucket. Valid values:

    Note

    After you create a data replication rule, changes to the x-oss-last-access-time attribute of the objects and the storage class conversion of objects in the source bucket due to lifecycle rules or the CopyObject operation are not synchronized to the destination bucket.

    • Add/Change (applicable to disaster recovery): OSS replicates only object creation and update operations from the source bucket to the destination bucket.

      Important

      If this replication policy is applied, only objects that are uploaded or updated after the policy takes effect will be replicated to the destination bucket, and objects deleted from the source bucket will not be deleted from the destination bucket. This policy effectively prevents data loss in the destination bucket resulting from manual deletion or automated deletion triggered by lifecycle policies in the source bucket.

    • Add/Delete/Change (applicable to scenarios in which multiple users or applications need to share and access the same dataset): OSS replicates object creation, update, and deletion operations from the source bucket to the destination bucket.

      Important

      Besides replication of newly uploaded and updated objects, this replication policy includes replication of deletion, which ensures the consistency of data. This policy is applicable to scenarios in which multiple users or applications need to share and access the same dataset. Objects deleted from the source bucket, either manually or through lifecycle policies, will also be deleted from the destination bucket. Objects cannot be recovered after they are deleted.

    If you use multipart upload to upload an object to the source bucket, each uploaded part is replicated to the destination bucket. After you call CompleteMultipartUpload to complete the multipart upload task, the object is also replicated to the destination bucket.

    For more information about the replication behavior when CRR is used together with versioning, see Data replication with versioning.

    Replicate Historical Data

    Specifies whether to replicate historical data (data that exists in the source bucket before you enable CRR) to the destination bucket.

    • Enable: Historical data is replicated to the destination bucket.

      Important

      When historical data is replicated, objects that are replicated from the source bucket may overwrite objects that have the same names in the destination bucket. To prevent data loss, we recommend that you enable versioning for the source and destination buckets.

    • Disable: Only objects that are uploaded or updated after the CRR rule is created are replicated.

    Replicate Objects Encrypted Based On KMS

    Specify whether to replicate objects encrypted based on KMS from the source bucket to the destination bucket. Valid values:

    • Yes: Objects encrypted by using SSE-KMS (CMK ID specified) in the source bucket or objects in the destination bucket that are encrypted by using SSE-KMS are replicated to the destination bucket. If you set Replicate Objects Encrypted Based on KMS to Yes, you must specify the CMK ID parameter.

      Note

      You can call HeadObject and GetBucketEncryption to query the encryption status of the source object and the destination bucket.

    • No: Objects encrypted based on KMS are not replicated to the destination bucket.

    KMS Key

    Specify the ARN of the KMS key. For information about how to obtain the ARN of a KMS key, see Create a software key in a KMS instance.

    RAM Role

    Select the role created in Step 1 from the drop-down list.

    Acceleration Type

    The Transfer Acceleration option is available for Transfer Type only when the source and destination buckets are located in regions inside and outside the Chinese mainland.

    If you enable transfer acceleration, you are charged transfer acceleration fees. For more information about the billing methods, see Transfer acceleration fees.

    Replication Time Control (RTC)

    Note
    • RTC is available in the following regions: China (Hangzhou), China (Shanghai), China (Qingdao), China (Beijing), China (Zhangjiakou), and China (Shenzhen).

    • RTC is available in the following regions: US (Silicon Valley) and US (Virginia).

    After Replication Time Control (RTC) is enabled, OSS replicates most of the objects that you uploaded to OSS within a few seconds and replicates 99.99% of the objects within 10 minutes. For more information about RTC, see Use replication time control (RTC). You are charged when you enable RTC. For more information, see RTC fees for CRR.

  6. Click OK, and then click Enable in the dialog box that appears.

    • After you create a CRR rule, the rule cannot be modified or deleted.

    • After you configure a CRR rule, the replication task starts in 3 to 5 minutes. You can view the progress of the replication task on the CRR tab of the source bucket.

    • In CRR, data is asynchronously replicated. Depending on the amount of data, the time that is required to replicate data from the source bucket to the destination bucket may range from a few minutes to a few hours.

Use Alibaba Cloud SDK

CRR across accounts is supported only by using OSS SDK for Java, OSS SDK for Python, and OSS SDK for Go.

Java

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.AddBucketReplicationRequest;

public class Demo {

    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Specify the ID of the Alibaba Cloud region in which the bucket is located. Example: cn-hangzhou.
        String region = "cn-hangzhou";
        // We recommend that you do not save access credentials in the project code. Otherwise, access credentials may be leaked, which compromises the security of all resources in your account. In this example, access credentials are obtained from environment variables. Before you run the sample code, make sure that the environment variables are configured.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the source bucket. Example: src-bucket.
        String bucketName = "src-bucket";
        // Specify the destination bucket to which you want to replicate the data. The source and destination buckets must belong to different Alibaba Cloud accounts.
        String targetBucketName = "dest-bucket";
        // Specify the region in which the destination bucket is located. The destination bucket and the source bucket must be located in different regions.
        String targetBucketLocation = "oss-cn-shanghai";
        
        // Create an OSSClient instance.
        // When you are done with the OSSClient instance, call the shutdown method to release the resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        // Explicitly declare the use of the V4 signature algorithm
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            AddBucketReplicationRequest request = new AddBucketReplicationRequest(bucketName);
            request.setTargetBucketName(targetBucketName);
            request.setTargetBucketLocation(targetBucketLocation);
            // By default, historical data is replicated. In this example, this parameter is set to false, which indicates that historical data is not replicated.
            request.setEnableHistoricalObjectReplication(false);
            // Specify the name of the role that you want OSS to use to replicate data. The role must have the permissions to perform CRR on the source bucket and receive replicated objects in the destination bucket.
            request.setSyncRole("yourRole");           
            //List prefixes = new ArrayList();
            //prefixes.add("image/");
            //prefixes.add("video");
            //prefixes.add("a");
            //prefixes.add("A");
            // Specify the prefixes that are contained in the names of the objects that you want to replicate. After you specify the prefixes, only objects whose names contain the prefixes are replicated to the destination bucket.
            //request.setObjectPrefixList(prefixes);
            //List actions = new ArrayList();
            //actions.add(AddBucketReplicationRequest.ReplicationAction.PUT);
            // Specify that OSS replicates object creation and update operations from the source bucket to the destination bucket.
            //request.setReplicationActionList(actions);
            ossClient.addBucketReplication(request);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}        

Python

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from oss2.models import ReplicationRule
# Obtain access credentials from environment variables. Before you execute the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
# Specify the endpoint of the region in which the source bucket is located. For example, if the bucket resides in the China (Hangzhou) region, set this parameter to https://oss-cn-hangzhou.aliyuncs.com.
# Specify the name of the source bucket. Example: src-bucket.
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'src-bucket')
replica_config = ReplicationRule(
    # Specify the destination bucket to which data is replicated. The source and destination buckets must belong to different Alibaba Cloud accounts.
    target_bucket_name='dest-bucket',
    # Specify the region in which the destination bucket is located. The destination bucket and the source bucket must be located in different regions.
    target_bucket_location='oss-cn-shanghai',
    # Specify the name of the role that you want to authorize OSS to use to replicate data. The role must have the permissions to perform CRR on the source bucket and receive replicated objects in the destination bucket.
    sync_role_name='roleNameTest',
)

# Specify the prefix that is contained in the names of the objects that you want to replicate. After you specify the prefix, only objects whose names contain the specified prefix are replicated to the destination bucket.
# prefix_list = ['prefix1', 'prefix2']
# Configure the data replication rule.
# replica_config = ReplicationRule(
     # prefix_list=prefix_list,
     # Specify that OSS replicates object creation and update operations from the source bucket to the destination bucket.
     # action_list=[ReplicationRule.P],
     # Specify the destination bucket to which data is replicated. The source and destination buckets must belong to different Alibaba Cloud accounts.
     # target_bucket_name='dest-bucket',
     # Specify the region in which the destination bucket is located. The destination bucket and the source bucket must be located in different regions.
     # target_bucket_location='yourTargetBucketLocation',
     # By default, historical data is replicated. In this example, this parameter is set to False, which indicates that historical data is not replicated.
     # is_enable_historical_object_replication=False,
     # Specify the link that is used to transfer data during data replication.
     # target_transfer_type='oss_acc',    
  #)

# Enable data replication.
bucket.put_bucket_replication(replica_config)

Go

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // Region in which the bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	var (
		targetBucket   = "target bucket name" // Name of the destination bucket.
		targetLocation = "oss-cn-beijing"     // Region in which the destination bucket is located.
	)

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to enable data replication for the bucket.
	request := &oss.PutBucketReplicationRequest{
		Bucket: oss.Ptr(bucketName), // Name of the bucket.
		ReplicationConfiguration: &oss.ReplicationConfiguration{
			Rules: []oss.ReplicationRule{
				{
					RTC: &oss.ReplicationTimeControl{
						Status: oss.Ptr("enabled"), // Enable the RTC feature.
					},
					Destination: &oss.ReplicationDestination{
						Bucket:       oss.Ptr(targetBucket),   // Name of the destination bucket.
						Location:     oss.Ptr(targetLocation), // Region in which the destination bucket is located.
						TransferType: oss.TransferTypeOssAcc,  // Type of transfer.
					},
					HistoricalObjectReplication: oss.HistoricalObjectReplicationEnabled, // Enable the historical data replication feature.
				},
			},
		},
	}

	// Enable data replication.
	result, err := client.PutBucketReplication(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put bucket replication %v", err)
	}

	// Display the result.
	log.Printf("put bucket replication result:%#v\n", result)
}

Use ossutil

For more information about how to enable CRR across accounts by using ossutil, see put-bucket-replication.

Use REST API

If your business requires a high level of customization, you can directly call the OSS API. To directly call an API, you must include the signature calculation in your code. For more information, see PutBucketReplication.

References