文件 AWS 開發套件範例 GitHub 儲存庫中有更多可用的 AWS SDK 範例 。
本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
文件 AWS 開發套件範例 GitHub 儲存庫中有更多可用的 AWS SDK 範例 。
本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
GetObjectLockConfiguration
搭配 AWS SDK 或 CLI 使用下列程式碼範例示範如何使用 GetObjectLockConfiguration
。
動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:
.NET
AWS SDK for .NET
public async Task<ObjectLockConfiguration> GetBucketObjectLockConfiguration (string bucketName )
{
try
{
var request = new GetObjectLockConfigurationRequest()
{
BucketName = bucketName
};
var response = await _amazonS3.GetObjectLockConfigurationAsync(request);
Console.WriteLine($"\tBucket object lock config for { bucketName} in { bucketName} : " +
$"\n\tEnabled: { response.ObjectLockConfiguration.ObjectLockEnabled} " +
$"\n\tRule: { response.ObjectLockConfiguration.Rule?.DefaultRetention} " );
return response.ObjectLockConfiguration;
}
catch (AmazonS3Exception ex)
{
Console.WriteLine($"\tUnable to fetch object lock config: ' { ex.Message} '" );
return new ObjectLockConfiguration();
}
}
CLI
AWS CLI
擷取儲存貯體的物件鎖定組態
下列get-object-lock-configuration
範例會擷取指定儲存貯體的物件鎖定組態。
aws s3api get-object-lock-configuration \
--bucket amzn-s3-demo-bucket-with -object -lock
輸出:
{
"ObjectLockConfiguration": {
"ObjectLockEnabled": "Enabled",
"Rule": {
"DefaultRetention": {
"Mode": "COMPLIANCE",
"Days": 50
}
}
}
}
Go
SDK for Go V2
import (
"bytes"
"context"
"errors"
"fmt"
"log"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/aws/smithy-go"
)
type S3Actions struct {
S3Client *s3.Client
S3Manager *manager.Uploader
}
func (actor S3Actions) GetObjectLockConfiguration (ctx context.Context, bucket string ) (*types.ObjectLockConfiguration, error) {
var lockConfig *types.ObjectLockConfiguration
input := &s3.GetObjectLockConfigurationInput{
Bucket: aws.String(bucket),
}
output, err := actor.S3Client.GetObjectLockConfiguration(ctx, input)
if err != nil {
var noBucket *types.NoSuchBucket
var apiErr *smithy.GenericAPIError
if errors.As(err, &noBucket) {
log.Printf("Bucket %s does not exist.\n" , bucket)
err = noBucket
} else if errors.As(err, &apiErr) && apiErr.ErrorCode() == "ObjectLockConfigurationNotFoundError" {
log.Printf("Bucket %s does not have an object lock configuration.\n" , bucket)
err = nil
}
} else {
lockConfig = output.ObjectLockConfiguration
}
return lockConfig, err
}
Java
SDK for Java 2.x
public void getBucketObjectLockConfiguration (String bucketName) {
GetObjectLockConfigurationRequest objectLockConfigurationRequest = GetObjectLockConfigurationRequest.builder()
.bucket(bucketName)
.build();
GetObjectLockConfigurationResponse response = getClient().getObjectLockConfiguration(objectLockConfigurationRequest);
System.out.println("Bucket object lock config for " +bucketName +": " );
System.out.println("\tEnabled: " +response.objectLockConfiguration().objectLockEnabled());
System.out.println("\tRule: " + response.objectLockConfiguration().rule().defaultRetention());
}
JavaScript
SDK for JavaScript (v3)
import {
GetObjectLockConfigurationCommand,
S3Client,
S3ServiceException,
} from "@aws-sdk/client-s3" ;
export const main = async ({ bucketName }) => {
const client = new S3Client({ });
try {
const { ObjectLockConfiguration } = await client.send(
new GetObjectLockConfigurationCommand({
Bucket : bucketName,
}),
);
console .log(
`Object Lock Configuration:\n$ { JSON .stringify(ObjectLockConfiguration)} ` ,
);
} catch (caught) {
if (
caught instanceof S3ServiceException &&
caught.name === "NoSuchBucket"
) {
console .error(
`Error from S3 while getting object lock configuration for $ { bucketName} . The bucket doesn't exist.` ,
);
} else if (caught instanceof S3ServiceException) {
console .error(
`Error from S3 while getting object lock configuration for $ { bucketName} . $ { caught.name} : $ { caught.message} ` ,
);
} else {
throw caught;
}
}
};
import { parseArgs } from "node:util" ;
import {
isMain,
validateArgs,
} from "@aws-doc-sdk-examples/lib/utils/util-node.js" ;
const loadArgs = () => {
const options = {
bucketName : {
type : "string" ,
required : true ,
},
};
const results = parseArgs({ options });
const { errors } = validateArgs({ options }, results);
return { errors, results };
};
if (isMain(import .meta.url)) {
const { errors, results } = loadArgs();
if (!errors) {
main(results.values);
} else {
console .error(errors.join("\n" ));
}
}
PowerShell
Tools for PowerShell
範例 1:如果為指定的 S3 儲存貯體啟用物件鎖定組態,此命令會傳回值 'Enabled'。
Get-S3ObjectLockConfiguration -BucketName 'amzn-s3-demo-bucket' -Select ObjectLockConfiguration.ObjectLockEnabled
輸出:
Value
-----
Enabled
Python
SDK for Python (Boto3)
取得物件鎖定組態。
def is_object_lock_enabled (s3_client, bucket: str ) -> bool :
"""
Check if object lock is enabled for a bucket.
Args:
s3_client: Boto3 S3 client.
bucket: The name of the bucket to check.
Returns:
True if object lock is enabled, False otherwise.
"""
try :
response = s3_client.get_object_lock_configuration(Bucket=bucket)
return (
"ObjectLockConfiguration" in response
and response["ObjectLockConfiguration" ]["ObjectLockEnabled" ] == "Enabled"
)
except s3_client.exceptions.ClientError as e:
if e.response["Error" ]["Code" ] == "ObjectLockConfigurationNotFoundError" :
return False
else :
raise