Gunakan GetObjectRetention dengan AWS SDK atau CLI - AWS SDKContoh Kode

Ada lebih banyak AWS SDK contoh yang tersedia di GitHub repo SDKContoh AWS Dokumen.

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

Gunakan GetObjectRetention dengan AWS SDK atau CLI

Contoh kode berikut menunjukkan cara menggunakanGetObjectRetention.

Contoh tindakan adalah kutipan kode dari program yang lebih besar dan harus dijalankan dalam konteks. Anda dapat melihat tindakan ini dalam konteks dalam contoh kode berikut:

.NET
AWS SDK for .NET
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

/// <summary> /// Get the retention period for an S3 object. /// </summary> /// <param name="bucketName">The bucket of the object.</param> /// <param name="objectKey">The object key.</param> /// <returns>The object retention details.</returns> public async Task<ObjectLockRetention> GetObjectRetention(string bucketName, string objectKey) { try { var request = new GetObjectRetentionRequest() { BucketName = bucketName, Key = objectKey }; var response = await _amazonS3.GetObjectRetentionAsync(request); Console.WriteLine($"\tObject retention for {objectKey} in {bucketName}: " + $"\n\t{response.Retention.Mode} until {response.Retention.RetainUntilDate:d}."); return response.Retention; } catch (AmazonS3Exception ex) { Console.WriteLine($"\tUnable to fetch object lock retention: '{ex.Message}'"); return new ObjectLockRetention(); } }
CLI
AWS CLI

Untuk mengambil konfigurasi retensi objek untuk objek

get-object-retentionContoh berikut mengambil konfigurasi retensi objek untuk objek tertentu.

aws s3api get-object-retention \ --bucket my-bucket-with-object-lock \ --key doc1.rtf

Output:

{ "Retention": { "Mode": "GOVERNANCE", "RetainUntilDate": "2025-01-01T00:00:00.000Z" } }
Go
SDKuntuk Go V2
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

// S3Actions wraps S3 service actions. type S3Actions struct { S3Client *s3.Client S3Manager *manager.Uploader } // GetObjectRetention retrieves the object retention configuration for an S3 object. func (actor S3Actions) GetObjectRetention(ctx context.Context, bucket string, key string) (*types.ObjectLockRetention, error) { var retention *types.ObjectLockRetention input := &s3.GetObjectRetentionInput{ Bucket: aws.String(bucket), Key: aws.String(key), } output, err := actor.S3Client.GetObjectRetention(ctx, input) if err != nil { var noKey *types.NoSuchKey var apiErr *smithy.GenericAPIError if errors.As(err, &noKey) { log.Printf("Object %s does not exist in bucket %s.\n", key, bucket) err = noKey } else if errors.As(err, &apiErr) { switch apiErr.ErrorCode() { case "NoSuchObjectLockConfiguration": err = nil case "InvalidRequest": log.Printf("Bucket %s does not have locking enabled.", bucket) err = nil } } } else { retention = output.Retention } return retention, err }
Java
SDKuntuk Java 2.x
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

// Get the retention period for an S3 object. public ObjectLockRetention getObjectRetention(String bucketName, String key){ try { GetObjectRetentionRequest retentionRequest = GetObjectRetentionRequest.builder() .bucket(bucketName) .key(key) .build(); GetObjectRetentionResponse response = getClient().getObjectRetention(retentionRequest); System.out.println("tObject retention for "+key +" in "+ bucketName +": " + response.retention().mode() +" until "+ response.retention().retainUntilDate() +"."); return response.retention(); } catch (S3Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); return null; } }
JavaScript
SDKuntuk JavaScript (v3)
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

import { GetObjectRetentionCommand, S3Client, S3ServiceException, } from "@aws-sdk/client-s3"; /** * Log the "RetainUntilDate" for an object in an S3 bucket. * @param {{ bucketName: string, key: string }} */ export const main = async ({ bucketName, key }) => { const client = new S3Client({}); try { const { Retention } = await client.send( new GetObjectRetentionCommand({ Bucket: bucketName, Key: key, }), ); console.log( `${key} in ${bucketName} will be retained until ${Retention.RetainUntilDate}`, ); } catch (caught) { if ( caught instanceof S3ServiceException && caught.name === "NoSuchObjectLockConfiguration" ) { console.warn( `The object "${key}" in the bucket "${bucketName}" does not have an ObjectLock configuration.`, ); } else if (caught instanceof S3ServiceException) { console.error( `Error from S3 while getting object retention settings 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, }, key: { 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
Alat untuk PowerShell

Contoh 1: Perintah mengembalikan mode dan tanggal sampai objek akan dipertahankan.

Get-S3ObjectRetention -BucketName 'amzn-s3-demo-bucket' -Key 'testfile.txt'
  • Untuk API detailnya, lihat GetObjectRetentiondi AWS Tools for PowerShell Referensi Cmdlet.