使用 AWS SDK 创建 Amazon S3 桶 - AWS SDK 代码示例

文档 AWS SDK 示例 GitHub 存储库中还有更多 S AWS DK 示例

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

使用 AWS SDK 创建 Amazon S3 桶

以下代码示例演示如何创建 S3 桶。

操作示例是大型程序的代码摘录,必须在上下文中运行。您可以在以下代码示例中查看此操作的上下文:

.NET
AWS SDK for .NET
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整示例,了解如何进行设置和运行。

/// <summary> /// Shows how to create a new Amazon S3 bucket. /// </summary> /// <param name="client">An initialized Amazon S3 client object.</param> /// <param name="bucketName">The name of the bucket to create.</param> /// <returns>A boolean value representing the success or failure of /// the bucket creation process.</returns> public static async Task<bool> CreateBucketAsync(IAmazonS3 client, string bucketName) { try { var request = new PutBucketRequest { BucketName = bucketName, UseClientRegion = true, }; var response = await client.PutBucketAsync(request); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; } catch (AmazonS3Exception ex) { Console.WriteLine($"Error creating bucket: '{ex.Message}'"); return false; } }
  • 有关 API 的详细信息,请参阅 AWS SDK for .NETAPI 参考CreateBucket中的。

Bash
AWS CLI 及 Bash 脚本
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整示例,了解如何进行设置和运行。

############################################################################### # function iecho # # This function enables the script to display the specified text only if # the global variable $VERBOSE is set to true. ############################################################################### function iecho() { if [[ $VERBOSE == true ]]; then echo "$@" fi } ############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################### # function create-bucket # # This function creates the specified bucket in the specified AWS Region, unless # it already exists. # # Parameters: # -b bucket_name -- The name of the bucket to create. # -r region_code -- The code for an AWS Region in which to # create the bucket. # # Returns: # The URL of the bucket that was created. # And: # 0 - If successful. # 1 - If it fails. ############################################################################### function create_bucket() { local bucket_name region_code response local option OPTARG # Required to use getopts command in a function. # bashsupport disable=BP5008 function usage() { echo "function create_bucket" echo "Creates an Amazon S3 bucket. You must supply a bucket name:" echo " -b bucket_name The name of the bucket. It must be globally unique." echo " [-r region_code] The code for an AWS Region in which the bucket is created." echo "" } # Retrieve the calling parameters. while getopts "b:r:h" option; do case "${option}" in b) bucket_name="${OPTARG}" ;; r) region_code="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done if [[ -z "$bucket_name" ]]; then errecho "ERROR: You must provide a bucket name with the -b parameter." usage return 1 fi local bucket_config_arg # A location constraint for "us-east-1" returns an error. if [[ -n "$region_code" ]] && [[ "$region_code" != "us-east-1" ]]; then bucket_config_arg="--create-bucket-configuration LocationConstraint=$region_code" fi iecho "Parameters:\n" iecho " Bucket name: $bucket_name" iecho " Region code: $region_code" iecho "" # If the bucket already exists, we don't want to try to create it. if (bucket_exists "$bucket_name"); then errecho "ERROR: A bucket with that name already exists. Try again." return 1 fi # shellcheck disable=SC2086 response=$(aws s3api create-bucket \ --bucket "$bucket_name" \ $bucket_config_arg) # shellcheck disable=SC2181 if [[ ${?} -ne 0 ]]; then errecho "ERROR: AWS reports create-bucket operation failed.\n$response" return 1 fi }
  • 有关 API 的详细信息,请参阅AWS CLI命令参考CreateBucket中的。

C++
适用于 C++ 的 SDK
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整示例,了解如何进行设置和运行。

bool AwsDoc::S3::CreateBucket(const Aws::String &bucketName, const Aws::Client::ClientConfiguration &clientConfig) { Aws::S3::S3Client client(clientConfig); Aws::S3::Model::CreateBucketRequest request; request.SetBucket(bucketName); //TODO(user): Change the bucket location constraint enum to your target Region. if (clientConfig.region != "us-east-1") { Aws::S3::Model::CreateBucketConfiguration createBucketConfig; createBucketConfig.SetLocationConstraint( Aws::S3::Model::BucketLocationConstraintMapper::GetBucketLocationConstraintForName( clientConfig.region)); request.SetCreateBucketConfiguration(createBucketConfig); } Aws::S3::Model::CreateBucketOutcome outcome = client.CreateBucket(request); if (!outcome.IsSuccess()) { auto err = outcome.GetError(); std::cerr << "Error: CreateBucket: " << err.GetExceptionName() << ": " << err.GetMessage() << std::endl; } else { std::cout << "Created bucket " << bucketName << " in the specified AWS Region." << std::endl; } return outcome.IsSuccess(); }
  • 有关 API 的详细信息,请参阅 AWS SDK for C++API 参考CreateBucket中的。

CLI
AWS CLI

示例 1:创建存储桶

以下 create-bucket 示例创建一个名为 my-bucket 的存储桶:

aws s3api create-bucket \ --bucket my-bucket \ --region us-east-1

输出:

{ "Location": "/my-bucket" }

有关更多信息,请参阅《Amazon S3 用户指南》中的创建存储桶

示例 2:创建带有强制拥有者的存储桶

以下 create-bucket 示例创建一个名为 my-bucket 的存储桶,该存储桶对于 S3 对象所有权使用强制存储桶拥有者设置。

aws s3api create-bucket \ --bucket my-bucket \ --region us-east-1 \ --object-ownership BucketOwnerEnforced

输出:

{ "Location": "/my-bucket" }

有关更多信息,请参阅《Amazon S3 用户指南》中的控制对象所有权和禁用 ACL

示例 3:在“us-east-1”区域之外创建存储桶

以下 create-bucket 示例在 eu-west-1 区域中创建名为 my-bucket 的存储桶。us-east-1 之外的区域需要指定相应的 LocationConstraint 才能在所需区域创建存储桶。

aws s3api create-bucket \ --bucket my-bucket \ --region eu-west-1 \ --create-bucket-configuration LocationConstraint=eu-west-1

输出:

{ "Location": "http://my-bucket.s3.amazonaws.com/" }

有关更多信息,请参阅《Amazon S3 用户指南》中的创建存储桶

  • 有关 API 的详细信息,请参阅AWS CLI命令参考CreateBucket中的。

Go
适用于 Go V2 的 SDK
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整示例,了解如何进行设置和运行。

// BucketBasics encapsulates the Amazon Simple Storage Service (Amazon S3) actions // used in the examples. // It contains S3Client, an Amazon S3 service client that is used to perform bucket // and object actions. type BucketBasics struct { S3Client *s3.Client } // CreateBucket creates a bucket with the specified name in the specified Region. func (basics BucketBasics) CreateBucket(name string, region string) error { _, err := basics.S3Client.CreateBucket(context.TODO(), &s3.CreateBucketInput{ Bucket: aws.String(name), CreateBucketConfiguration: &types.CreateBucketConfiguration{ LocationConstraint: types.BucketLocationConstraint(region), }, }) if err != nil { log.Printf("Couldn't create bucket %v in Region %v. Here's why: %v\n", name, region, err) } return err }
  • 有关 API 的详细信息,请参阅 AWS SDK for GoAPI 参考CreateBucket中的。

Java
适用于 Java 2.x 的 SDK
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整示例,了解如何进行设置和运行。

import software.amazon.awssdk.core.waiters.WaiterResponse; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.CreateBucketRequest; import software.amazon.awssdk.services.s3.model.HeadBucketRequest; import software.amazon.awssdk.services.s3.model.HeadBucketResponse; import software.amazon.awssdk.services.s3.model.S3Exception; import software.amazon.awssdk.services.s3.waiters.S3Waiter; import java.net.URISyntaxException; /** * 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 CreateBucket { public static void main(String[] args) throws URISyntaxException { final String usage = """ Usage: <bucketName>\s Where: bucketName - The name of the bucket to create. The bucket name must be unique, or an error occurs. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String bucketName = args[0]; System.out.format("Creating a bucket named %s\n", bucketName); Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() .region(region) .build(); createBucket(s3, bucketName); s3.close(); } public static void createBucket(S3Client s3Client, String bucketName) { try { S3Waiter s3Waiter = s3Client.waiter(); CreateBucketRequest bucketRequest = CreateBucketRequest.builder() .bucket(bucketName) .build(); s3Client.createBucket(bucketRequest); HeadBucketRequest bucketRequestWait = HeadBucketRequest.builder() .bucket(bucketName) .build(); // Wait until the bucket is created and print out the response. WaiterResponse<HeadBucketResponse> waiterResponse = s3Waiter.waitUntilBucketExists(bucketRequestWait); waiterResponse.matched().response().ifPresent(System.out::println); System.out.println(bucketName + " is ready"); } catch (S3Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • 有关 API 的详细信息,请参阅 AWS SDK for Java 2.xAPI 参考CreateBucket中的。

JavaScript
适用于 JavaScript (v3) 的软件开发工具包
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整示例,了解如何进行设置和运行。

创建存储桶。

import { CreateBucketCommand, S3Client } from "@aws-sdk/client-s3"; const client = new S3Client({}); export const main = async () => { const command = new CreateBucketCommand({ // The name of the bucket. Bucket names are unique and have several other constraints. // See https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucketnamingrules.html Bucket: "bucket-name", }); try { const { Location } = await client.send(command); console.log(`Bucket created with location ${Location}`); } catch (err) { console.error(err); } };
Kotlin
适用于 Kotlin 的 SDK
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整示例,了解如何进行设置和运行。

suspend fun createNewBucket(bucketName: String) { val request = CreateBucketRequest { bucket = bucketName } S3Client { region = "us-east-1" }.use { s3 -> s3.createBucket(request) println("$bucketName is ready") } }
  • 有关 API 的详细信息,请参阅适用CreateBucket于 K otlin 的 AWS SDK API 参考

PHP
适用于 PHP 的 SDK
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整示例,了解如何进行设置和运行。

创建桶。

$s3client = new Aws\S3\S3Client(['region' => 'us-west-2']); try { $this->s3client->createBucket([ 'Bucket' => $this->bucketName, 'CreateBucketConfiguration' => ['LocationConstraint' => $region], ]); echo "Created bucket named: $this->bucketName \n"; } catch (Exception $exception) { echo "Failed to create bucket $this->bucketName with error: " . $exception->getMessage(); exit("Please fix error with bucket creation before continuing."); }
  • 有关 API 的详细信息,请参阅 AWS SDK for PHPAPI 参考CreateBucket中的。

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 create(self, region_override=None): """ Create an Amazon S3 bucket in the default Region for the account or in the specified Region. :param region_override: The Region in which to create the bucket. If this is not specified, the Region configured in your shared credentials is used. """ if region_override is not None: region = region_override else: region = self.bucket.meta.client.meta.region_name try: self.bucket.create(CreateBucketConfiguration={"LocationConstraint": region}) self.bucket.wait_until_exists() logger.info("Created bucket '%s' in region=%s", self.bucket.name, region) except ClientError as error: logger.exception( "Couldn't create bucket named '%s' in region=%s.", self.bucket.name, region, ) raise error

使用生命周期配置创建版本控制的桶。

def create_versioned_bucket(bucket_name, prefix): """ Creates an Amazon S3 bucket, enables it for versioning, and configures a lifecycle that expires noncurrent object versions after 7 days. Adding a lifecycle configuration to a versioned bucket is a best practice. It helps prevent objects in the bucket from accumulating a large number of noncurrent versions, which can slow down request performance. Usage is shown in the usage_demo_single_object function at the end of this module. :param bucket_name: The name of the bucket to create. :param prefix: Identifies which objects are automatically expired under the configured lifecycle rules. :return: The newly created bucket. """ try: bucket = s3.create_bucket( Bucket=bucket_name, CreateBucketConfiguration={ "LocationConstraint": s3.meta.client.meta.region_name }, ) logger.info("Created bucket %s.", bucket.name) except ClientError as error: if error.response["Error"]["Code"] == "BucketAlreadyOwnedByYou": logger.warning("Bucket %s already exists! Using it.", bucket_name) bucket = s3.Bucket(bucket_name) else: logger.exception("Couldn't create bucket %s.", bucket_name) raise try: bucket.Versioning().enable() logger.info("Enabled versioning on bucket %s.", bucket.name) except ClientError: logger.exception("Couldn't enable versioning on bucket %s.", bucket.name) raise try: expiration = 7 bucket.LifecycleConfiguration().put( LifecycleConfiguration={ "Rules": [ { "Status": "Enabled", "Prefix": prefix, "NoncurrentVersionExpiration": {"NoncurrentDays": expiration}, } ] } ) logger.info( "Configured lifecycle to expire noncurrent versions after %s days " "on bucket %s.", expiration, bucket.name, ) except ClientError as error: logger.warning( "Couldn't configure lifecycle on bucket %s because %s. " "Continuing anyway.", bucket.name, error, ) return bucket
  • 有关 API 的详细信息,请参阅适用CreateBucketPython 的 AWS SDK (Boto3) API 参考

Ruby
适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整示例,了解如何进行设置和运行。

require "aws-sdk-s3" # Wraps Amazon S3 bucket actions. class BucketCreateWrapper attr_reader :bucket # @param bucket [Aws::S3::Bucket] An Amazon S3 bucket initialized with a name. This is a client-side object until # create is called. def initialize(bucket) @bucket = bucket end # Creates an Amazon S3 bucket in the specified AWS Region. # # @param region [String] The Region where the bucket is created. # @return [Boolean] True when the bucket is created; otherwise, false. def create?(region) @bucket.create(create_bucket_configuration: { location_constraint: region }) true rescue Aws::Errors::ServiceError => e puts "Couldn't create bucket. Here's why: #{e.message}" false end # Gets the Region where the bucket is located. # # @return [String] The location of the bucket. def location if @bucket.nil? "None. You must create a bucket before you can get its location!" else @bucket.client.get_bucket_location(bucket: @bucket.name).location_constraint end rescue Aws::Errors::ServiceError => e "Couldn't get the location of #{@bucket.name}. Here's why: #{e.message}" end end # Example usage: def run_demo region = "us-west-2" wrapper = BucketCreateWrapper.new(Aws::S3::Bucket.new("doc-example-bucket-#{Random.uuid}")) return unless wrapper.create?(region) puts "Created bucket #{wrapper.bucket.name}." puts "Your bucket's region is: #{wrapper.location}" end run_demo if $PROGRAM_NAME == __FILE__
  • 有关 API 的详细信息,请参阅 AWS SDK for RubyAPI 参考CreateBucket中的。

Rust
适用于 Rust 的 SDK
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整示例,了解如何进行设置和运行。

pub async fn create_bucket( client: &Client, bucket_name: &str, region: &str, ) -> Result<CreateBucketOutput, SdkError<CreateBucketError>> { let constraint = BucketLocationConstraint::from(region); let cfg = CreateBucketConfiguration::builder() .location_constraint(constraint) .build(); client .create_bucket() .create_bucket_configuration(cfg) .bucket(bucket_name) .send() .await }
  • 有关 API 的详细信息,请参阅适用CreateBucketRust 的 AWS SDK API 参考

SAP ABAP
SDK for SAP ABAP
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整示例,了解如何进行设置和运行。

TRY. lo_s3->createbucket( iv_bucket = iv_bucket_name ). MESSAGE 'S3 bucket created.' TYPE 'I'. CATCH /aws1/cx_s3_bucketalrdyexists. MESSAGE 'Bucket name already exists.' TYPE 'E'. CATCH /aws1/cx_s3_bktalrdyownedbyyou. MESSAGE 'Bucket already exists and is owned by you.' TYPE 'E'. ENDTRY.
  • 有关 API 的详细信息,请参阅适用CreateBucket于 S AP 的 AWS SDK ABAP API 参考

Swift
SDK for Swift
注意

这是预览版 SDK 的预发布文档。本文档随时可能更改。

注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整示例,了解如何进行设置和运行。

public func createBucket(name: String) async throws { let config = S3ClientTypes.CreateBucketConfiguration( locationConstraint: .usEast2 ) let input = CreateBucketInput( bucket: name, createBucketConfiguration: config ) _ = try await client.createBucket(input: input) }
  • 有关 API 的详细信息,请参阅适用于 S wift 的 AWS SDK API 参考CreateBucket中。