OSS replication automatically copies objects from a source bucket to a destination bucket. Use it to implement geo-disaster recovery, data residency compliance, or cross-environment data isolation.
Quick start
The minimal end-to-end flow:
-
Set environment variables and initialize a
bucket object — see Common setup. -
(Optional) Call
get_bucket_replication_location to confirm your target region is supported. -
Call
put_bucket_replication to create a replication rule. -
Call
get_bucket_replication to retrieve the assigned rule ID. -
Call
get_bucket_replication_progress to monitor replication. -
Call
delete_bucket_replication when the rule is no longer needed.
Choose a replication mode
| Use case | CRR | SRR |
|---|---|---|
| Protect against regional outages with geo-disaster recovery | Yes | No |
| Keep data in a specific region for compliance (data residency) | Yes | No |
| Reduce read latency for users in remote regions | Yes | No |
| Aggregate logs from multiple buckets into one | No | Yes |
| Isolate production and test environments | No | Yes |
| Add account-level redundancy within a region | No | Yes |
After choosing a mode, set
How it works
OSS replication works as follows:
-
Asynchronous replication — OSS replicates objects asynchronously after writes complete on the source bucket. There is no guaranteed replication latency; actual latency depends on object size and cross-region network distance.
-
Historical data — By default, OSS replicates existing objects in addition to new writes. Set
is_enable_historical_object_replication toFalse to replicate only objects written after the rule is created. -
Incremental data — OSS continuously replicates new writes after the rule is active.
-
Delete operations — Delete operations on the source bucket are replicated to the destination. If you delete an object in the source bucket, OSS removes the corresponding object in the destination bucket.
-
Encryption support — SSE-KMS-encrypted objects can be replicated with an authorized RAM role and a destination KMS key.
API overview
| Method | Description | Required permission |
|---|---|---|
|
|
Create a replication rule |
|
|
|
Query replication rules |
|
|
|
Query available destination regions |
|
|
|
Query replication progress |
|
|
|
Delete a replication rule |
|
Prerequisites
Complete the following steps before using the SDK to manage replication rules.
Required permissions
Grant your RAM (Resource Access Management) user the permissions needed for each operation. For more information, see Attach a custom policy to a RAM user.
| Operation | Required permission |
|---|---|
| Create a replication rule |
|
| Query replication rules |
|
| Query available destination regions |
|
| Query replication progress |
|
| Delete a replication rule |
|
Required bucket configuration
-
Set the
OSS_ACCESS_KEY_ID andOSS_ACCESS_KEY_SECRET environment variables. For more information, see Configure access credentials using OSS SDK for Python 1.0. -
Obtain an OSS endpoint for your bucket's region. For more information, see Regions and endpoints.
-
(Optional) Configure a custom domain name or Security Token Service (STS) credentials. For more information, see Initialization.
The source bucket and destination bucket must have the same versioning state. If the source bucket has versioning enabled, the destination bucket must also have versioning enabled. A mismatch in versioning state prevents the replication rule from functioning correctly.
Common setup
Initialize the
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from oss2.models import ReplicationRule
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
region = "cn-hangzhou"
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)
Replace
Query available destination regions
Before creating a replication rule, call
try:
result = bucket.get_bucket_replication_location()
print("Available destination regions:")
for location in result.location_list:
print(" -", location)
except oss2.exceptions.OssError as e:
print(f"Failed to query destination regions: {e.status} {e.request_id}")
raise
Related API: GetBucketReplicationLocation.
Create a replication rule
Call
The source and destination buckets must have the same versioning state: both unversioned, or both with versioning enabled.
The following example creates a basic replication rule that replicates all objects to a destination bucket:
replica_config = ReplicationRule(
target_bucket_name='destexamplebucket',
target_bucket_location='yourTargetBucketLocation',
)
try:
bucket.put_bucket_replication(replica_config)
print("Replication rule created.")
except oss2.exceptions.OssError as e:
print(f"Failed to create replication rule: {e.status} {e.request_id}")
raise
ReplicationRule parameters
The
ReplicationRule(
target_bucket_name='string', # Required
target_bucket_location='string', # Required
prefix_list=['prefix1', 'prefix2'], # Optional
action_list=[ReplicationRule.PUT], # Optional
is_enable_historical_object_replication=True, # Optional (default: True)
target_transfer_type='oss_acc', # Optional
sync_role_name='string', # Optional
sse_kms_encrypted_objects_status=ReplicationRule.ENABLED, # Optional
replica_kms_keyid='string' # Optional
)
| Parameter | Type | Required | Valid values | Default | Description |
|---|---|---|---|---|---|
|
|
str | Yes | — | — | Name of the destination bucket. |
|
|
str | Yes | — | — | Region of the destination bucket. |
|
|
list | No | Any list of string prefixes | — | Object name prefixes to replicate. Only objects whose names match a listed prefix are replicated. Omit to replicate all objects. Note: tag-based filtering is not supported; prefix filtering only. |
|
|
list | No | — | Operations to replicate. |
|
|
|
bool | No | Whether to replicate pre-existing objects. Set to |
||
|
|
str | No | — | Transfer type. Set to |
|
|
|
str | No | — | — | RAM role name authorized for data replication. Required when replicating SSE-KMS-encrypted objects. |
|
|
str | No | — | Set to |
|
|
|
str | No | — | — | KMS key ID used to encrypt objects at the destination. Required when replicating SSE-KMS-encrypted objects. |
The three SSE-KMS parameters —
Create a rule with filtering and encryption
The following example creates a rule that replicates only objects with specific prefixes and encrypts them at the destination using SSE-KMS:
# Replicate only objects with the specified prefixes.
prefix_list = ['prefix1', 'prefix2']
replica_config = ReplicationRule(
prefix_list=prefix_list,
# Replicate only creates and updates.
action_list=[ReplicationRule.PUT],
target_bucket_name='destexamplebucket',
target_bucket_location='yourTargetBucketLocation',
# Disable historical data replication.
is_enable_historical_object_replication=False,
# Use transfer acceleration.
target_transfer_type='oss_acc',
# Required for SSE-KMS encryption.
sync_role_name='roleNameTest',
sse_kms_encrypted_objects_status=ReplicationRule.ENABLED,
replica_kms_keyid='9468da86-3509-4f8d-a61e-6eab1eac****',
)
try:
bucket.put_bucket_replication(replica_config)
print("Replication rule created with filtering and encryption.")
except oss2.exceptions.OssError as e:
print(f"Failed to create replication rule: {e.status} {e.request_id}")
raise
Verify replication
After creating a replication rule, upload a test object to the source bucket and confirm it appears in the destination bucket.
Replication is asynchronous. The following example waits 60 seconds and then checks whether the object has appeared in the destination bucket.
import time
# Upload a test object to the source bucket.
bucket.put_object('replication-test.txt', 'This is a replication test.')
# Wait for replication to complete. Replication is asynchronous and may take some time.
time.sleep(60)
# Connect to the destination bucket.
# Replace the endpoint and region with those of the destination bucket.
dest_bucket = oss2.Bucket(auth, '<destination-endpoint>', 'destexamplebucket', region='<destination-region>')
if dest_bucket.object_exists('replication-test.txt'):
print("Replication verified: test object found in destination bucket.")
else:
print("Object not yet replicated. Replication is asynchronous and may take some time.")
Related API: PutBucketReplication.
Query replication rules
Call
try:
result = bucket.get_bucket_replication()
for rule in result.rule_list:
print("Rule ID:", rule.rule_id)
print("Destination bucket:", rule.target_bucket_name)
print("Destination region:", rule.target_bucket_location)
except oss2.exceptions.OssError as e:
print(f"Failed to query replication rules: {e.status} {e.request_id}")
raise
Each rule in
| Field | Type | Description |
|---|---|---|
|
|
str | Unique identifier of the replication rule, assigned by OSS at creation time. |
|
|
str | Name of the destination bucket. |
|
|
str | Region of the destination bucket. |
|
|
list | Operations being replicated (for example, |
|
|
list | Object name prefixes being filtered. Present only if set at creation time. |
|
|
str | Current status of the replication rule (for example, |
For the full response schema, see GetBucketReplication.
Related API: GetBucketReplication.
Query replication progress
OSS tracks replication progress in two ways:
-
Historical object replication — A percentage indicating how much of the pre-existing data has been replicated. Available only when
is_enable_historical_object_replication is enabled. -
Incremental replication — A point-in-time marker. All objects written to the source bucket before this timestamp have been replicated. For example, a value of
"2024-01-15T12:00:00.000Z" means all objects created before that time have been replicated.
Pass the rule ID to
try:
# Replace 'test_replication_1' with the rule ID returned by get_bucket_replication().
result = bucket.get_bucket_replication_progress('test_replication_1')
print("Rule ID:", result.progress.rule_id)
print("Historical replication enabled:", result.progress.is_enable_historical_object_replication)
print("Historical replication progress:", result.progress.historical_object_progress)
print("Incremental replication progress:", result.progress.new_object_progress)
except oss2.exceptions.OssError as e:
print(f"Failed to query replication progress: {e.status} {e.request_id}")
raise
The
| Field | Type | Description |
|---|---|---|
|
|
str | Replication rule ID. |
|
|
str | Whether historical object replication is enabled: |
|
|
str | Percentage of historical objects replicated. For example, |
|
|
str | Point-in-time marker for incremental replication. All objects written to the source before this timestamp have been replicated. |
Related API: GetBucketReplicationProgress.
Delete a replication rule
Call
When you delete a replication rule:
-
Objects already replicated to the destination bucket are preserved.
-
Subsequent changes to the source bucket are no longer replicated.
try:
# Replace 'test_replication_1' with the rule ID to delete.
bucket.delete_bucket_replication('test_replication_1')
print("Replication rule deleted successfully.")
except oss2.exceptions.OssError as e:
print(f"Failed to delete replication rule: {e.status} {e.request_id}")
raise
Related API: DeleteBucketReplication.