AWS SDK または CLI で PutBucketAcl を使用する - Amazon Simple Storage Service

AWS SDK または CLI で PutBucketAcl を使用する

以下のコード例は、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++
SDK for C++
注記

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 権限を 2 人の AWS ユーザー (user1@example.com と user2@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 の詳細については、http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTacl.html を参照してください (put-bucket-acl などの s3api ACL コマンドは、同じ略記法を使用します)。

  • API の詳細については、AWS CLI コマンドリファレンスの「PutBucketAcl」を参照してください。

Java
SDK for Java 2.x
注記

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
SDK for 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
SDK for Kotlin
注記

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 for Kotlin API リファレンス」の「PutBucketAcl」を参照してください。

Python
SDK for Python (Boto3)
注記

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 SDK for Python (Boto3) API リファレンス」の「PutBucketAcl」を参照してください。

AWS SDK デベロッパーガイドとコード例の完全なリストについては、「このサービスを AWS SDK で使用する」を参照してください。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。