Use PutObjectRetention com um AWS SDK ou CLI - AWS SDKExemplos de código

Há mais AWS SDK exemplos disponíveis no GitHub repositório AWS Doc SDK Examples.

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

Use PutObjectRetention com um AWS SDK ou CLI

Os exemplos de código a seguir mostram como usar o PutObjectRetention.

Exemplos de ações são trechos de código de programas maiores e devem ser executados em contexto. É possível ver essa ação no contexto no seguinte exemplo de código:

.NET
AWS SDK for .NET
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

/// <summary> /// Set or modify a retention period on an object in an S3 bucket. /// </summary> /// <param name="bucketName">The bucket of the object.</param> /// <param name="objectKey">The key of the object.</param> /// <param name="retention">The retention mode.</param> /// <param name="retainUntilDate">The date retention expires.</param> /// <returns>True if successful.</returns> public async Task<bool> ModifyObjectRetentionPeriod(string bucketName, string objectKey, ObjectLockRetentionMode retention, DateTime retainUntilDate) { try { var request = new PutObjectRetentionRequest() { BucketName = bucketName, Key = objectKey, Retention = new ObjectLockRetention() { Mode = retention, RetainUntilDate = retainUntilDate } }; var response = await _amazonS3.PutObjectRetentionAsync(request); Console.WriteLine($"\tSet retention for {objectKey} in {bucketName} until {retainUntilDate:d}."); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; } catch (AmazonS3Exception ex) { Console.WriteLine($"\tError modifying retention period: '{ex.Message}'"); return false; } }
CLI
AWS CLI

Como definir uma configuração de retenção de objetos para um objeto

O exemplo de put-object-retention a seguir define uma configuração de retenção de objetos para o objeto especificado até 2025-01-01.

aws s3api put-object-retention \ --bucket my-bucket-with-object-lock \ --key doc1.rtf \ --retention '{ "Mode": "GOVERNANCE", "RetainUntilDate": "2025-01-01T00:00:00" }'

Este comando não produz saída.

Go
SDKpara Go V2
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

// S3Actions wraps S3 service actions. type S3Actions struct { S3Client *s3.Client S3Manager *manager.Uploader } // PutObjectRetention sets the object retention configuration for an S3 object. func (actor S3Actions) PutObjectRetention(ctx context.Context, bucket string, key string, retentionMode types.ObjectLockRetentionMode, retentionPeriodDays int32) error { input := &s3.PutObjectRetentionInput{ Bucket: aws.String(bucket), Key: aws.String(key), Retention: &types.ObjectLockRetention{ Mode: retentionMode, RetainUntilDate: aws.Time(time.Now().AddDate(0, 0, int(retentionPeriodDays))), }, BypassGovernanceRetention: aws.Bool(true), } _, err := actor.S3Client.PutObjectRetention(ctx, input) if err != nil { var noKey *types.NoSuchKey if errors.As(err, &noKey) { log.Printf("Object %s does not exist in bucket %s.\n", key, bucket) err = noKey } } return err }
Java
SDKpara Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

// Set or modify a retention period on an object in an S3 bucket. public void modifyObjectRetentionPeriod(String bucketName, String objectKey) { // Calculate the instant one day from now. Instant futureInstant = Instant.now().plus(1, ChronoUnit.DAYS); // Convert the Instant to a ZonedDateTime object with a specific time zone. ZonedDateTime zonedDateTime = futureInstant.atZone(ZoneId.systemDefault()); // Define a formatter for human-readable output. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // Format the ZonedDateTime object to a human-readable date string. String humanReadableDate = formatter.format(zonedDateTime); // Print the formatted date string. System.out.println("Formatted Date: " + humanReadableDate); ObjectLockRetention retention = ObjectLockRetention.builder() .mode(ObjectLockRetentionMode.GOVERNANCE) .retainUntilDate(futureInstant) .build(); PutObjectRetentionRequest retentionRequest = PutObjectRetentionRequest.builder() .bucket(bucketName) .key(objectKey) .retention(retention) .build(); getClient().putObjectRetention(retentionRequest); System.out.println("Set retention for "+objectKey +" in " +bucketName +" until "+ humanReadableDate +"."); }
  • Para API obter detalhes, consulte PutObjectRetentionem AWS SDK for Java 2.x APIReferência.

JavaScript
SDKpara JavaScript (v3)
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

import { fileURLToPath } from "url"; import { PutObjectRetentionCommand, S3Client } from "@aws-sdk/client-s3"; /** * @param {S3Client} client * @param {string} bucketName * @param {string} objectKey */ export const main = async (client, bucketName, objectKey) => { const command = new PutObjectRetentionCommand({ Bucket: bucketName, Key: objectKey, BypassGovernanceRetention: false, // ChecksumAlgorithm: "ALGORITHM", // ContentMD5: "MD5_HASH", // ExpectedBucketOwner: "ACCOUNT_ID", // RequestPayer: "requester", Retention: { Mode: "GOVERNANCE", // or "COMPLIANCE" RetainUntilDate: new Date(new Date().getTime() + 24 * 60 * 60 * 1000), }, // VersionId: "OBJECT_VERSION_ID", }); try { const response = await client.send(command); console.log( `Object Retention settings updated: ${response.$metadata.httpStatusCode}`, ); } catch (err) { console.error(err); } }; // Invoke main function if this file was run directly. if (process.argv[1] === fileURLToPath(import.meta.url)) { main(new S3Client(), "BUCKET_NAME", "OBJECT_KEY"); }
  • Para API obter detalhes, consulte PutObjectRetentionem AWS SDK for JavaScript APIReferência.

PowerShell
Ferramentas para PowerShell

Exemplo 1: o comando habilita o modo de retenção de governança até a data “31st Dec 2019 00:00:00” para o objeto “testfile.txt” no bucket do S3 em questão.

Write-S3ObjectRetention -BucketName 's3buckettesting' -Key 'testfile.txt' -Retention_Mode GOVERNANCE -Retention_RetainUntilDate "2019-12-31T00:00:00"
  • Para API obter detalhes, consulte PutObjectRetentionem Referência de AWS Tools for PowerShell cmdlet.

Python
SDKpara Python (Boto3)
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

Defina uma retenção de objetos.

s3_client.put_object_retention( Bucket=bucket, Key=key, VersionId=version_id, Retention={"Mode": "GOVERNANCE", "RetainUntilDate": far_future_date}, BypassGovernanceRetention=True, )
  • Para API obter detalhes, consulte a PutObjectRetentionReferência AWS SDK do Python (Boto3). API