先决条件 - 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. 通过以下网址打开 Amazon S3 控制台:https://console.aws.amazon.com/s3/

  2. 选择 Create bucket (创建存储桶)

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

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

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

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

    • 不包含大写字符。

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

    创建存储桶后,便无法再更改其名称。确保所选的存储桶名称在 Amazon S3 内所有现有存储桶名称中具有唯一性。有关存储分区命名规则和惯例的更多信息,请参阅存储桶限制在里面Amazon Sonvice 用户指南.

    重要

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

  4. 对于 Region(区域),选择要放置存储桶的Amazon区域。

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

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

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

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

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

      重要

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

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

    有关 S3 对象锁定功能的更多信息,请参阅使用 Amazon S3 对象锁定以锁定对象在里面Amazon Sonvice 用户指南.

  7. 请选择 Create bucket (创建存储桶)

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

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

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

这些 Amazon 软件开发工具包代码示例执行以下任务:

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

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

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

Java

此示例说明如何使用 Amazon SDK for Java 创建 Amazon S3 存储桶。有关创建和测试有效示例的说明,请参阅测试 Amazon S3 Java 代码示例.

import com.amazonaws.AmazonServiceException; import com.amazonaws.SdkClientException; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.regions.Regions; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.s3.model.CreateBucketRequest; import com.amazonaws.services.s3.model.GetBucketLocationRequest; import java.io.IOException; public class CreateBucket2 { public static void main(String[] args) throws IOException { Regions clientRegion = Regions.DEFAULT_REGION; String bucketName = "*** Bucket name ***"; try { AmazonS3 s3Client = AmazonS3ClientBuilder.standard() .withCredentials(new ProfileCredentialsProvider()) .withRegion(clientRegion) .build(); if (!s3Client.doesBucketExistV2(bucketName)) { // Because the CreateBucketRequest object doesn't specify a region, the // bucket is created in the region specified in the client. s3Client.createBucket(new CreateBucketRequest(bucketName)); // Verify that the bucket was created by retrieving it and checking its location. String bucketLocation = s3Client.getBucketLocation(new GetBucketLocationRequest(bucketName)); System.out.println("Bucket location: " + bucketLocation); } } catch (AmazonServiceException e) { // The call was transmitted successfully, but Amazon S3 couldn't process // it and returned an error response. e.printStackTrace(); } catch (SdkClientException e) { // Amazon S3 couldn't be contacted for a response, or the client // couldn't parse the response from Amazon S3. e.printStackTrace(); } } }
.NET

有关如何创建和测试有效示例的信息,请参阅运行 Amazon S3 .NET 代码示例.

using Amazon; using Amazon.S3; using Amazon.S3.Model; using Amazon.S3.Util; using System; using System.Threading.Tasks; namespace Amazon.DocSamples.S3 { class CreateBucketTest { private const string bucketName = "*** bucket name ***"; // Specify your bucket region (an example region is shown). private static readonly RegionEndpoint bucketRegion = RegionEndpoint.USWest2; private static IAmazonS3 s3Client; public static void Main() { s3Client = new AmazonS3Client(bucketRegion); CreateBucketAsync().Wait(); } static async Task CreateBucketAsync() { try { if (!(await AmazonS3Util.DoesS3BucketExistAsync(s3Client, bucketName))) { var putBucketRequest = new PutBucketRequest { BucketName = bucketName, UseClientRegion = true }; PutBucketResponse putBucketResponse = await s3Client.PutBucketAsync(putBucketRequest); } // Retrieve the bucket location. string bucketLocation = await FindBucketLocationAsync(s3Client); } catch (AmazonS3Exception e) { Console.WriteLine("Error encountered on server. Message:'{0}' when writing an object", e.Message); } catch (Exception e) { Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message); } } static async Task<string> FindBucketLocationAsync(IAmazonS3 client) { string bucketLocation; var request = new GetBucketLocationRequest() { BucketName = bucketName }; GetBucketLocationResponse response = await client.GetBucketLocationAsync(request); bucketLocation = response.Location.ToString(); return bucketLocation; } } }
Ruby

有关如何创建和测试有效示例的信息,请参阅使用AmazonSDK for Ruby(版本 3).

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 it's 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 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__

您也可以使用Amazon Command Line Interface (Amazon CLI) 创建 S3 存储桶。有关更多信息,请参阅《Amazon CLI 命令参考》中的 create-bucket

有关 Amazon CLI 的更多信息,请参阅《Amazon Command Line Interface 用户指南》中的什么是 Amazon Command Line Interface?

注意

您也可以使用来自其他账户的 Amazon S3 存储桶,但您可能需要为该存储桶创建策略以授予访问权限Amazon Config. 有关向 Amazon S3 存储桶授予访问的信息,请参阅Amazon S3 存储桶的权限,然后转到创建Amazon SNS 主题.

创建Amazon SNS 主题

如果您的账户中已有 Amazon SNS 主题并要使用它,请跳过此步骤,并转到前往创建 IAM 角色.

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

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

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

    • 如果之前已在您的 Amazon Web Services 账户 下创建主题,请在导航面板上选择 Topics(主题)。

  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 KMSAPI 权限:操作和资源参考在里面Amazon Key Management Service开发人员指南.

      • 默认情况下,Amazon SNS 的 Amazon 托管 CMK(默认)alias/aws/sns 被选择。

        注意

        记住以下内容:

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

        • 或者,您第一次对启用了 SSE 的主题使用 Publish 操作时,Amazon KMS 创建 Amazon SNS 的 Amazon 托管 CMK。

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

        注意

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

      • 要从您的 Amazon 账户或另一个 Amazon 账户中使用使用自定义 CMK ARN,请将其输入到 Customer master key (CMK)(客户主密钥 (CMK))字段中。

  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. 选择 Create topic(创建主题)

    主题已创建并且MyTopic将显示页面。

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

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

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

  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. Kinesis Data Firehose 终端节点数 对于订阅角色 ARN,指定您为写入到 Kinesis Data Firehose 传输流创建的 IAM 角色的 ARN。有关更多信息,请参阅订阅 Kinesis Data Firehose 传输流到 Amazon SNS 主题的先决条件.

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

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

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

    8. 选择 Create subscription(创建订阅)。

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

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

以下代码示例显示如何创建 Amazon SNS 主题。

.NET
Amazon SDK for .NET
提示

要了解如何设置和运行此示例,请参阅GitHub.

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. The example was created /// using the AWS SDK for .NET version 3.7 and .NET Core 5.0. /// </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; } }
  • 有关API详细信息,请参阅CreateTopicAmazon SDK for .NETAPI 参考.

C++
适用于 C++ 的 SDK
提示

要了解如何设置和运行此示例,请参阅GitHub.

Aws::SDKOptions options; Aws::InitAPI(options); { Aws::String topic_name = argv[1]; Aws::SNS::SNSClient sns; Aws::SNS::Model::CreateTopicRequest ct_req; ct_req.SetName(topic_name); auto ct_out = sns.CreateTopic(ct_req); if (ct_out.IsSuccess()) { std::cout << "Successfully created topic " << topic_name << std::endl; } else { std::cout << "Error creating topic " << topic_name << ":" << ct_out.GetError().GetMessage() << std::endl; } } Aws::ShutdownAPI(options);
  • 有关API详细信息,请参阅CreateTopicAmazon SDK for C++API 参考.

Go
SDK for Go V2
提示

要了解如何设置和运行此示例,请参阅GitHub.

  • 有关API详细信息,请参阅CreateTopicAmazon SDK for GoAPI 参考.

Java
SDK for Java 2.x
提示

要了解如何设置和运行此示例,请参阅GitHub.

public static String createSNSTopic(SnsClient snsClient, String topicName ) { CreateTopicResponse result = null; 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详细信息,请参阅CreateTopicAmazon SDK for Java 2.xAPI 参考.

JavaScript
开发工具包适用于 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

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

import { SNSClient } from "@aws-sdk/client-sns"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create SNS service object. const snsClient = new SNSClient({ region: REGION }); export { snsClient };

导入软件开发工具包和客户端模块,然后调用 API。

// Import required AWS SDK clients and commands for Node.js import {CreateTopicCommand } from "@aws-sdk/client-sns"; import {snsClient } from "./libs/snsClient.js"; // Set the parameters const params = { Name: "TOPIC_NAME" }; //TOPIC_NAME const run = async () => { try { const data = await snsClient.send(new CreateTopicCommand(params)); console.log("Success.", data); return data; // For unit tests. } catch (err) { console.log("Error", err.stack); } }; run();
Kotlin
SDK for Kotlin
注意

这是适用于预览版中功能的预发行文档。本文档随时可能更改。

提示

要了解如何设置和运行此示例,请参阅GitHub.

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详细信息,请参阅CreateTopicAmazonSK for Kot LIN API 参考.

PHP
SDK for PHP
提示

要了解如何设置和运行此示例,请参阅GitHub.

require 'vendor/autoload.php'; use Aws\Sns\SnsClient; use Aws\Exception\AwsException; /** * 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
适用于 Python (Boto3) 的 SDK
提示

要了解如何设置和运行此示例,请参阅GitHub.

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详细信息,请参阅CreateTopicAmazonSDK for Python (Boto3) API 参考.

Ruby
SDK for Ruby
提示

要了解如何设置和运行此示例,请参阅GitHub.

require 'aws-sdk-sns' # v2: require 'aws-sdk' def topic_created?(sns_client, topic_name) sns_client.create_topic(name: topic_name) rescue StandardError => e puts "Error while creating the topic named '#{topic_name}': #{e.message}" end # Full example call: def run_me topic_name = 'TOPIC_NAME' region = 'REGION' sns_client = Aws::SNS::Client.new(region: region) puts "Creating the topic '#{topic_name}'..." if topic_created?(sns_client, topic_name) puts 'The topic was created.' else puts 'The topic was not created. Stopping program.' exit 1 end end run_me if $PROGRAM_NAME == __FILE__
Rust
SDK for Rust
注意

本文档适用于预览版中的软件开发工具包。软件开发工具包可能随时发生变化,不应在生产环境中使用。

提示

要了解如何设置和运行此示例,请参阅GitHub.

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详细信息,请参阅CreateTopicAmazonSK for Rust API 参考.

您还可以使用Amazon Command Line Interface(Amazon CLI) 创建 Amazon SNS 主题。有关更多信息,请参阅创建主题在里面Amazon CLI命令参考.

有关 Amazon CLI 的更多信息,请参阅《Amazon Command Line Interface 用户指南》中的什么是 Amazon Command Line Interface?

注意

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

创建 IAM 角色

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

注意

如果您Amazon使用的服务Amazon Config(例如AmazonSecurity Hub 或AmazonControl Tower)和一个Amazon Config角色已创建,您应确保在设置时使用的 IAM 角色Amazon Config保持与已创建的最低权限相同的最低权限Amazon Config按顺序排列另一个角色Amazon服务将继续按预期运行。

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

有关 IAM 角色的更多信息Amazon Config请参请参请参请参请参AmazonIdentity and Access Management.

如需创建角色Amazon服务
  1. 登录Amazon Web Services Management Console,然后通过以下网址打开 IAM 控制台:https://console.aws.amazon.com/iam/

  2. 在 IAM 控制台的导航窗格中,选择 Roles,然后选择 Create role

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

  4. 选择您想要的使用案例Amazon Config:Config,Config-Organizations,Config,或Config-一致性包. 然后选择下一步

  5. 命名、审阅和创建页面,检视有关角色的详细信息,然后选择创建角色.

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

以下代码示例显示如何创建 IAM 角色。

.NET
Amazon SDK for .NET
提示

要了解如何设置和运行此示例,请参阅GitHub.

/// <summary> /// Create a new IAM role which we can attach to a user. /// </summary> /// <param name="client">The initialized IAM client object.</param> /// <param name="roleName">The name of the IAM role to create.</param> /// <param name="rolePermissions">The permissions which the role will have.</param> /// <returns>A Role object representing the newly created role.</returns> public static async Task<Role> CreateRoleAsync( AmazonIdentityManagementServiceClient client, string roleName, string rolePermissions) { var request = new CreateRoleRequest { RoleName = roleName, AssumeRolePolicyDocument = rolePermissions, }; var response = await client.CreateRoleAsync(request); return response.Role; }
  • 有关API详细信息,请参阅CreateRoleAmazon SDK for .NETAPI 参考.

Go
SDK for Go V2
提示

要了解如何设置和运行此示例,请参阅GitHub.

// CreateRole myRole, err := service.CreateRole(context.Background(), &iam.CreateRoleInput{ RoleName: aws.String(ExampleRoleName), Description: aws.String("My super awesome example role"), AssumeRolePolicyDocument: aws.String(`{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "ec2.amazonaws.com" }, "Action": "sts:AssumeRole" } ] }`), }) if err != nil { panic("Couldn't create role: " + err.Error()) } fmt.Println("☑️ Create Role") fmt.Printf("The new role's ARN is %s \n", *myRole.Role.Arn)
  • 有关API详细信息,请参阅CreateRoleAmazon SDK for GoAPI 参考.

Java
SDK for Java 2.x
提示

要了解如何设置和运行此示例,请参阅GitHub.

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详细信息,请参阅CreateRoleAmazon SDK for Java 2.xAPI 参考.

JavaScript
开发工具包适用于 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

import { IAMClient } from "@aws-sdk/client-iam"; // Set the AWS Region. const REGION = "REGION"; // For example, "us-east-1". // Create an IAM service client object. const iamClient = new IAMClient({ region: REGION }); export { iamClient };

创建角色。

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import { CreateRoleCommand } from "@aws-sdk/client-iam"; // Sample assume role policy JSON. const role_json = { Version: "2012-10-17", Statement: [ { Effect: "Allow", Principal: { AWS: "USER_ARN", // The ARN of the user. }, Action: "sts:AssumeRole", }, ], }; // Stringify the assume role policy JSON. const myJson = JSON.stringify(role_json); // Set the parameters. const params = { AssumeRolePolicyDocument: myJson, Path: "/", RoleName: "ROLE_NAME" }; const run = async () => { try { const data = await iamClient.send(new CreateRoleCommand(params)); console.log("Success. Role created. Role Arn: ", data.Role.RoleName); } catch (err) { console.log("Error", err); } }; run();
  • 有关API详细信息,请参阅CreateRoleAmazon SDK for JavaScriptAPI 参考.

PHP
SDK for PHP
提示

要了解如何设置和运行此示例,请参阅GitHub.

$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详细信息,请参阅CreateRoleAmazon SDK for PHPAPI 参考.

Python
适用于 Python (Boto3) 的 SDK
提示

要了解如何设置和运行此示例,请参阅GitHub.

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详细信息,请参阅CreateRoleAmazonSDK for Python (Boto3) API 参考.

Ruby
SDK for Ruby
提示

要了解如何设置和运行此示例,请参阅GitHub.

# Creates a role that can be assumed by a user. # # @param role_name [String] The name to give the role. # @param user [Aws::IAM::User] The user who is granted permission to assume the role. # @return [Aws::IAM::Role] The newly created role. def create_role(role_name, user) role = @iam_resource.create_role( role_name: role_name, assume_role_policy_document: { Version: "2012-10-17", Statement: [{ Effect: "Allow", Principal: {'AWS': user.arn}, Action: "sts:AssumeRole" }] }.to_json) puts("Created role #{role.name}.") rescue Aws::Errors::ServiceError => e puts("Couldn't create a role for the demo. Here's why: ") puts("\t#{e.code}: #{e.message}") raise else role end
  • 有关API详细信息,请参阅CreateRoleAmazon SDK for RubyAPI 参考.

Rust
SDK for Rust
注意

本文档适用于预览版中的软件开发工具包。软件开发工具包可能随时发生变化,不应在生产环境中使用。

提示

要了解如何设置和运行此示例,请参阅GitHub.

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详细信息,请参阅CreateRoleAmazonSK for Rust API 参考.

您还可以使用Amazon Command Line Interface(Amazon CLI)创建 IAM 角色。有关更多信息,请参阅create-role在里面Amazon CLI命令参考. 然后,您可以使用以下命令将策略附加到该角色attach-role-policy命令。

有关 Amazon CLI 的更多信息,请参阅《Amazon Command Line Interface 用户指南》中的什么是 Amazon Command Line Interface?