先决条件 - Amazon Config
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

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

先决条件

在设置 Amazon 之前 Amazon CLI,您需要创建一个 Amazon S3 存储桶、一个 Amazon SNS 主题和一个将附加策略作为先决条件的 IAM 角色。然后,您可以使用 Amazon CLI 为指定存储桶、主题和角色 Amazon Config。请按照以下步骤设置 Amazon Config的先决条件。

创建 Amazon S3 存储桶

如果您的账户中已存在 Amazon S3 存储桶,并且您想使用该存储桶,请跳过此步骤并转至 创建 Amazon SNS 主题

创建存储桶
  1. 通过 https://console.aws.amazon.com/s3/ 打开 Amazon S3 控制台。

  2. 选择 创建存储桶

  3. Bucket name(桶名称)中,输入符合 DNS 标准的桶名称。

    桶名称必须满足以下要求:

    • 在所有 Amazon S3 中是唯一的。

    • 长度必须介于 3 到 63 个字符之间。

    • 不包含大写字符。

    • 以小写字母或数字开头。

    创建存储桶后,便无法再更改其名称。请确保您选择的存储桶名称在 Amazon S3 中所有现有存储桶名称中唯一。有关存储桶命名规则和约定的更多信息,请参阅《Amazon Simple Storage Service 用户指南》中的存储桶约束和限制

    重要

    避免在存储桶名称中包含敏感信息。存储桶名称会显示在指向存储桶中的对象的 URL 中。

  4. 区域中,选择您想要存储桶所在的 Amazon 区域。

    请选择一个靠近您的区域可最大程度地减少延迟和成本以及满足法规要求。在某一区域存储的对象将一直留在该区域,除非您特意将其转移到其他区域。有关 Amazon S3 Amazon 区域的列表,请参阅中的Amazon 服务终端节点Amazon Web Services 一般参考

  5. Bucket settings for Block Public Access(阻止公有访问的桶设置)中,请选择要应用于桶的 Block Public Access(阻止公有访问)设置。

    我们建议您将所有设置保持为启用状态,除非您知道您需要为您的使用案例关闭其中一个或多个设置,例如托管公共网站。您为存储桶启用的阻止公有访问设置也将为您在存储桶上创建的所有访问点启用。有关屏蔽公共访问权限的更多信息,请参阅《Amazon Simple Storage Service 用户指南》中的使用 Amazon S3 屏蔽公共访问权限

  6. (可选)如果要启用 S3 对象锁定:

    1. 请选择 Advanced settings (高级设置),然后阅读显示的消息。

      重要

      您只能在创建存储桶时为其启用 S3 对象锁定。如果您为存储桶启用了对象锁定,则以后无法禁用它。启用对象锁定还会启用存储桶的版本控制。为存储桶启用对象锁定后,必须先配置对象锁定设置,然后才能保护存储桶中的任何对象。有关配置对象保护的更多信息,请参阅使用 Amazon S3 控制台配置 S3 对象锁定

    2. 如果要启用对象锁定,请在文本框中输入 enable 并选择 Confirm (确认)

    有关 S3 对象锁定功能的更多信息,请参阅《Amazon Simple Storage Service 用户指南》中的使用 Amazon S3 对象锁定以锁定对象

  7. 选择 创建存储桶

使用 Amazon 软件开发工具包创建存储桶时,必须创建一个客户端,然后使用该客户端发送创建存储桶的请求。作为最佳做法,您应在同一 Amazon Web Services 区域中创建客户端和桶。如果您在创建客户端或桶时未指定区域,Amazon S3 将使用默认区域美国东部(弗吉尼亚北部)。

要创建用于访问双栈端点的客户端,必须指定。 Amazon Web Services 区域有关更多信息,请参阅 Amazon S3 双堆栈端点。有关可用区域的列表 Amazon Web Services 区域,请参阅中的区域和终端节点Amazon Web Services 一般参考

创建客户端时,区域映射到特定于区域的端点。客户端使用此端点与 Amazon S3 进行通信:s3.<region>.amazonaws.com。如果您的区域是在 2019 年 3 月 20 日之后启动的,则您的客户端和存储桶必须位于同一区域。不过,您可以使用美国东部(弗吉尼亚北部)区域中的客户端在 2019 年 3 月 20 日之前启动的任何区域中创建存储桶。有关更多信息,请参阅传统端点

这些 Amazon SDK 代码示例执行以下任务:

  • 通过明确指定 Amazon Web Services 区域创建客户端 – 在本示例中,客户端使用 s3.us-west-2.amazonaws.com 终端节点与 Amazon S3 通信。您可以指定任意 Amazon Web Services 区域。有关列表 Amazon Web Services 区域,请参阅《Amazon 一般参考》中的区域和终端节点

  • 通过仅指定桶名称来发送创建桶请求 — 客户端向 Amazon S3 发送请求,请求在您创建客户端的区域中创建桶。

  • 检索有关桶位置的信息 — Amazon S3 将桶位置信息存储在与桶关联的位置子资源中。

以下代码示例演示如何使用 CreateBucket

.NET
Amazon SDK for .NET
注意

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

/// <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; } }

创建一个启用对象锁定的存储桶。

/// <summary> /// Create a new Amazon S3 bucket with object lock actions. /// </summary> /// <param name="bucketName">The name of the bucket to create.</param> /// <param name="enableObjectLock">True to enable object lock on the bucket.</param> /// <returns>True if successful.</returns> public async Task<bool> CreateBucketWithObjectLock(string bucketName, bool enableObjectLock) { Console.WriteLine($"\tCreating bucket {bucketName} with object lock {enableObjectLock}."); try { var request = new PutBucketRequest { BucketName = bucketName, UseClientRegion = true, ObjectLockEnabledForBucket = enableObjectLock, }; var response = await _amazonS3.PutBucketAsync(request); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; } catch (AmazonS3Exception ex) { Console.WriteLine($"Error creating bucket: '{ex.Message}'"); return false; } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for .NET API 参考CreateBucket中的。

Bash
Amazon CLI 使用 Bash 脚本
注意

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

############################################################################### # 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 的详细信息,请参阅Amazon CLI 命令参考CreateBucket中的。

C++
SDK for C++
注意

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

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 的详细信息,请参阅 Amazon SDK for C++ API 参考CreateBucket中的。

CLI
Amazon 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 的详细信息,请参阅Amazon CLI 命令参考CreateBucket中的。

Go
适用于 Go V2 的 SDK
注意

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

// 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 的详细信息,请参阅 Amazon SDK for Go API 参考CreateBucket中的。

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

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

创建存储桶。

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); } } }

创建一个启用对象锁定的存储桶。

// Create a new Amazon S3 bucket with object lock options. public void createBucketWithLockOptions(boolean enableObjectLock, String bucketName) { S3Waiter s3Waiter = getClient().waiter(); CreateBucketRequest bucketRequest = CreateBucketRequest.builder() .bucket(bucketName) .objectLockEnabledForBucket(enableObjectLock) .build(); getClient().createBucket(bucketRequest); HeadBucketRequest bucketRequestWait = HeadBucketRequest.builder() .bucket(bucketName) .build(); // Wait until the bucket is created and print out the response. s3Waiter.waitUntilBucketExists(bucketRequestWait); System.out.println(bucketName + " is ready"); }
  • 有关 API 的详细信息,请参阅 Amazon SDK for Java 2.x API 参考CreateBucket中的。

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

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

创建存储桶。

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。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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 的Amazon SDK API 参考

PHP
适用于 PHP 的 SDK
注意

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

创建存储桶。

$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 的详细信息,请参阅 Amazon SDK for PHP API 参考CreateBucket中的。

Python
SDK for Python (Boto3)
注意

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

使用默认设置创建存储桶。

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 的Amazon SDK (Boto3) API 参考

Ruby
适用于 Ruby 的 SDK
注意

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

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 的详细信息,请参阅 Amazon SDK for Ruby API 参考CreateBucket中的。

Rust
适用于 Rust 的 SDK
注意

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

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 的Amazon SDK API 参考

SAP ABAP
SDK for SAP ABAP
注意

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

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 的Amazon SDK ABAP API 参考

Swift
SDK for Swift
注意

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

注意

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

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 的详细信息,请参阅适用CreateBucket于 S wift 的Amazon SDK API 参考

注意

您也可以使用另一个账户中的 Amazon S3 存储桶,但您可能需要为该存储桶创建策略以便向 Amazon Config授予访问权限。有关向 Amazon S3 存储桶授予权限的信息,请参阅 Amazon Config 传送渠道的 Amazon S3 存储桶的权限,然后转至 创建 Amazon SNS 主题

创建 Amazon SNS 主题

如果您的账户中已经存在 Amazon SNS 主题并且您想要使用该主题,请跳过本步骤并转至 创建 IAM 角色

创建 Amazon SNS 主题
  1. 通过 https://console.aws.amazon.com/sns/v3/home 打开 Amazon SNS 控制台。

  2. 请执行以下操作之一:

    • 如果 Amazon Web Services 账户 之前未在您的主题下创建过任何主题,请阅读主页上对 Amazon SNS 的描述。

    • 如果 Amazon Web Services 账户 之前在您的下方创建过主题,请在导航面板上选择主题

  3. Topics(主页)页面上,选择 Create topic(创建主题)。

  4. Create topic(创建主题)页面上,在 Details(详细信息)部分中,执行以下操作:

    1. 对于 Type(类型),选择主题类型(标准或者FIFO)。

    2. 输入主题的名称。对于 FIFO 主题,将 .fifo 添加到名称的末尾。

    3. (可选)输入主题的显示名称

    4. (可选)对于 FIFO 主题,您可以选择基于内容的消息重复数据删除以启用默认的消息重复数据删除。有关更多信息,请参阅 FIFO 主题的消息重复数据删除

  5. (可选)展开加密部分并执行以下操作。有关更多信息,请参阅静态加密

    1. 选择 Enable encryption(启用加密)

    2. 指定客户主密钥 (CMK)。有关更多信息,请参阅关键术语

      对于每个 CMK 类型,都会显示 Description (描述)Account (账户)CMK ARN

      重要

      如果您不是 CMK 的拥有者,或者您登录的账户没有 kms:ListAliaseskms:DescribeKey 权限,则无法在 Amazon SNS 控制台上查看有关 CMK 的信息。

      要求 CMK 拥有者授予您这些权限。有关更多信息,请参阅 Amazon Key Management Service 开发人员指南中的 Amazon KMS API 权限:操作和资源参考

      • 默认情况下,Amazon SNS(默认)别名/aws/sns 的 Amazon 托管 CMK 处于选中状态。

        注意

        记住以下内容:

        • 首次使用为主题 Amazon KMS 指定适用于 Amazon SNS 的 Amazon 托管 CMK 时,会为 Amazon SNS 创建 Amazon 托管 CMK。 Amazon Web Services Management Console

        • 或者,在启用 SSE 的情况下首次对主题使用Publish操作时, Amazon KMS 会为 Amazon SNS 创建 Amazon 托管 CMK。

      • 要使用您的自定义 CMK Amazon Web Services 账户,请选择客户主密钥 (CMK) 字段,然后从列表中选择自定义 CMK。

        注意

        有关创建自定义 CMK 的说明,请参阅 Amazon Key Management Service 开发人员指南中的创建密钥

      • 要使用来自 Amazon Web Services 账户 您 Amazon 或其他账户的自定义 CMK ARN,请将其输入到客户主密钥 (CM K) 字段。

  6. (可选)默认情况下,只有主题拥有者才能发布或订阅主题。要配置其他访问权限,请展开访问策略部分。有关更多信息,请参阅 Amazon SNS 中的 Identity and Access Management用于 Amazon SNS 访问控制的示例案例

    注意

    使用控制台创建主题时,默认策略使用 aws:SourceOwner 条件键。此密钥类似于 aws:SourceAccount

  7. (可选)要配置 Amazon SNS 重试失败消息传输尝试的方式,请展开 Delivery retry policy (HTTP/S)(传输重试策略 (HTTP/S))部分。有关更多信息,请参阅 Amazon SNS 消息传输重试

  8. (可选)要配置 Amazon SNS 如何记录向其发送的消息 CloudWatch,请展开传送状态记录部分。有关更多信息,请参阅 Amazon SNS 消息传输状态

  9. (可选)要将元数据标签添加到主题中,请展开标签部分,输入一个(可选),然后选择添加标签。有关更多信息,请参阅 Amazon SNS 主题标记

  10. 选择创建主题

    创建主题并显示MyTopic页面。

    主题的名称ARN、(可选)显示名称主题所有者的 Amazon 账户 ID 将显示在 Details(详细信息)部分中。

  11. 将主题 ARN 复制到剪贴板,例如:

    arn:aws:sns:us-east-2:123456789012:MyTopic
使用电子邮件地址订阅 Amazon SNS 主题
  1. 通过 https://console.aws.amazon.com/sns/v3/home 打开 Amazon SNS 控制台。

  2. 在左侧导航窗格中,选择订阅

  3. Subscriptions(订阅)页面上,选择 Create subscription(创建订阅)。

  4. Create subscription(创建订阅)页上的 Details(详细信息)部分中,执行以下操作:

    1. 对于 Topic ARN(主题 ARN),选择主题的 Amazon Resource Name (ARN)。

    2. 对于 Protocol(协议),选择终端节点类型。可用的终端节点类型包括:

    3. 对于 Endpoint(终端节点),输入终端节点值,例如电子邮件地址或 Amazon SQS 队列的 ARN。

    4. 仅限 Firehose 终端节点:对于订阅角色 ARN,请指定您为写入 Firehose 交付流而创建的 IAM 角色的 ARN。有关更多信息,请参阅将 Firehose 传输流订阅 Amazon SNS 的先决条件主题。

    5. (可选)对于 Firehose、Amazon SQS、HTTP/S 终端节点,您还可以启用原始消息传输。有关更多信息,请参阅 Amazon SNS 原始消息传输

    6. (可选)要配置筛选策略,请展开 Subscription filter policy(订阅筛选策略)部分。有关更多信息,请参阅 Amazon SNS 订阅筛选策略

    7. (可选)要为订阅配置死信队列,请展开 Redrive policy (dead-letter queue)(重新驱动策略(死信队列))部分。有关更多信息,请参阅 Amazon SNS 死信队列 (DLQ)

    8. 选择创建订阅

      控制台将创建订阅并打开订阅的 Details(详细信息)页面。

要使用 S Amazon DK,必须使用您的凭据对其进行配置。有关更多信息,请参阅 Amazon 开发工具包和工具参考指南中的共享配置和凭证文件

以下代码示例演示如何使用 CreateTopic

.NET
Amazon SDK for .NET
注意

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

使用特定的名称创建主题。

using System; using System.Threading.Tasks; using Amazon.SimpleNotificationService; using Amazon.SimpleNotificationService.Model; /// <summary> /// This example shows how to use Amazon Simple Notification Service /// (Amazon SNS) to add a new Amazon SNS topic. /// </summary> public class CreateSNSTopic { public static async Task Main() { string topicName = "ExampleSNSTopic"; IAmazonSimpleNotificationService client = new AmazonSimpleNotificationServiceClient(); var topicArn = await CreateSNSTopicAsync(client, topicName); Console.WriteLine($"New topic ARN: {topicArn}"); } /// <summary> /// Creates a new SNS topic using the supplied topic name. /// </summary> /// <param name="client">The initialized SNS client object used to /// create the new topic.</param> /// <param name="topicName">A string representing the topic name.</param> /// <returns>The Amazon Resource Name (ARN) of the created topic.</returns> public static async Task<string> CreateSNSTopicAsync(IAmazonSimpleNotificationService client, string topicName) { var request = new CreateTopicRequest { Name = topicName, }; var response = await client.CreateTopicAsync(request); return response.TopicArn; } }

创建一个包含名称以及特定 FIFO 和重复数据消除属性的新主题。

/// <summary> /// Create a new topic with a name and specific FIFO and de-duplication attributes. /// </summary> /// <param name="topicName">The name for the topic.</param> /// <param name="useFifoTopic">True to use a FIFO topic.</param> /// <param name="useContentBasedDeduplication">True to use content-based de-duplication.</param> /// <returns>The ARN of the new topic.</returns> public async Task<string> CreateTopicWithName(string topicName, bool useFifoTopic, bool useContentBasedDeduplication) { var createTopicRequest = new CreateTopicRequest() { Name = topicName, }; if (useFifoTopic) { // Update the name if it is not correct for a FIFO topic. if (!topicName.EndsWith(".fifo")) { createTopicRequest.Name = topicName + ".fifo"; } // Add the attributes from the method parameters. createTopicRequest.Attributes = new Dictionary<string, string> { { "FifoTopic", "true" } }; if (useContentBasedDeduplication) { createTopicRequest.Attributes.Add("ContentBasedDeduplication", "true"); } } var createResponse = await _amazonSNSClient.CreateTopicAsync(createTopicRequest); return createResponse.TopicArn; }
  • 有关 API 的详细信息,请参阅 Amazon SDK for .NET API 参考CreateTopic中的。

C++
SDK for C++
注意

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

//! Create an Amazon Simple Notification Service (Amazon SNS) topic. /*! \param topicName: An Amazon SNS topic name. \param topicARNResult: String to return the Amazon Resource Name (ARN) for the topic. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::createTopic(const Aws::String &topicName, Aws::String &topicARNResult, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::CreateTopicRequest request; request.SetName(topicName); const Aws::SNS::Model::CreateTopicOutcome outcome = snsClient.CreateTopic(request); if (outcome.IsSuccess()) { topicARNResult = outcome.GetResult().GetTopicArn(); std::cout << "Successfully created an Amazon SNS topic " << topicName << " with topic ARN '" << topicARNResult << "'." << std::endl; } else { std::cerr << "Error creating topic " << topicName << ":" << outcome.GetError().GetMessage() << std::endl; topicARNResult.clear(); } return outcome.IsSuccess(); }
  • 有关 API 的详细信息,请参阅 Amazon SDK for C++ API 参考CreateTopic中的。

CLI
Amazon CLI

创建 SNS 主题

以下 create-topic 示例将创建名为 my-topic 的 SNS 主题。

aws sns create-topic \ --name my-topic

输出:

{ "ResponseMetadata": { "RequestId": "1469e8d7-1642-564e-b85d-a19b4b341f83" }, "TopicArn": "arn:aws:sns:us-west-2:123456789012:my-topic" }

有关更多信息,请参阅Amazon 命令行界面用户指南中的在 Amazon SQS 和 Amazon SNS 中使用命令Amazon 行界面。

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

Go
适用于 Go V2 的 SDK
注意

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

// SnsActions encapsulates the Amazon Simple Notification Service (Amazon SNS) actions // used in the examples. type SnsActions struct { SnsClient *sns.Client } // CreateTopic creates an Amazon SNS topic with the specified name. You can optionally // specify that the topic is created as a FIFO topic and whether it uses content-based // deduplication instead of ID-based deduplication. func (actor SnsActions) CreateTopic(topicName string, isFifoTopic bool, contentBasedDeduplication bool) (string, error) { var topicArn string topicAttributes := map[string]string{} if isFifoTopic { topicAttributes["FifoTopic"] = "true" } if contentBasedDeduplication { topicAttributes["ContentBasedDeduplication"] = "true" } topic, err := actor.SnsClient.CreateTopic(context.TODO(), &sns.CreateTopicInput{ Name: aws.String(topicName), Attributes: topicAttributes, }) if err != nil { log.Printf("Couldn't create topic %v. Here's why: %v\n", topicName, err) } else { topicArn = *topic.TopicArn } return topicArn, err }
  • 有关 API 的详细信息,请参阅 Amazon SDK for Go API 参考CreateTopic中的。

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

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

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.CreateTopicRequest; import software.amazon.awssdk.services.sns.model.CreateTopicResponse; import software.amazon.awssdk.services.sns.model.SnsException; /** * 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 CreateTopic { public static void main(String[] args) { final String usage = """ Usage: <topicName> Where: topicName - The name of the topic to create (for example, mytopic). """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String topicName = args[0]; System.out.println("Creating a topic with name: " + topicName); SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); String arnVal = createSNSTopic(snsClient, topicName); System.out.println("The topic ARN is" + arnVal); snsClient.close(); } public static String createSNSTopic(SnsClient snsClient, String topicName) { CreateTopicResponse result; try { CreateTopicRequest request = CreateTopicRequest.builder() .name(topicName) .build(); result = snsClient.createTopic(request); return result.topicArn(); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for Java 2.x API 参考CreateTopic中的。

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

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

在单独的模块中创建客户端并将其导出。

import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({});

导入 SDK 和客户端模块,然后调用 API。

import { CreateTopicCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} topicName - The name of the topic to create. */ export const createTopic = async (topicName = "TOPIC_NAME") => { const response = await snsClient.send( new CreateTopicCommand({ Name: topicName }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '087b8ad2-4593-50c4-a496-d7e90b82cf3e', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // TopicArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:TOPIC_NAME' // } return response; };
Kotlin
适用于 Kotlin 的 SDK
注意

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

suspend fun createSNSTopic(topicName: String): String { val request = CreateTopicRequest { name = topicName } SnsClient { region = "us-east-1" }.use { snsClient -> val result = snsClient.createTopic(request) return result.topicArn.toString() } }
  • 有关 API 的详细信息,请参阅适用CreateTopic于 K otlin 的Amazon SDK API 参考

PHP
适用于 PHP 的 SDK
注意

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

require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; /** * Create a Simple Notification Service topics in your AWS account at the requested region. * * This code expects that you have AWS credentials set up per: * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_credentials.html */ $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); $topicname = 'myTopic'; try { $result = $SnSclient->createTopic([ 'Name' => $topicname, ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }
Python
SDK for Python (Boto3)
注意

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

class SnsWrapper: """Encapsulates Amazon SNS topic and subscription functions.""" def __init__(self, sns_resource): """ :param sns_resource: A Boto3 Amazon SNS resource. """ self.sns_resource = sns_resource def create_topic(self, name): """ Creates a notification topic. :param name: The name of the topic to create. :return: The newly created topic. """ try: topic = self.sns_resource.create_topic(Name=name) logger.info("Created topic %s with ARN %s.", name, topic.arn) except ClientError: logger.exception("Couldn't create topic %s.", name) raise else: return topic
  • 有关 API 的详细信息,请参阅适用CreateTopicPython 的Amazon SDK (Boto3) API 参考

Ruby
适用于 Ruby 的 SDK
注意

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

# This class demonstrates how to create an Amazon Simple Notification Service (SNS) topic. class SNSTopicCreator # Initializes an SNS client. # # Utilizes the default AWS configuration for region and credentials. def initialize @sns_client = Aws::SNS::Client.new end # Attempts to create an SNS topic with the specified name. # # @param topic_name [String] The name of the SNS topic to create. # @return [Boolean] true if the topic was successfully created, false otherwise. def create_topic(topic_name) @sns_client.create_topic(name: topic_name) puts "The topic '#{topic_name}' was successfully created." true rescue Aws::SNS::Errors::ServiceError => e # Handles SNS service errors gracefully. puts "Error while creating the topic named '#{topic_name}': #{e.message}" false end end # Example usage: if $PROGRAM_NAME == __FILE__ topic_name = "YourTopicName" # Replace with your topic name sns_topic_creator = SNSTopicCreator.new puts "Creating the topic '#{topic_name}'..." unless sns_topic_creator.create_topic(topic_name) puts "The topic was not created. Stopping program." exit 1 end end
Rust
适用于 Rust 的 SDK
注意

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

async fn make_topic(client: &Client, topic_name: &str) -> Result<(), Error> { let resp = client.create_topic().name(topic_name).send().await?; println!( "Created topic with ARN: {}", resp.topic_arn().unwrap_or_default() ); Ok(()) }
  • 有关 API 的详细信息,请参阅适用CreateTopicRust 的Amazon SDK API 参考

SAP ABAP
SDK for SAP ABAP
注意

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

TRY. oo_result = lo_sns->createtopic( iv_name = iv_topic_name ). " oo_result is returned for testing purposes. " MESSAGE 'SNS topic created' TYPE 'I'. CATCH /aws1/cx_snstopiclimitexcdex. MESSAGE 'Unable to create more topics. You have reached the maximum number of topics allowed.' TYPE 'E'. ENDTRY.
  • 有关 API 的详细信息,请参阅适用CreateTopic于 S AP 的Amazon SDK ABAP API 参考

注意

您也可以使用另一个账户中的 Amazon SNS 主题,但在这种情况下,您可能需要为该主题创建策略以便向 Amazon Config授予访问权限。有关向 Amazon SNS 主题授予访问权限的信息,请参阅 Amazon SNS 主题的权限,然后转至 创建 IAM 角色

创建 IAM 角色

您可以使用 IAM 控制台创建一个 IAM 角色,该角色授予访问您的 Amazon S3 存储桶、访问您的 Amazon SNS 主题以及获取支持 Amazon 资源的配置详细信息的 Amazon Config 权限。当您使用控制台创建 IAM 角色时, Amazon Config 会自动为您将必需权限附加到该角色。

注意

如果您使用的是使用的 Amazon 服务 Amazon Config (例如 Sec Amazon urity Hub 或 Cont Amazon rol Tower),并且已经创建了角色,则应确保在设置时使用的 IAM 角色与已创建的 Amazon Config 角色 Amazon Config 保持相同的最低权限,以便其他 Amazon 服务继续按预期运行。 Amazon Config

例如,如果 Cont Amazon rol Tower 有一个 Amazon Config 允许读取 Amazon S3 对象的 IAM 角色,则应保证在设置时使用的 IAM 角色中授予的权限相同 Amazon Config。否则,它可能会干扰 Amazon 控制塔的运行。

有关的 IAM 角色的更多信息 Amazon Config,请参阅 Ident Amazon ity and Access 管理

为 Amazon 服务创建角色
  1. 登录 Amazon Web Services Management Console 并打开 IAM 控制台,网址为 https://console.aws.amazon.com/iam/

  2. 在 IAM 控制台的导航窗格中,选择角色,然后选择创建角色

  3. 对于选择可信实体,选择 Amazon 服务

  4. 选择你想要的用例 Amazon Config:Config-可自定义、Config-OrganizationsCon fig 或 Config-Conformance Packs。然后选择下一步

  5. 命名、查看和创建页面上,查看有关您的角色的详细信息,然后选择创建角色

要使用 S Amazon DK,必须使用您的凭据对其进行配置。有关更多信息,请参阅 Amazon 开发工具包和工具参考指南中的共享配置和凭证文件

以下代码示例演示如何使用 CreateRole

.NET
Amazon SDK for .NET
注意

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

/// <summary> /// Create a new IAM role. /// </summary> /// <param name="roleName">The name of the IAM role.</param> /// <param name="rolePolicyDocument">The name of the IAM policy document /// for the new role.</param> /// <returns>The Amazon Resource Name (ARN) of the role.</returns> public async Task<string> CreateRoleAsync(string roleName, string rolePolicyDocument) { var request = new CreateRoleRequest { RoleName = roleName, AssumeRolePolicyDocument = rolePolicyDocument, }; var response = await _IAMService.CreateRoleAsync(request); return response.Role.Arn; }
  • 有关 API 的详细信息,请参阅 Amazon SDK for .NET API 参考CreateRole中的。

Bash
Amazon CLI 使用 Bash 脚本
注意

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

############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################### # function iam_create_role # # This function creates an IAM role. # # Parameters: # -n role_name -- The name of the IAM role. # -p policy_json -- The assume role policy document. # # Returns: # The ARN of the role. # And: # 0 - If successful. # 1 - If it fails. ############################################################################### function iam_create_role() { local role_name policy_document response local option OPTARG # Required to use getopts command in a function. # bashsupport disable=BP5008 function usage() { echo "function iam_create_user_access_key" echo "Creates an AWS Identity and Access Management (IAM) role." echo " -n role_name The name of the IAM role." echo " -p policy_json -- The assume role policy document." echo "" } # Retrieve the calling parameters. while getopts "n:p:h" option; do case "${option}" in n) role_name="${OPTARG}" ;; p) policy_document="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$role_name" ]]; then errecho "ERROR: You must provide a role name with the -n parameter." usage return 1 fi if [[ -z "$policy_document" ]]; then errecho "ERROR: You must provide a policy document with the -p parameter." usage return 1 fi response=$(aws iam create-role \ --role-name "$role_name" \ --assume-role-policy-document "$policy_document" \ --output text \ --query Role.Arn) local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports create-role operation failed.\n$response" return 1 fi echo "$response" return 0 }
  • 有关 API 的详细信息,请参阅Amazon CLI 命令参考CreateRole中的。

C++
SDK for C++
注意

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

bool AwsDoc::IAM::createIamRole( const Aws::String &roleName, const Aws::String &policy, const Aws::Client::ClientConfiguration &clientConfig) { Aws::IAM::IAMClient client(clientConfig); Aws::IAM::Model::CreateRoleRequest request; request.SetRoleName(roleName); request.SetAssumeRolePolicyDocument(policy); Aws::IAM::Model::CreateRoleOutcome outcome = client.CreateRole(request); if (!outcome.IsSuccess()) { std::cerr << "Error creating role. " << outcome.GetError().GetMessage() << std::endl; } else { const Aws::IAM::Model::Role iamRole = outcome.GetResult().GetRole(); std::cout << "Created role " << iamRole.GetRoleName() << "\n"; std::cout << "ID: " << iamRole.GetRoleId() << "\n"; std::cout << "ARN: " << iamRole.GetArn() << std::endl; } return outcome.IsSuccess(); }
  • 有关 API 的详细信息,请参阅 Amazon SDK for C++ API 参考CreateRole中的。

CLI
Amazon CLI

示例 1:创建 IAM 角色

以下 create-role 命令将创建一个名为 Test-Role 的角色并对其附加信任策略。

aws iam create-role \ --role-name Test-Role \ --assume-role-policy-document file://Test-Role-Trust-Policy.json

输出:

{ "Role": { "AssumeRolePolicyDocument": "<URL-encoded-JSON>", "RoleId": "AKIAIOSFODNN7EXAMPLE", "CreateDate": "2013-06-07T20:43:32.821Z", "RoleName": "Test-Role", "Path": "/", "Arn": "arn:aws:iam::123456789012:role/Test-Role" } }

信任策略在 Test-Role-Trust-Policy.json 文件中定义为 JSON 文档。(文件名和扩展名没有意义。) 信任策略必须指定主体。

要将权限策略附加到角色,请使用 put-role-policy 命令。

有关更多信息,请参阅《Amazon IAM 用户指南》中的创建 IAM 角色

示例 2:创建具有指定最长会话持续时间的 IAM 角色

以下 create-role 命令将创建一个名为 Test-Role 的角色,并将最长会话持续时间设置为 7200 秒(2 小时)。

aws iam create-role \ --role-name Test-Role \ --assume-role-policy-document file://Test-Role-Trust-Policy.json \ --max-session-duration 7200

输出:

{ "Role": { "Path": "/", "RoleName": "Test-Role", "RoleId": "AKIAIOSFODNN7EXAMPLE", "Arn": "arn:aws:iam::12345678012:role/Test-Role", "CreateDate": "2023-05-24T23:50:25+00:00", "AssumeRolePolicyDocument": { "Version": "2012-10-17", "Statement": [ { "Sid": "Statement1", "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::12345678012:root" }, "Action": "sts:AssumeRole" } ] } } }

有关更多信息,请参阅 I Amazon AM 用户指南中的修改角色最长会话持续时间 (Amazon API)

示例 3:创建带有标签的 IAM 角色

以下命令将创建带有标签的 IAM 角色 Test-Role。此示例使用带有以下 JSON 格式标签的 --tags 参数标志:'{"Key": "Department", "Value": "Accounting"}' '{"Key": "Location", "Value": "Seattle"}'。或者,--tags 标志可与简写格式的标签一起使用:'Key=Department,Value=Accounting Key=Location,Value=Seattle'

aws iam create-role \ --role-name Test-Role \ --assume-role-policy-document file://Test-Role-Trust-Policy.json \ --tags '{"Key": "Department", "Value": "Accounting"}' '{"Key": "Location", "Value": "Seattle"}'

输出:

{ "Role": { "Path": "/", "RoleName": "Test-Role", "RoleId": "AKIAIOSFODNN7EXAMPLE", "Arn": "arn:aws:iam::123456789012:role/Test-Role", "CreateDate": "2023-05-25T23:29:41+00:00", "AssumeRolePolicyDocument": { "Version": "2012-10-17", "Statement": [ { "Sid": "Statement1", "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::123456789012:root" }, "Action": "sts:AssumeRole" } ] }, "Tags": [ { "Key": "Department", "Value": "Accounting" }, { "Key": "Location", "Value": "Seattle" } ] } }

有关更多信息,请参阅《Amazon IAM 用户指南》中的标记 IAM 角色

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

Go
适用于 Go V2 的 SDK
注意

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

// RoleWrapper encapsulates AWS Identity and Access Management (IAM) role actions // used in the examples. // It contains an IAM service client that is used to perform role actions. type RoleWrapper struct { IamClient *iam.Client } // CreateRole creates a role that trusts a specified user. The trusted user can assume // the role to acquire its permissions. // PolicyDocument shows how to work with a policy document as a data structure and // serialize it to JSON by using Go's JSON marshaler. func (wrapper RoleWrapper) CreateRole(roleName string, trustedUserArn string) (*types.Role, error) { var role *types.Role trustPolicy := PolicyDocument{ Version: "2012-10-17", Statement: []PolicyStatement{{ Effect: "Allow", Principal: map[string]string{"AWS": trustedUserArn}, Action: []string{"sts:AssumeRole"}, }}, } policyBytes, err := json.Marshal(trustPolicy) if err != nil { log.Printf("Couldn't create trust policy for %v. Here's why: %v\n", trustedUserArn, err) return nil, err } result, err := wrapper.IamClient.CreateRole(context.TODO(), &iam.CreateRoleInput{ AssumeRolePolicyDocument: aws.String(string(policyBytes)), RoleName: aws.String(roleName), }) if err != nil { log.Printf("Couldn't create role %v. Here's why: %v\n", roleName, err) } else { role = result.Role } return role, err }
  • 有关 API 的详细信息,请参阅 Amazon SDK for Go API 参考CreateRole中的。

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

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

import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import software.amazon.awssdk.services.iam.model.CreateRoleRequest; import software.amazon.awssdk.services.iam.model.CreateRoleResponse; import software.amazon.awssdk.services.iam.model.IamException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.iam.IamClient; import java.io.FileReader; /* * This example requires a trust policy document. For more information, see: * https://aws.amazon.com/blogs/security/how-to-use-trust-policies-with-iam-roles/ * * * In addition, set up your development environment, including your credentials. * * For information, see this documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class CreateRole { public static void main(String[] args) throws Exception { final String usage = """ Usage: <rolename> <fileLocation>\s Where: rolename - The name of the role to create.\s fileLocation - The location of the JSON document that represents the trust policy.\s """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String rolename = args[0]; String fileLocation = args[1]; Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() .region(region) .build(); String result = createIAMRole(iam, rolename, fileLocation); System.out.println("Successfully created user: " + result); iam.close(); } public static String createIAMRole(IamClient iam, String rolename, String fileLocation) throws Exception { try { JSONObject jsonObject = (JSONObject) readJsonSimpleDemo(fileLocation); CreateRoleRequest request = CreateRoleRequest.builder() .roleName(rolename) .assumeRolePolicyDocument(jsonObject.toJSONString()) .description("Created using the AWS SDK for Java") .build(); CreateRoleResponse response = iam.createRole(request); System.out.println("The ARN of the role is " + response.role().arn()); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } public static Object readJsonSimpleDemo(String filename) throws Exception { FileReader reader = new FileReader(filename); JSONParser jsonParser = new JSONParser(); return jsonParser.parse(reader); } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for Java 2.x API 参考CreateRole中的。

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

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

创建角色。

import { CreateRoleCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} roleName */ export const createRole = (roleName) => { const command = new CreateRoleCommand({ AssumeRolePolicyDocument: JSON.stringify({ Version: "2012-10-17", Statement: [ { Effect: "Allow", Principal: { Service: "lambda.amazonaws.com", }, Action: "sts:AssumeRole", }, ], }), RoleName: roleName, }); return client.send(command); };
  • 有关 API 的详细信息,请参阅 Amazon SDK for JavaScript API 参考CreateRole中的。

PHP
适用于 PHP 的 SDK
注意

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

$uuid = uniqid(); $service = new IAMService(); $assumeRolePolicyDocument = "{ \"Version\": \"2012-10-17\", \"Statement\": [{ \"Effect\": \"Allow\", \"Principal\": {\"AWS\": \"{$user['Arn']}\"}, \"Action\": \"sts:AssumeRole\" }] }"; $assumeRoleRole = $service->createRole("iam_demo_role_$uuid", $assumeRolePolicyDocument); echo "Created role: {$assumeRoleRole['RoleName']}\n"; /** * @param string $roleName * @param string $rolePolicyDocument * @return array * @throws AwsException */ public function createRole(string $roleName, string $rolePolicyDocument) { $result = $this->customWaiter(function () use ($roleName, $rolePolicyDocument) { return $this->iamClient->createRole([ 'AssumeRolePolicyDocument' => $rolePolicyDocument, 'RoleName' => $roleName, ]); }); return $result['Role']; }
  • 有关 API 的详细信息,请参阅 Amazon SDK for PHP API 参考CreateRole中的。

PowerShell
用于 PowerShell

示例 1:此示例创建一个名为 MyNewRole 的新角色,并将文件 NewRoleTrustPolicy.json 中的策略附加到该角色。请注意,必须使用 -Raw 开关参数才能成功处理 JSON 策略文件。输出中显示的策略文档采用 URL 编码。在本例中,使用 UrlDecode .NET 方法对其进行解码。

$results = New-IAMRole -AssumeRolePolicyDocument (Get-Content -raw NewRoleTrustPolicy.json) -RoleName MyNewRole $results

输出:

Arn : arn:aws:iam::123456789012:role/MyNewRole AssumeRolePolicyDocument : %7B%0D%0A%20%20%22Version%22%3A%20%222012-10-17%22%2C%0D%0A%20%20%22Statement%22 %3A%20%5B%0D%0A%20%20%20%20%7B%0D%0A%20%20%20%20%20%20%22Sid%22%3A%20%22%22%2C %0D%0A%20%20%20%20%20%20%22Effect%22%3A%20%22Allow%22%2C%0D%0A%20%20%20%20%20%20 %22Principal%22%3A%20%7B%0D%0A%20%20%20%20%20%20%20%20%22AWS%22%3A%20%22arn%3Aaws %3Aiam%3A%3A123456789012%3ADavid%22%0D%0A%20%20%20%20%20%20%7D%2C%0D%0A%20%20%20 %20%20%20%22Action%22%3A%20%22sts%3AAssumeRole%22%0D%0A%20%20%20%20%7D%0D%0A%20 %20%5D%0D%0A%7D CreateDate : 4/15/2015 11:04:23 AM Path : / RoleId : V5PAJI2KPN4EAEXAMPLE1 RoleName : MyNewRole [System.Reflection.Assembly]::LoadWithPartialName("System.Web.HttpUtility") [System.Web.HttpUtility]::UrlDecode($results.AssumeRolePolicyDocument) { "Version": "2012-10-17", "Statement": [ { "Sid": "", "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::123456789012:David" }, "Action": "sts:AssumeRole" } ] }
  • 有关 API 的详细信息,请参阅 Amazon Tools for PowerShell Cmdlet 参考CreateRole中的。

Python
SDK for Python (Boto3)
注意

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

def create_role(role_name, allowed_services): """ Creates a role that lets a list of specified services assume the role. :param role_name: The name of the role. :param allowed_services: The services that can assume the role. :return: The newly created role. """ trust_policy = { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": {"Service": service}, "Action": "sts:AssumeRole", } for service in allowed_services ], } try: role = iam.create_role( RoleName=role_name, AssumeRolePolicyDocument=json.dumps(trust_policy) ) logger.info("Created role %s.", role.name) except ClientError: logger.exception("Couldn't create role %s.", role_name) raise else: return role
  • 有关 API 的详细信息,请参阅适用CreateRolePython 的Amazon SDK (Boto3) API 参考

Ruby
适用于 Ruby 的 SDK
注意

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

# Creates a role and attaches policies to it. # # @param role_name [String] The name of the role. # @param assume_role_policy_document [Hash] The trust relationship policy document. # @param policy_arns [Array<String>] The ARNs of the policies to attach. # @return [String, nil] The ARN of the new role if successful, or nil if an error occurred. def create_role(role_name, assume_role_policy_document, policy_arns) response = @iam_client.create_role( role_name: role_name, assume_role_policy_document: assume_role_policy_document.to_json ) role_arn = response.role.arn policy_arns.each do |policy_arn| @iam_client.attach_role_policy( role_name: role_name, policy_arn: policy_arn ) end role_arn rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error creating role: #{e.message}") nil end
  • 有关 API 的详细信息,请参阅 Amazon SDK for Ruby API 参考CreateRole中的。

Rust
适用于 Rust 的 SDK
注意

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

pub async fn create_role( client: &iamClient, role_name: &str, role_policy_document: &str, ) -> Result<Role, iamError> { let response: CreateRoleOutput = loop { if let Ok(response) = client .create_role() .role_name(role_name) .assume_role_policy_document(role_policy_document) .send() .await { break response; } }; Ok(response.role.unwrap()) }
  • 有关 API 的详细信息,请参阅适用CreateRoleRust 的Amazon SDK API 参考

Swift
SDK for Swift
注意

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

注意

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

public func createRole(name: String, policyDocument: String) async throws -> String { let input = CreateRoleInput( assumeRolePolicyDocument: policyDocument, roleName: name ) do { let output = try await client.createRole(input: input) guard let role = output.role else { throw ServiceHandlerError.noSuchRole } guard let id = role.roleId else { throw ServiceHandlerError.noSuchRole } return id } catch { throw error } }
  • 如需了解 API 的详细信息,请参阅适用CreateRole于 S wift 的Amazon SDK API 参考