Uso de GetObjectLockConfiguration con un AWS SDK o una CLI - Amazon Simple Storage Service

Uso de GetObjectLockConfiguration con un AWS SDK o una CLI

En los siguientes ejemplos de código, se muestra cómo utilizar GetObjectLockConfiguration.

Los ejemplos de acciones son extractos de código de programas más grandes y deben ejecutarse en contexto. Puede ver esta acción en contexto en el siguiente ejemplo de código:

.NET
AWS SDK for .NET
nota

Hay más información en GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de 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(); } }
CLI
AWS CLI

Para recuperar una configuración de bloqueo de objetos para un bucket

En el siguiente ejemplo de get-object-lock-configuration, se recupera la configuración de bloqueo de objetos para el bucket especificado.

aws s3api get-object-lock-configuration \ --bucket my-bucket-with-object-lock

Salida:

{ "ObjectLockConfiguration": { "ObjectLockEnabled": "Enabled", "Rule": { "DefaultRetention": { "Mode": "COMPLIANCE", "Days": 50 } } } }
Go
SDK para Go V2
nota

Hay más en GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de 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 }
Java
SDK para Java 2.x
nota

Hay más en GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de 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()); }
  • Para obtener información sobre la APl, consulte GetObjectLockConfiguration en la Referencia de la API de AWS SDK for Java 2.x..

JavaScript
SDK para JavaScript (v3)
nota

Hay más información en GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

import { fileURLToPath } from "url"; import { GetObjectLockConfigurationCommand, S3Client, } from "@aws-sdk/client-s3"; /** * @param {S3Client} client * @param {string} bucketName */ export const main = async (client, bucketName) => { const command = new GetObjectLockConfigurationCommand({ Bucket: bucketName, // Optionally, you can provide additional parameters // ExpectedBucketOwner: "ACCOUNT_ID", }); try { const { ObjectLockConfiguration } = await client.send(command); console.log(`Object Lock Configuration: ${ObjectLockConfiguration}`); } 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"); }
  • Para obtener información sobre la APl, consulte GetObjectLockConfiguration en la Referencia de la API de AWS SDK for JavaScript..

PowerShell
Herramientas para PowerShell

Ejemplo 1: este comando devuelve el valor “Enabled” si la configuración de bloqueo de objetos está habilitada para el bucket de S3 indicado.

Get-S3ObjectLockConfiguration -BucketName 's3buckettesting' -Select ObjectLockConfiguration.ObjectLockEnabled

Salida:

Value ----- Enabled
  • Para obtener información sobre la API, consulte GetObjectLockConfiguration en la Referencia de Cmdlet de AWS Tools for PowerShell.

Python
SDK para Python (Boto3)
nota

Hay más en GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

Obtenga la configuración de bloqueo de objetos.

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
  • Para obtener información sobre la API, consulte GetObjectLockConfiguration en la Referencia de la del SDK de AWS SDK para Python (Boto3).

Para obtener una lista completa de las guías para desarrolladores del AWS SDK y ejemplos de código, consulte Uso de este servicio con un SDK de AWS. En este tema también se incluye información sobre cómo comenzar a utilizar el SDK y detalles sobre sus versiones anteriores.