文件範例儲存庫中有更多 AWS SDK可用的範例。 AWS SDK
本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
GetObjectLockConfiguration
搭配 AWS SDK或 使用 CLI
下列程式碼範例示範如何使用 GetObjectLockConfiguration
。
動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:
- .NET
-
- AWS SDK for .NET
-
注意
還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 /// <summary> /// Get the object lock configuration details for an S3 bucket. /// </summary> /// <param name="bucketName">The bucket to get details.</param> /// <returns>The bucket's object lock configuration details.</returns> 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(); } }
-
如需API詳細資訊,請參閱 參考 GetObjectLockConfiguration中的 。 AWS SDK for .NET API
-
- CLI
-
- AWS CLI
-
擷取儲存貯體的物件鎖定組態
下列
get-object-lock-configuration
範例會擷取指定儲存貯體的物件鎖定組態。aws s3api get-object-lock-configuration \ --bucket
my-bucket-with-object-lock
輸出:
{ "ObjectLockConfiguration": { "ObjectLockEnabled": "Enabled", "Rule": { "DefaultRetention": { "Mode": "COMPLIANCE", "Days": 50 } } } }
-
如需API詳細資訊,請參閱 命令參考 GetObjectLockConfiguration
中的 。 AWS CLI
-
- Go
-
- SDK for Go V2
-
注意
還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 // S3Actions wraps S3 service actions. type S3Actions struct { S3Client *s3.Client S3Manager *manager.Uploader } // GetObjectLockConfiguration retrieves the object lock configuration for an S3 bucket. 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 }
-
如需API詳細資訊,請參閱 參考 GetObjectLockConfiguration
中的 。 AWS SDK for Go API
-
- Java
-
- SDK 適用於 Java 2.x
-
注意
還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 // Get the object lock configuration details for an S3 bucket. 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()); }
-
如需API詳細資訊,請參閱 參考 GetObjectLockConfiguration中的 。 AWS SDK for Java 2.x API
-
- JavaScript
-
- SDK 適用於 JavaScript (v3)
-
注意
還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 import { GetObjectLockConfigurationCommand, S3Client, S3ServiceException, } from "@aws-sdk/client-s3"; /** * Gets the Object Lock configuration for a bucket. * @param {{ bucketName: string }} */ export const main = async ({ bucketName }) => { const client = new S3Client({}); try { const { ObjectLockConfiguration } = await client.send( new GetObjectLockConfigurationCommand({ Bucket: bucketName, // Optionally, you can provide additional parameters // ExpectedBucketOwner: "<account ID that is expected to own the bucket>", }), ); 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; } } }; // Call function if run directly 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")); } }
-
如需API詳細資訊,請參閱 參考 GetObjectLockConfiguration中的 。 AWS SDK for JavaScript API
-
- PowerShell
-
- 適用於 的工具 PowerShell
-
範例 1:如果為指定的 S3 儲存貯體啟用物件鎖定組態,此命令會傳回值 'Enabled'。
Get-S3ObjectLockConfiguration -BucketName 'amzn-s3-demo-bucket' -Select ObjectLockConfiguration.ObjectLockEnabled
輸出:
Value ----- Enabled
-
如需API詳細資訊,請參閱 AWS Tools for PowerShell Cmdlet 參考 GetObjectLockConfiguration中的 。
-
- Python
-
- SDK for Python (Boto3)
-
注意
還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 取得物件鎖定組態。
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
-
如需API詳細資訊,請參閱 GetObjectLockConfiguration 中的 AWS SDK for Python (Boto3) API參考 。
-