搭PutBucketAcl配 AWS 開發套件或 CLI 使用 - AWS SDK 程式碼範例

AWS 文件 AWS SDK 範例 GitHub 存放庫中提供了更多 SDK 範例

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

PutBucketAcl配 AWS 開發套件或 CLI 使用

下列程式碼範例會示範如何使用PutBucketAcl

動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:

.NET
AWS SDK for .NET
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

/// <summary> /// Creates an Amazon S3 bucket with an ACL to control access to the /// bucket and the objects stored in it. /// </summary> /// <param name="client">The initialized client object used to create /// an Amazon S3 bucket, with an ACL applied to the bucket. /// </param> /// <param name="region">The AWS Region where the bucket will be created.</param> /// <param name="newBucketName">The name of the bucket to create.</param> /// <returns>A boolean value indicating success or failure.</returns> public static async Task<bool> CreateBucketUseCannedACLAsync(IAmazonS3 client, S3Region region, string newBucketName) { try { // Create a new Amazon S3 bucket with Canned ACL. var putBucketRequest = new PutBucketRequest() { BucketName = newBucketName, BucketRegion = region, CannedACL = S3CannedACL.LogDeliveryWrite, }; PutBucketResponse putBucketResponse = await client.PutBucketAsync(putBucketRequest); return putBucketResponse.HttpStatusCode == System.Net.HttpStatusCode.OK; } catch (AmazonS3Exception ex) { Console.WriteLine($"Amazon S3 error: {ex.Message}"); } return false; }
  • 如需 API 詳細資訊,請參閱 AWS SDK for .NET API 參考PutBucketAcl中的。

C++
適用於 C++ 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

bool AwsDoc::S3::putBucketAcl(const Aws::String &bucketName, const Aws::String &ownerID, const Aws::String &granteePermission, const Aws::String &granteeType, const Aws::String &granteeID, const Aws::String &granteeEmailAddress, const Aws::String &granteeURI, const Aws::S3::S3ClientConfiguration &clientConfig) { Aws::S3::S3Client s3Client(clientConfig); Aws::S3::Model::Owner owner; owner.SetID(ownerID); Aws::S3::Model::Grantee grantee; grantee.SetType(setGranteeType(granteeType)); if (!granteeEmailAddress.empty()) { grantee.SetEmailAddress(granteeEmailAddress); } if (!granteeID.empty()) { grantee.SetID(granteeID); } if (!granteeURI.empty()) { grantee.SetURI(granteeURI); } Aws::S3::Model::Grant grant; grant.SetGrantee(grantee); grant.SetPermission(setGranteePermission(granteePermission)); Aws::Vector<Aws::S3::Model::Grant> grants; grants.push_back(grant); Aws::S3::Model::AccessControlPolicy acp; acp.SetOwner(owner); acp.SetGrants(grants); Aws::S3::Model::PutBucketAclRequest request; request.SetAccessControlPolicy(acp); request.SetBucket(bucketName); Aws::S3::Model::PutBucketAclOutcome outcome = s3Client.PutBucketAcl(request); if (!outcome.IsSuccess()) { const Aws::S3::S3Error &error = outcome.GetError(); std::cerr << "Error: putBucketAcl: " << error.GetExceptionName() << " - " << error.GetMessage() << std::endl; } else { std::cout << "Successfully added an ACL to the bucket '" << bucketName << "'." << std::endl; } return outcome.IsSuccess(); } //! Routine which converts a human-readable string to a built-in type enumeration. /*! \param access: Human readable string. \return Permission: A Permission enum. */ Aws::S3::Model::Permission setGranteePermission(const Aws::String &access) { if (access == "FULL_CONTROL") return Aws::S3::Model::Permission::FULL_CONTROL; if (access == "WRITE") return Aws::S3::Model::Permission::WRITE; if (access == "READ") return Aws::S3::Model::Permission::READ; if (access == "WRITE_ACP") return Aws::S3::Model::Permission::WRITE_ACP; if (access == "READ_ACP") return Aws::S3::Model::Permission::READ_ACP; return Aws::S3::Model::Permission::NOT_SET; } //! Routine which converts a human-readable string to a built-in type enumeration. /*! \param type: Human readable string. \return Type: Type enumeration */ Aws::S3::Model::Type setGranteeType(const Aws::String &type) { if (type == "Amazon customer by email") return Aws::S3::Model::Type::AmazonCustomerByEmail; if (type == "Canonical user") return Aws::S3::Model::Type::CanonicalUser; if (type == "Group") return Aws::S3::Model::Type::Group; return Aws::S3::Model::Type::NOT_SET; }
  • 如需 API 詳細資訊,請參閱 AWS SDK for C++ API 參考PutBucketAcl中的。

CLI
AWS CLI

此範例授full control予兩位 AWS 使用者 (user1@example.comuser2@example.com),並授予所有人的read權限:

aws s3api put-bucket-acl --bucket MyBucket --grant-full-control emailaddress=user1@example.com,emailaddress=user2@example.com --grant-read uri=http://acs.amazonaws.com/groups/global/AllUsers

如需有關自訂 ACL (s3api ACL 命令,例如,使用相同的速記引數表示法) 的詳細資訊put-bucket-acl,請參閱 http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTacl.html。

  • 如需 API 詳細資訊,請參閱AWS CLI 命令參考PutBucketAcl中的。

Java
適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.AccessControlPolicy; import software.amazon.awssdk.services.s3.model.Grant; import software.amazon.awssdk.services.s3.model.Permission; import software.amazon.awssdk.services.s3.model.PutBucketAclRequest; import software.amazon.awssdk.services.s3.model.S3Exception; import software.amazon.awssdk.services.s3.model.Type; import java.util.ArrayList; 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 SetAcl { public static void main(String[] args) { final String usage = """ Usage: <bucketName> <id>\s Where: bucketName - The Amazon S3 bucket to grant permissions on.\s id - The ID of the owner of this bucket (you can get this value from the AWS Management Console). """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String bucketName = args[0]; String id = args[1]; System.out.format("Setting access \n"); System.out.println(" in bucket: " + bucketName); Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() .region(region) .build(); setBucketAcl(s3, bucketName, id); System.out.println("Done!"); s3.close(); } public static void setBucketAcl(S3Client s3, String bucketName, String id) { try { Grant ownerGrant = Grant.builder() .grantee(builder -> builder.id(id) .type(Type.CANONICAL_USER)) .permission(Permission.FULL_CONTROL) .build(); List<Grant> grantList2 = new ArrayList<>(); grantList2.add(ownerGrant); AccessControlPolicy acl = AccessControlPolicy.builder() .owner(builder -> builder.id(id)) .grants(grantList2) .build(); PutBucketAclRequest putAclReq = PutBucketAclRequest.builder() .bucket(bucketName) .accessControlPolicy(acl) .build(); s3.putBucketAcl(putAclReq); } catch (S3Exception e) { e.printStackTrace(); System.exit(1); } } }
  • 如需 API 詳細資訊,請參閱 AWS SDK for Java 2.x API 參考PutBucketAcl中的。

JavaScript
適用於 JavaScript (v3) 的開發套件
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

放置儲存貯體的 ACL。

import { PutBucketAclCommand, S3Client } from "@aws-sdk/client-s3"; const client = new S3Client({}); // Most Amazon S3 use cases don't require the use of access control lists (ACLs). // We recommend that you disable ACLs, except in unusual circumstances where // you need to control access for each object individually. // Consider a policy instead. For more information see https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucket-policies.html. export const main = async () => { // Grant a user READ access to a bucket. const command = new PutBucketAclCommand({ Bucket: "test-bucket", AccessControlPolicy: { Grants: [ { Grantee: { // The canonical ID of the user. This ID is an obfuscated form of your AWS account number. // It's unique to Amazon S3 and can't be found elsewhere. // For more information, see https://docs.aws.amazon.com/AmazonS3/latest/userguide/finding-canonical-user-id.html. ID: "canonical-id-1", Type: "CanonicalUser", }, // One of FULL_CONTROL | READ | WRITE | READ_ACP | WRITE_ACP // https://docs.aws.amazon.com/AmazonS3/latest/API/API_Grant.html#AmazonS3-Type-Grant-Permission Permission: "FULL_CONTROL", }, ], Owner: { ID: "canonical-id-2", }, }, }); try { const response = await client.send(command); console.log(response); } catch (err) { console.error(err); } };
Kotlin
適用於 Kotlin 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

suspend fun setBucketAcl( bucketName: String, idVal: String, ) { val myGrant = Grantee { id = idVal type = Type.CanonicalUser } val ownerGrant = Grant { grantee = myGrant permission = Permission.FullControl } val grantList = mutableListOf<Grant>() grantList.add(ownerGrant) val ownerOb = Owner { id = idVal } val acl = AccessControlPolicy { owner = ownerOb grants = grantList } val request = PutBucketAclRequest { bucket = bucketName accessControlPolicy = acl } S3Client { region = "us-east-1" }.use { s3 -> s3.putBucketAcl(request) println("An ACL was successfully set on $bucketName") } }
  • 有關 API 的詳細信息,請參閱 AWS SDK PutBucketAcl中的 Kotlin API 參考。

Python
適用於 Python (Boto3) 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在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 grant_log_delivery_access(self): """ Grant the AWS Log Delivery group write access to the bucket so that Amazon S3 can deliver access logs to the bucket. This is the only recommended use of an S3 bucket ACL. """ try: acl = self.bucket.Acl() # Putting an ACL overwrites the existing ACL. If you want to preserve # existing grants, append new grants to the list of existing grants. grants = acl.grants if acl.grants else [] grants.append( { "Grantee": { "Type": "Group", "URI": "http://acs.amazonaws.com/groups/s3/LogDelivery", }, "Permission": "WRITE", } ) acl.put(AccessControlPolicy={"Grants": grants, "Owner": acl.owner}) logger.info("Granted log delivery access to bucket '%s'", self.bucket.name) except ClientError: logger.exception("Couldn't add ACL to bucket '%s'.", self.bucket.name) raise
  • 如需 API 的詳細資訊,請參閱AWS 開發套件PutBucketAcl中的 Python (博托 3) API 參考。