AWS SDK を使用して、Amazon S3 バケットの新しい ACL を設定する - AWS SDK コードサンプル

Doc AWS SDK Examples リポジトリには、他にも SDK の例があります。 AWS GitHub

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

AWS SDK を使用して、Amazon S3 バケットの新しい ACL を設定する

次のコード例は、S3 バケットの新しいアクセスコントロールリスト (ACL) を設定する方法を示しています。

アクション例は、より大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。次のコード例で、このアクションのコンテキストを確認できます。

.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 の詳細については、「 API リファレンスPutBucketAcl」の「」を参照してください。 AWS SDK for .NET

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::Client::ClientConfiguration &clientConfig, const Aws::String &granteeDisplayName, const Aws::String &granteeEmailAddress, const Aws::String &granteeURI) { Aws::S3::S3Client s3_client(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 (!granteeDisplayName.empty()) { grantee.SetDisplayName(granteeDisplayName); } 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 = s3_client.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. /*! \sa SetGranteePermission() \param access Human readable string. */ 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. /*! \sa SetGranteeType() \param type Human readable string. */ 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 の詳細については、「 API リファレンスPutBucketAcl」の「」を参照してください。 AWS SDK for C++

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 の詳細については、「 コマンドリファレンスPutBucketAcl」の「」を参照してください。 AWS CLI

Java
SDK for Java 2.x
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

import java.util.ArrayList; import java.util.List; import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.services.s3.model.Permission; import software.amazon.awssdk.services.s3.model.Grant; import software.amazon.awssdk.services.s3.model.AccessControlPolicy; import software.amazon.awssdk.services.s3.model.Type; import software.amazon.awssdk.services.s3.model.PutBucketAclRequest; import software.amazon.awssdk.services.s3.model.S3Exception; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; /** * 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 の詳細については、「 API リファレンスPutBucketAcl」の「」を参照してください。 AWS SDK for Java 2.x

JavaScript
SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

バケット ACL をプットします。

import { PutBucketAclCommand, GetBucketAclCommand, 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 の詳細については、PutBucketAclAWS「 SDK for Kotlin API リファレンス」の「」を参照してください。

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