Usar GetBucketAcl com o AWS SDK ou a CLI - Amazon Simple Storage Service

Usar GetBucketAcl com o AWS SDK ou a CLI

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

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

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

/// <summary> /// Get the access control list (ACL) for the new bucket. /// </summary> /// <param name="client">The initialized client object used to get the /// access control list (ACL) of the bucket.</param> /// <param name="newBucketName">The name of the newly created bucket.</param> /// <returns>An S3AccessControlList.</returns> public static async Task<S3AccessControlList> GetACLForBucketAsync(IAmazonS3 client, string newBucketName) { // Retrieve bucket ACL to show that the ACL was properly applied to // the new bucket. GetACLResponse getACLResponse = await client.GetACLAsync(new GetACLRequest { BucketName = newBucketName, }); return getACLResponse.AccessControlList; }
  • Para obter detalhes da API, consulte GetBucketAcl na Referência da API AWS SDK for .NET.

C++
SDK para C++
nota

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

bool AwsDoc::S3::getBucketAcl(const Aws::String &bucketName, const Aws::S3::S3ClientConfiguration &clientConfig) { Aws::S3::S3Client s3Client(clientConfig); Aws::S3::Model::GetBucketAclRequest request; request.SetBucket(bucketName); Aws::S3::Model::GetBucketAclOutcome outcome = s3Client.GetBucketAcl(request); if (!outcome.IsSuccess()) { const Aws::S3::S3Error &err = outcome.GetError(); std::cerr << "Error: getBucketAcl: " << err.GetExceptionName() << ": " << err.GetMessage() << std::endl; } else { Aws::Vector<Aws::S3::Model::Grant> grants = outcome.GetResult().GetGrants(); for (auto it = grants.begin(); it != grants.end(); it++) { Aws::S3::Model::Grant grant = *it; Aws::S3::Model::Grantee grantee = grant.GetGrantee(); std::cout << "For bucket " << bucketName << ": " << std::endl << std::endl; if (grantee.TypeHasBeenSet()) { std::cout << "Type: " << getGranteeTypeString(grantee.GetType()) << std::endl; } if (grantee.DisplayNameHasBeenSet()) { std::cout << "Display name: " << grantee.GetDisplayName() << std::endl; } if (grantee.EmailAddressHasBeenSet()) { std::cout << "Email address: " << grantee.GetEmailAddress() << std::endl; } if (grantee.IDHasBeenSet()) { std::cout << "ID: " << grantee.GetID() << std::endl; } if (grantee.URIHasBeenSet()) { std::cout << "URI: " << grantee.GetURI() << std::endl; } std::cout << "Permission: " << getPermissionString(grant.GetPermission()) << std::endl << std::endl; } } return outcome.IsSuccess(); } //! Routine which converts a built-in type enumeration to a human-readable string. /*! \param type: Type enumeration. \return String: Human-readable string. */ Aws::String getGranteeTypeString(const Aws::S3::Model::Type &type) { switch (type) { case Aws::S3::Model::Type::AmazonCustomerByEmail: return "Email address of an AWS account"; case Aws::S3::Model::Type::CanonicalUser: return "Canonical user ID of an AWS account"; case Aws::S3::Model::Type::Group: return "Predefined Amazon S3 group"; case Aws::S3::Model::Type::NOT_SET: return "Not set"; default: return "Type unknown"; } } //! Routine which converts a built-in type enumeration to a human-readable string. /*! \param permission: Permission enumeration. \return String: Human-readable string. */ Aws::String getPermissionString(const Aws::S3::Model::Permission &permission) { switch (permission) { case Aws::S3::Model::Permission::FULL_CONTROL: return "Can list objects in this bucket, create/overwrite/delete " "objects in this bucket, and read/write this " "bucket's permissions"; case Aws::S3::Model::Permission::NOT_SET: return "Permission not set"; case Aws::S3::Model::Permission::READ: return "Can list objects in this bucket"; case Aws::S3::Model::Permission::READ_ACP: return "Can read this bucket's permissions"; case Aws::S3::Model::Permission::WRITE: return "Can create, overwrite, and delete objects in this bucket"; case Aws::S3::Model::Permission::WRITE_ACP: return "Can write this bucket's permissions"; default: return "Permission unknown"; } return "Permission unknown"; }
  • Para obter detalhes da API, consulte GetBucketAcl na Referência da API AWS SDK for C++.

CLI
AWS CLI

O seguinte comando recupera a lista de controle de acesso do bucket my-bucket:

aws s3api get-bucket-acl --bucket my-bucket

Saída:

{ "Owner": { "DisplayName": "my-username", "ID": "7009a8971cd538e11f6b6606438875e7c86c5b672f46db45460ddcd087d36c32" }, "Grants": [ { "Grantee": { "DisplayName": "my-username", "ID": "7009a8971cd538e11f6b6606438875e7c86c5b672f46db45460ddcd087d36c32" }, "Permission": "FULL_CONTROL" } ] }
  • Para obter detalhes da API, consulte GetBucketAcl na Referência de comandos da AWS CLI.

Java
SDK para Java 2.x
nota

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

import software.amazon.awssdk.services.s3.model.S3Exception; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.GetObjectAclRequest; import software.amazon.awssdk.services.s3.model.GetObjectAclResponse; import software.amazon.awssdk.services.s3.model.Grant; import java.util.List; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class GetAcl { public static void main(String[] args) { final String usage = """ Usage: <bucketName> <objectKey> Where: bucketName - The Amazon S3 bucket to get the access control list (ACL) for. objectKey - The object to get the ACL for.\s """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String bucketName = args[0]; String objectKey = args[1]; System.out.println("Retrieving ACL for object: " + objectKey); System.out.println("in bucket: " + bucketName); Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() .region(region) .build(); getBucketACL(s3, objectKey, bucketName); s3.close(); System.out.println("Done!"); } public static String getBucketACL(S3Client s3, String objectKey, String bucketName) { try { GetObjectAclRequest aclReq = GetObjectAclRequest.builder() .bucket(bucketName) .key(objectKey) .build(); GetObjectAclResponse aclRes = s3.getObjectAcl(aclReq); List<Grant> grants = aclRes.grants(); String grantee = ""; for (Grant grant : grants) { System.out.format(" %s: %s\n", grant.grantee().id(), grant.permission()); grantee = grant.grantee().id(); } return grantee; } catch (S3Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } }
  • Para obter detalhes da API, consulte GetBucketAcl na Referência da API AWS SDK for Java 2.x.

JavaScript
SDK para JavaScript (v3)
nota

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

Obtenha as permissões de ACL.

import { GetBucketAclCommand, S3Client } from "@aws-sdk/client-s3"; const client = new S3Client({}); export const main = async () => { const command = new GetBucketAclCommand({ Bucket: "test-bucket", }); try { const response = await client.send(command); console.log(response); } catch (err) { console.error(err); } };
Python
SDK para Python (Boto3).
nota

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

class BucketWrapper: """Encapsulates S3 bucket actions.""" def __init__(self, bucket): """ :param bucket: A Boto3 Bucket resource. This is a high-level resource in Boto3 that wraps bucket actions in a class-like structure. """ self.bucket = bucket self.name = bucket.name def get_acl(self): """ Get the ACL of the bucket. :return: The ACL of the bucket. """ try: acl = self.bucket.Acl() logger.info( "Got ACL for bucket %s. Owner is %s.", self.bucket.name, acl.owner ) except ClientError: logger.exception("Couldn't get ACL for bucket %s.", self.bucket.name) raise else: return acl
  • Para obter detalhes da API, consulte GetBucketAcl na Referência da API AWS SDK para Python (Boto3).

Para obter uma lista completa dos Guias do desenvolvedor do SDK da AWS e exemplos de código, consulte Usar este serviço com um AWS SDK. Este tópico também inclui informações sobre como começar e detalhes sobre versões anteriores do SDK.