The following code provides examples of how to configure a retention policy by using common SDKs. For information about how to configure a retention policy by using other SDKs, see Introduction to SDKs.
Java
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.InitiateBucketWormRequest;
import com.aliyun.oss.model.InitiateBucketWormResult;
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";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Create an InitiateBucketWormRequest object.
InitiateBucketWormRequest initiateBucketWormRequest = new InitiateBucketWormRequest(bucketName);
// Set the retention period to 1 day.
initiateBucketWormRequest.setRetentionPeriodInDays(1);
// Create a retention policy.
InitiateBucketWormResult initiateBucketWormResult = ossClient.initiateBucketWorm(initiateBucketWormRequest);
// Display the ID of the retention policy.
String wormId = initiateBucketWormResult.getWormId();
System.out.println(wormId);
} 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();
}
}
}
}
PHP
<?php
// Import the autoloader file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Define command line argument descriptions.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located', 'required' => True], // Required. The region where the bucket is located.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS', 'required' => False], // Optional. The domain name that other services can use to access OSS.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // Required. The name of the bucket.
];
// Generate a long options list to parse command line arguments.
$longopts = \array_map(function ($key) {
return "$key:"; // Add a colon after each argument to indicate that a value is required.
}, array_keys($optsdesc));
// Parse the command line arguments.
$options = getopt("", $longopts);
// Check if any required arguments are missing.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help"; // Prompt the user that a required argument is missing.
exit(1);
}
}
// Get the command line argument values.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
// Load credential information, such as AccessKey ID and AccessKey secret, from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configurations of the software development kit (SDK).
$cfg = Oss\Config::loadDefault();
// Set the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);
// Set the region.
$cfg->setRegion($region);
// If an endpoint is provided, set the endpoint.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSS client instance.
$client = new Oss\Client($cfg);
// Create a request object to initialize the retention policy for the bucket. Set the retention period to 3 days.
$request = new Oss\Models\InitiateBucketWormRequest(
bucket: $bucket,
initiateWormConfiguration: new Oss\Models\InitiateWormConfiguration(
retentionPeriodInDays: 3 // The retention period in days.
));
// Call the initiateBucketWorm method to initialize the retention policy for the bucket.
$result = $client->initiateBucketWorm($request);
// Print the returned result.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code.
'request id:' . $result->requestId . PHP_EOL . // The unique ID of the request.
'worm id:' . $result->wormId // The ID of the retention policy.
);
Node.js
const OSS = require('ali-oss');
const client = new OSS({
// Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to oss-cn-hangzhou.
region: 'yourregion',
// Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Set bucket to your bucket name.
bucket: 'yourBucketName',
});
// Create a data retention policy.
async function initiateBucketWorm() {
// Set bucket to your bucket name.
const bucket = 'yourbucketname'
// Specify the retention period in days.
const days = '<Retention Days>'
const res = await client.initiateBucketWorm(bucket, days)
console.log(res.wormId)
}
initiateBucketWorm()
Python
import argparse
import alibabacloud_oss_v2 as oss
# Create a command-line argument parser and describe the script's purpose: This sample shows how to initialize the WORM configuration for an OSS bucket.
parser = argparse.ArgumentParser(description="initiate bucket worm sample")
# Add the --region command-line argument, which specifies the bucket region. This argument is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Add the --bucket command-line argument, which specifies the bucket name. This argument is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Add the --endpoint command-line argument, which specifies the domain name that other services can use to access OSS. This argument is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Add the --retention_period_in_days command-line argument, which specifies the retention period in days. This argument is required.
parser.add_argument('--retention_period_in_days', help='The number of days for which objects can be retained.', required=True)
def main():
# Parse the command-line arguments to get the user-provided values.
args = parser.parse_args()
# Load the access credentials for OSS from environment variables for identity verification.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Create a configuration object using the SDK's default configurations and set the credentials provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
cfg.region = args.region
# If a custom endpoint is provided, update the endpoint property in the configuration object.
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Initialize the OSS client with the configuration to interact with OSS.
client = oss.Client(cfg)
# Send a request to initialize the WORM configuration for the specified bucket.
result = client.initiate_bucket_worm(oss.InitiateBucketWormRequest(
bucket=args.bucket, # Bucket name.
initiate_worm_configuration=oss.InitiateWormConfiguration(
retention_period_in_days=int(args.retention_period_in_days), # Retention period in days, converted to an integer.
),
))
# Print the status code, request ID, and WORM ID of the operation to confirm the request status.
print(f'status code: {result.status_code},'
f' request id: {result.request_id},'
f' worm id: {result.worm_id}'
)
# When this script is run directly, call the main function to start the processing logic.
if __name__ == "__main__":
main() # Script entry point, where the program flow starts.
Go
package main
import (
"log"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
log.Fatalf("Error creating credentials provider: %v", err)
}
// Create an OSSClient instance.
// Set yourEndpoint to the Endpoint of the bucket. For example, for a bucket in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual Endpoint.
// Set yourRegion to the region where the bucket is located. For example, for a bucket in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Set the signature version.
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New("yourEndpoint", "", "", clientOptions...)
if err != nil {
log.Fatalf("Error creating OSS client: %v", err)
}
// Specify the name of the bucket for which you want to configure a retention policy.
bucketName := "<yourBucketName>"
// Set the retention period for objects to 60 days.
result, err := client.InitiateBucketWorm(bucketName, 60)
if err != nil {
log.Fatalf("Error initiating bucket WORM: %v", err)
}
log.Println("WORM policy initiated successfully:", result)
}
C++
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize information about the account that is used to access OSS. */
/* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. */
std::string Region = "yourRegion";
/* Specify the name of the bucket. Example: examplebucket. */
std::string BucketName = "examplebucket";
/* Initialize resources, such as network resources. */
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
/* Create a retention policy and set the retention period to 1 day. */
auto outcome = client.InitiateBucketWorm(InitiateBucketWormRequest(BucketName, 1));
if (outcome.isSuccess()) {
std::cout << " InitiateBucketWorm success " << std::endl;
std::cout << "WormId:" << outcome.result().WormId() << std::endl;
}
else {
/* Handle exceptions. */
std::cout << "InitiateBucketWorm fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
/* Release resources, such as network resources. */
ShutdownSdk();
return 0;
}