

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

# 入门AWS Config
<a name="getting-started"></a>

AWS Config提供了中AWS资源配置的详细视图AWS 账户。借AWS Config助，您可以查看配置和AWS资源之间关系的变化，浏览资源配置历史记录，并使用规则来确定合规性。有关更多信息，请参阅[什么是AWS Config？](https://docs.aws.amazon.com/config/latest/developerguide/WhatIsConfig.html) 以及[AWS Config工作原理](https://docs.aws.amazon.com/config/latest/developerguide/how-does-config-work.html)。

## 报名参加AWS
<a name="getting-started-signing-up"></a>

**Topics**
+ [注册获取AWS 账户](#sign-up-for-aws)
+ [创建具有管理访问权限的用户](#create-an-admin)

### 注册获取AWS 账户
<a name="sign-up-for-aws"></a>

如果您没有AWS 账户，请完成以下步骤来创建一个。

**报名参加AWS 账户**

1. 打开[https://portal.aws.amazon.com/billing/注册。](https://portal.aws.amazon.com/billing/signup)

1. 按照屏幕上的说明操作。

   在注册时，将接到电话或收到短信，要求使用电话键盘输入一个验证码。

   当您注册时AWS 账户，就会创建*AWS 账户根用户*一个。根用户有权访问该账户中的所有AWS 服务和资源。作为最佳安全实践，请为用户分配管理访问权限，并且只使用根用户来执行[需要根用户访问权限的任务](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html#root-user-tasks)。

AWS注册过程完成后会向您发送一封确认电子邮件。您可以随时前往 [https://aws.amazon.com/](https://aws.amazon.com/)并选择 “**我的账户”，查看您当前的账户活动并管理您的账户**。

### 创建具有管理访问权限的用户
<a name="create-an-admin"></a>

注册后，请保护您的安全AWS 账户AWS 账户根用户AWS IAM Identity Center，启用并创建管理用户，这样您就不会使用 root 用户执行日常任务。

**保护你的AWS 账户根用户**

1.  选择 **Root 用户**并输入您的AWS 账户电子邮件地址，以账户所有者的身份登录。[AWS 管理控制台](https://console.aws.amazon.com/)在下一页上，输入您的密码。

   要获取使用根用户登录方面的帮助，请参阅《AWS 登录用户指南》**中的 [Signing in as the root user](https://docs.aws.amazon.com/signin/latest/userguide/console-sign-in-tutorials.html#introduction-to-root-user-sign-in-tutorial)。

1. 为您的根用户启用多重身份验证（MFA）。

   有关说明，请参阅 I [A *M* 用户指南中的为AWS 账户根用户启用虚拟 MFA 设备（控制台）](https://docs.aws.amazon.com/IAM/latest/UserGuide/enable-virt-mfa-for-root.html)。

**创建具有管理访问权限的用户**

1. 启用 IAM Identity Center。

   有关说明，请参阅**《AWS IAM Identity Center用户指南》中的 [Enabling。AWS IAM Identity Center](https://docs.aws.amazon.com//singlesignon/latest/userguide/get-set-up-for-idc.html)

1. 在 IAM Identity Center 中，为用户授予管理访问权限。

   有关使用IAM Identity Center 目录作为身份源的教程，请参阅《[用户*指南》IAM Identity Center 目录中的使用默认设置配置AWS IAM Identity Center用户*访问权限](https://docs.aws.amazon.com//singlesignon/latest/userguide/quick-start-default-idc.html)。

**以具有管理访问权限的用户身份登录**
+ 要使用您的 IAM Identity Center 用户身份登录，请使用您在创建 IAM Identity Center 用户时发送到您的电子邮件地址的登录 URL。

  有关使用 IAM Identity Center 用户[登录的帮助，请参阅*AWS 登录用户指南*中的登录AWS访问门户](https://docs.aws.amazon.com/signin/latest/userguide/iam-id-center-sign-in-tutorial.html)。

**将访问权限分配给其他用户**

1. 在 IAM Identity Center 中，创建一个权限集，该权限集遵循应用最低权限的最佳做法。

   有关说明，请参阅《AWS IAM Identity Center用户指南》**中的 [Create a permission set](https://docs.aws.amazon.com//singlesignon/latest/userguide/get-started-create-a-permission-set.html)。

1. 将用户分配到一个组，然后为该组分配单点登录访问权限。

   有关说明，请参阅《AWS IAM Identity Center用户指南》**中的 [Add groups](https://docs.aws.amazon.com//singlesignon/latest/userguide/addgroups.html)。

## 入门方法AWS Config
<a name="getting-started-using-aws-config"></a>

注册后AWS 账户，您可以开始AWS Config使用AWS 管理控制台、AWS CLI 或AWS SDKs。

**Topics**
+ [使用控制AWS Config台进行设置](https://docs.aws.amazon.com/config/latest/developerguide/gs-console.html)
+ [AWS Config使用进行设置AWS CLI](https://docs.aws.amazon.com/config/latest/developerguide/gs-cli.html)
+ [在AWS SDK 中使用AWS Config服务](https://docs.aws.amazon.com/config/latest/developerguide/sdk-general-information-section.html)

# 使用控制台设置 AWS Config
<a name="gs-console"></a>

AWS 管理控制台提供了一个快速、简化的 AWS Config 设置流程。

## 设置
<a name="gs-console-setting-up.title"></a>

**使用控制台设置 AWS Config**

1. 登录到，AWS 管理控制台然后通过以下网址打开 AWS Config 控制台：[https://console.aws.amazon.com/config/home](https://console.aws.amazon.com/config/home)。

1. 如果这是您首次打开 AWS Config 控制台或在新区域中设置，AWS ConfigAWS Config 控制台页面的外观与以下类似：  
![\[AWS Config 控制台页面上的图像概述了 AWS Config 服务，强调了该服务在记录和评估 AWS 资源配置变更中的作用。\]](http://docs.aws.amazon.com/zh_cn/config/latest/developerguide/images/welcome.png)

1. 根据 AWS 最佳实践选择 **一键设置**以启动。AWS Config您也可以选择**开始使用**来完成更详细的设置过程。

**Topics**
+ [设置](#gs-console-setting-up.title)
+ [一键设置](1-click-setup.md)
+ [手动设置](manual-setup.title.md)

# 一键设置 AWS Config
<a name="1-click-setup"></a>

AWS Config 通过减少手动选择的数量，**一键设置**有助于简化 AWS Config 主机客户的入门流程。要完成设置过程的所有手动选择，请参阅[手动设置](https://docs.aws.amazon.com/config/latest/developerguide/detailed-setup.html)。

**使用 “ AWS Config 一**键**设置” 在主机上进行设置**

1. 登录 AWS 管理控制台 并在家中打开[https://console.aws.amazon.com/config/主 AWS Config](https://console.aws.amazon.com/config/home)机。

1. 选择**一键设置**。

设置页面包括三个步骤，但是通过**一键设置**工作流，您将被自动定向到步骤 3（查看）。下面详细列出了这些步骤。
+ **设置**：选择 AWS Config 控制台记录资源和角色的方式，并选择配置历史记录和配置快照文件的发送位置。
+ **规则**：对于 AWS 区域 该支持 AWS Config 规则，您可以通过此步骤配置可以添加到您的账户的初始托管规则。设置完成后， AWS Config 将根据您选择的规则评估您的 AWS 资源。设置完成后，可以创建其他规则，您账户中的现有规则也会更新。
+ **查看**：验证您的设置详细信息。

## 步骤 1：设置
<a name="1-click-setup-settings.title"></a>

### 记录策略
<a name="1-click-setup-settings-recording-strategy.title"></a>

为您选择了**使用可自定义覆盖项记录所有资源类型的**选项。 AWS Config 将记录该区域所有当前和 future 支持的资源类型。有关更多信息，请参阅[支持的资源类型](https://docs.aws.amazon.com/config/latest/developerguide/resource-config-reference.html)。
+ **默认设置**

  默认记录频率已设置为**持续**。这意味着每当发生更改时，都会持续 AWS Config 记录配置更改。

  AWS Config 还支持将录制频率设置为 “**每日**” 的选项。如果您在设置之后选择该选项，将会收到代表过去 24 小时内资源最新状态的配置项（CI），前提是它与之前记录的 CI 不同。有关更多信息，请参阅[记录频率](https://docs.aws.amazon.com/config/latest/developerguide/select-resources.html#select-resources-recording-frequency)。
**注意**  
AWS Firewall Manager 依赖于持续录制来监控您的资源。如果您使用的是 Firewall Manager，建议您将记录频率设置为“持续”。
+ **覆盖设置 – *可选***

  您可以选择在设置完成后覆盖特定资源类型的记录频率，或从记录中排除特定资源类型。要覆盖默认设置，请在 AWS Config 控制台左侧导航栏中选择 **“设置**”，然后选择 “**编辑”**。

#### 记录资源时的注意事项
<a name="1-click-setup-considerations"></a>

** AWS Config 评估次数多**

与随后的几个月相比，您可能会注意到，在使用 AWS Config 记录的第一个月份中，您的账户活动有所增加。在初始引导过程中， AWS Config 会对您账户中您选择 AWS Config 要记录的所有资源进行评估。

如果您运行的是临时工作负载，则可能会看到 AWS Config 中的活动增加，因为它会记录与创建和删除这些临时资源相关的配置更改。*临时工作负载* 是临时使用在需要时加载和运行的计算资源。示例包括 Amazon Elastic Compute Cloud（Amazon EC2）竞价型实例、Amazon EMR 任务和。 AWS Auto Scaling如果您想避免因运行临时工作负载而导致活动增加，则可以设置配置记录器，将这些资源类型排除在记录范围之外，或者在单独的账户中运行这些类型的工作负载，同时将 AWS Config 关闭，以避免增加配置记录和规则评估。

**全局资源类型 \$1 Aurora 全局集群最初包含在记录范围内**

`AWS::RDS::GlobalCluster`资源类型将在启用配置记录器的所有支持 AWS Config 区域中进行记录。

如果您不想在所有已启用的区域中记录，`AWS::RDS::GlobalCluster`可以在设置完成后将此资源类型排除在记录范围之外。在左侧导航栏中选择**设置**，然后选择**编辑**。从**编辑**菜单转到**记录方法**部分的**覆盖设置**，选择 `AWS::RDS::GlobalCluster`，然后选择“从记录中排除”覆盖方法。

**全局资源类型 \$1 IAM 资源类型最初不包含在记录范围内**

为了帮您降低成本，“所有全局记录的 IAM 资源类型”最初都不包含在记录范围内。此捆绑包包括 IAM 用户、组、角色和客户管理型策略。选择**移除**以删除覆盖，并将这些资源包含在您的记录范围内。

此外， AWS Config 在 2022 年 2 月之后提供支持的区域中，无法记录以下全局 IAM 资源类型：`AWS::IAM::User`、`AWS::IAM::Group`、`AWS::IAM::Role` 和 `AWS::IAM::Policy`。有关这些区域的列表，请参阅[录制 AWS 资源 \$1 全球资源](https://docs.aws.amazon.com/config/latest/developerguide/select-resources.html#select-resources-all)。

### 数据治理
<a name="1-click-setup-data-governance"></a>

本节为您选择了将 AWS Config 数据保留7年（2557天）的默认数据保留期。

已为您选择 “**使用现有 AWS Config 服务相关角色**” 选项并将其设置为该**AWS Config 角色**。服务相关角色由服务预定义 AWS Config ，包括该服务调用其他 AWS 服务所需的所有权限。

### 传送方式
<a name="1-click-setup-data-delivery-method"></a>

在本部分中为您选择了**从您的账户中选择一个存储桶**选项。此选项将默认为您账户中以 `config-bucket-accountid` 格式命名的存储桶。例如 `config-bucket-012345678901`。如果您没有以这种格式创建存储桶，则会为您创建一个这种格式的存储桶。如果希望创建自己的存储桶，请参阅《Amazon Simple Storage Service 用户指南》**中的[创建存储桶](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket-overview.html)。

有关 S3 存储桶的更多信息，请参阅《Amazon Simple Storage Service（Amazon S3）用户指南**》中的[存储桶概述](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingBucket.html)。

## 步骤 2：规则
<a name="1-click-setup-rules.title"></a>

根据 **AWS 托管规则**，此步骤未为您选择任何规则。但我们鼓励您在完成账户设置后创建和更新规则。

## 第 3 步：查看
<a name="1-click-setup-review.title"></a>

查看您的 AWS Config 设置详细信息。您可以返回编辑每个部分中所做的更改。选择 “**确认**” 以完成设置 AWS Config。

# 的手动设置 AWS Config
<a name="manual-setup.title"></a>

**使用 Get** started 工作流程，您可以完成设置过程的所有手动选择以开始使用 AWS Config 控制台。有关简化的入门流程，请参阅[一键设置](https://docs.aws.amazon.com/config/latest/developerguide/1-click-setup.html)。

**使用 “**入门**” 在控制台上 AWS Config 进行设置**

1. 登录 AWS 管理控制台 并在家中打开[https://console.aws.amazon.com/config/主 AWS Config](https://console.aws.amazon.com/config/home)机。

1. 选择**开始**。

设置页面包括三个步骤。下文详细介绍了您选择**入门**之后的该过程。
+ **设置**：选择 AWS Config 控制台记录资源和角色的方式，并选择配置历史记录和配置快照文件的发送位置。
+ **规则**：对于 AWS 区域 该支持 AWS Config 规则，您可以通过此步骤配置可以添加到您的账户的初始托管规则。设置完成后， AWS Config 将根据您选择的规则评估您的 AWS 资源。设置完成后，可以创建其他规则，您账户中的现有规则也会更新。
+ **查看**：验证您的设置详细信息。

## 步骤 1：设置
<a name="gs-settings.title"></a>

### 记录策略
<a name="manual-setup-settings-recording-strategy.title"></a>

在**记录方法**部分，选择记录策略。您可以指定 AWS Config 要记录的 AWS 资源。

------
#### [ All resource types with customizable overrides ]

设置 AWS Config 为记录该区域所有当前和 future 支持的资源类型的配置更改。您可以覆盖特定资源类型的记录频率，也可以从记录中排除特定资源类型。有关更多信息，请参阅[支持的资源类型](https://docs.aws.amazon.com/config/latest/developerguide/resource-config-reference.html)。
+ **默认设置**

  为所有当前和未来支持的资源类型配置默认记录频率。有关更多信息，请参阅[记录频率](https://docs.aws.amazon.com/config/latest/developerguide/select-resources.html#select-resources-recording-frequency)。
  + 连续录制 — AWS Config 每当发生更改时，都会持续记录配置更改。
  + 每日记录 - 您会收到代表过去 24 小时内资源的最新状态的配置项（CI），前提是它与之前记录的 CI 不同。
**注意**  
AWS Firewall Manager 依赖于持续录制来监控您的资源。如果您使用的是 Firewall Manager，建议您将记录频率设置为“持续”。
+ **覆盖设置**

  覆盖特定资源类型的记录频率，或从记录中排除特定资源类型。如果您更改某一资源类型的记录频率或停止记录某一资源类型，则已记录的配置项会保持不变。

------
#### [ Specific resource types ]

设置 AWS Config 为仅记录您指定的资源类型的配置更改。
+ **特定的资源类型**

  选择要记录的资源类型及其频率。有关更多信息，请参阅[记录频率](https://docs.aws.amazon.com/config/latest/developerguide/select-resources.html#select-resources-recording-frequency)。
  + 连续录制 — AWS Config 每当发生更改时，都会持续记录配置更改。
  + 每日记录 - 您会收到代表过去 24 小时内资源的最新状态的配置项（CI），前提是它与之前记录的 CI 不同。
**注意**  
AWS Firewall Manager 依赖于持续录制来监控您的资源。如果您使用的是 Firewall Manager，建议您将记录频率设置为“持续”。

  如果您更改某一资源类型的记录频率或停止记录某一资源类型，则已记录的配置项会保持不变。

------

#### 记录资源时的注意事项
<a name="manual-setup-considerations"></a>

** AWS Config 评估次数多**

与随后的几个月相比，您可能会注意到，在使用 AWS Config 记录的第一个月份中，您的账户活动有所增加。在初始引导过程中， AWS Config 会对您账户中您选择 AWS Config 要记录的所有资源进行评估。

如果您运行的是临时工作负载，则可能会看到 AWS Config 中的活动增加，因为它会记录与创建和删除这些临时资源相关的配置更改。*临时工作负载* 是临时使用在需要时加载和运行的计算资源。示例包括亚马逊弹性计算云 (Amazon EC2) 竞价型实例、亚马逊 EMR 任务和。 AWS Auto Scaling如果您想避免因运行临时工作负载而导致活动增加，则可以设置配置记录器，将这些资源类型排除在记录范围之外，或者在单独的账户中运行这些类型的工作负载，同时将 AWS Config 关闭，以避免增加配置记录和规则评估。

------
#### [ Considerations: All resource types with customizable overrides ]

**全局记录的资源类型 \$1 Aurora 全局集群最初包含在记录范围内**

`AWS::RDS::GlobalCluster`资源类型将在启用配置记录器的所有支持 AWS Config 区域中进行记录。

如果您不想在所有已启用的区域中记录，`AWS::RDS::GlobalCluster`请选择“AWS RDS GlobalCluster”，然后选择“从记录中排除”覆盖方法。

**全局资源类型 \$1 IAM 资源类型最初不包含在记录范围内**

为了帮您降低成本，全局 IAM 资源类型最初将不包含在记录范围内。此捆绑包包括 IAM 用户、组、角色和客户管理型策略。选择**移除**以删除覆盖，并将这些资源包含在您的记录范围内。

此外，全球 IAM 资源类型（`AWS::IAM::User``AWS::IAM::Group`、`AWS::IAM::Role`、和`AWS::IAM::Policy`）不能记录在 2022 年 2 月 AWS Config 之后支持的区域中。有关这些区域的列表，请参阅[录制 AWS 资源 \$1 全球资源](https://docs.aws.amazon.com/config/latest/developerguide/select-resources.html#select-resources-all)。

**限制**

您可以添加最多 100 项频率覆盖和 600 项排除覆盖。

无法为以下资源类型指定每日记录：
+ `AWS::Config::ResourceCompliance`
+ `AWS::Config::ConformancePackCompliance`
+ `AWS::Config::ConfigurationRecorder`

------
#### [ Considerations: Specific resource types ]

**区域可用性**

在指定 AWS Config 要跟踪的资源类型之前，请检查[按区域可用性划分的资源覆盖率](https://docs.aws.amazon.com/config/latest/developerguide/what-is-resource-config-coverage.html)，以查看您设置的 AWS 区域是否支持该资源类型 AWS Config。如果至少有一个区域支持某种资源类型，则即使您设置的区域不支持指定的资源类型 AWS Config，您也可以在支持的所有 AWS 区域中启用该资源类型的记录 AWS Config。 AWS Config 

**限制**

如果所有资源类型的频率都相同，则没有限制。如果至少将一种资源类型设置为“持续”，则最多可以添加 100 种频率为“每日”的资源类型。

以下资源类型不支持“每日”频率：
+ `AWS::Config::ResourceCompliance`
+ `AWS::Config::ConformancePackCompliance`
+ `AWS::Config::ConfigurationRecorder`

------

### 数据治理
<a name="manual-setup-data-governance"></a>
+ 对于**数据保留期**，选择默认保留期以将 AWS Config 数据保留 7 年 (2557)，或者为记录的项目设置自定义保留期。 AWS Config

  AWS Config 允许您通过为自己的数据指定保留期来删除数据`ConfigurationItems`。指定保留期后， AWS Config 会将您的 `ConfigurationItems` 保留指定的时间段。您可以选择最少 30 天到最长 7 年（2557 天）之间的时间段。 AWS Config 删除早于您指定保留期的数据。
+ 对于**的 IAM 角色 AWS Config**，请从您的账户中选择现有的 AWS Config 服务相关角色或一个 IAM 角色。
  + 服务相关角色由服务预定义 AWS Config ，包括该服务调用其他 AWS 服务所需的所有权限。
**注意**  
**推荐：使用服务相关角色**  
建议您使用服务相关角色。服务相关角色可添加 AWS Config 按预期运行所需的所有必要权限。
  + 否则，请从现有的角色和权限策略中选择一个 IAM 角色。
**注意**  
**策略与合规结果**  
[在中管理@@ [的 IAM 策略](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)和其他策略 AWS Organizations](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies.html)可能会影响是否 AWS Config 有权记录资源的配置更改。此外，规则会直接评估资源的配置，且执行评估时不会考虑这些策略。确保现行策略与您打算使用 AWS Config的方式保持一致。  
**重用 IAM 角色时保留最低权限**  
如果您使用的是使用 AWS Security Hub CSPM 或之类的 AWS 服务 AWS Config AWS Control Tower，并且已经创建了 IAM 角色，请确保您在设置时使用的 IAM 角色 AWS Config 保持与先前存在的 IAM 角色相同的最低权限。您必须这样做才能确保其他 AWS 服务继续按预期运行。  
例如，如果 AWS Control Tower 拥有允许 AWS Config 读取 S3 对象的 IAM 角色，请确保向设置时使用的 IAM 角色授予相同的权限 AWS Config。否则，它可能会干扰 AWS Control Tower 工作方式。

### 传送方式
<a name="manue-setup-data-delivery-method"></a>
+ 对于**传送方式**，选择 AWS Config 将配置历史记录和配置快照文件发送到的 S3 存储桶：
  + **创建存储桶** – 对于 **S3 存储桶名称**，键入 S3 存储桶的名称。

    您键入的名称在 Amazon S3 中所有现有的存储桶名称中必须唯一。添加前缀（例如，您所在组织的名称）是确保唯一性的一种方法。存储桶创建完毕后，您无法更改其名称。有关更多信息，请参阅《Amazon Simple Storage Service 用户指南》**中的[存储桶限制](https://docs.aws.amazon.com/AmazonS3/latest/userguide/BucketRestrictions.html)。
  + **从您的账户选择一个存储桶** – 对于 **S3 存储桶名称**，选择您的首选存储桶。
  + **从另一账户选择存储桶** – 对于 **S3 存储桶名称**，键入存储桶名称。
**注意**  
**存储桶权限**  
如果您从其他账户中选择存储桶，则该存储桶必须具有授予访问权限的策略 AWS Config。有关更多信息，请参阅 [AWS Config 传送渠道的 Amazon S3 存储桶的权限](s3-bucket-policy.md)。
+ 对于 **Amazon SNS 主题**，选择将**配置更改和通知流式传输到 Amazon SNS** 主题，以便 AWS Config 发送配置历史传送、配置快照传输和合规性等通知。
+ 如果您选择 AWS Config 直播某个 Amazon SNS 主题，请选择目标主题：
  + **创建主题** – 对于**主题名称**，键入您的 SNS 主题的名称。
  + **从您的账户选择一个主题** – 对于**主题名称**，选择您的首选主题。
  + **从另一个账户选择一个主题** – 对于**主题 ARN**，键入主题的 Amazon 资源名称（ARN）。如果您从其他账户中选择一个主题，则该主题必须具有授予访问权限的策略 AWS Config。有关更多信息，请参阅 [Amazon SNS 主题的权限](sns-topic-policy.md)。
**注意**  
**Amazon SNS 主题的区域**  
Amazon SNS 主题必须与您设置的区域位于同一区域。 AWS Config

## 步骤 2：规则
<a name="manual-setup-rules.title"></a>

如果您在支持规则 AWS Config 的地区进行设置，请选择**下一步**。

## 第 3 步：查看
<a name="manual-setup-review.title"></a>

查看您的 AWS Config 设置详情。您可以返回编辑每个部分中所做的更改。选择 “**确认**” 以完成设置 AWS Config。

## 有关更多信息
<a name="manual-setup-more-info.title"></a>

有关在账户中查找现有资源和了解资源配置的信息，请参阅[查找资源](https://docs.aws.amazon.com/config/latest/developerguide/looking-up-discovered-resources.html)、[查看合规信息](https://docs.aws.amazon.com/config/latest/developerguide/evaluate-config_view-compliance.html)和[查看合规历史记录](https://docs.aws.amazon.com/config/latest/developerguide/view-manage-resource-console.html)。

您也可以使用 Amazon 简单队列服务以编程方式监控 AWS 资源。有关更多信息，请参阅 [使用 Amazon SQS 监控 AWS 资源变化](monitor-resource-changes.md)。

# 使用 AWS Config 设置 AWS CLI
<a name="gs-cli"></a>

AWS CLI 是用于管理 AWS 服务的统一工具。如果您仅使用一种工具进行下载和配置，则可通过命令行控制多个 AWS 服务并使用脚本来自动执行这些服务。有关 AWS CLI 的更多信息以及 AWS CLI 工具的安装说明，请参阅《*AWS Command Line Interface 用户指南*》中的以下内容。
+ [AWS Command Line Interface《用户指南](https://docs.aws.amazon.com/cli/latest/userguide/)》
+ [开始设置 AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-set-up.html) 

如有必要，请输入 `aws configure` 以将 AWS CLI 配置为使用提供 AWS Config 的 AWS 区域。

## 设置
<a name="gs-cli-setting-up.title"></a>

请参阅以下主题以使用 AWS Config 设置。AWS CLI

**Topics**
+ [设置](#gs-cli-setting-up.title)
+ [先决条件](gs-cli-prereq.md)
+ [启动 AWS Config](gs-cli-subscribe.md)
+ [验证设置](gs-cli-verify-subscribe.md)

# 使用进行设置 AWS Config 的先决条件 AWS CLI
<a name="gs-cli-prereq"></a>

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

**Topics**
+ [步骤 1：创建 Amazon S3 存储桶](#gs-cli-create-s3bucket)
+ [第 2 步：创建 Amazon SNS 主题](#gs-cli-create-snstopic)
+ [步骤 3：创建 IAM 角色](#gs-cli-create-iamrole)

## 步骤 1：创建 Amazon S3 存储桶
<a name="gs-cli-create-s3bucket"></a>

如果您的账户中已存在 Amazon S3 存储桶，并且您想使用该存储桶，请跳过此步骤并转至。[第 2 步：创建 Amazon SNS 主题](#gs-cli-create-snstopic)

### 使用 S3 控制台
<a name="create-bucket"></a>

**创建存储桶**

1. 打开 Amazon S3 控制台，网址为 [https://console.aws.amazon.com/s3/](https://console.aws.amazon.com/s3/)。

1. 选择**创建桶**。

1. 在 **Bucket name（桶名称）**中，输入符合 DNS 标准的桶名称。

   桶名称必须满足以下要求：
   + 在所有 Amazon S3 中是唯一的。
   + 长度必须介于 3 到 63 个字符之间。
   + 不包含大写字符。
   + 以小写字母或数字开头。

   创建存储桶后，便无法再更改其名称。请确保您选择的存储桶名称在 Amazon S3 中所有现有存储桶名称中唯一。有关存储桶命名规则和约定的更多信息，请参阅《Amazon Simple Storage Service 用户指南》**中的[存储桶约束和限制](https://docs.aws.amazon.com/AmazonS3/latest/userguide/BucketRestrictions.html)。
**重要**  
避免在存储桶名称中包含敏感信息。存储桶名称在指向存储桶 URLs 中对象的位置中可见。

1. 在**区域**中，选择您想要存储桶所在的 AWS 区域。

   请选择一个靠近您的区域可最大程度地减少延迟和成本以及满足法规要求。在某一区域存储的对象将一直留在该区域，除非您特意将其转移到其他区域。有关 Amazon S3 AWS 区域的列表，请参阅中的[AWS 服务终端节点*Amazon Web Services 一般参考*](https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region)。

1. 在 **Bucket settings for Block Public Access（阻止公有访问的桶设置）**中，请选择要应用于桶的 Block Public Access（阻止公有访问）设置。

   我们建议您将所有设置保持为启用状态，除非您知道您需要为您的使用案例关闭其中一个或多个设置，例如托管公共网站。您为存储桶启用的阻止公有访问设置也将为您在存储桶上创建的所有访问点启用。有关屏蔽公共访问权限的更多信息，请参阅《Amazon Simple Storage Service 用户指南》中的[使用 Amazon S3 屏蔽公共访问权限](https://docs.aws.amazon.com/AmazonS3/latest/dev/access-control-block-public-access.html)。**

1. （可选）如果要启用 S3 对象锁定：

   1. 请选择 **Advanced settings（高级设置）**，然后阅读显示的消息。
**重要**  
您只能在创建存储桶时为其启用 S3 对象锁定。如果您为存储桶启用了对象锁定，则以后无法禁用它。启用对象锁定还会启用存储桶的版本控制。为存储桶启用对象锁定后，必须先配置对象锁定设置，然后才能保护存储桶中的任何对象。有关配置对象保护的更多信息，请参阅[使用 Amazon S3 控制台配置 S3 对象锁定](https://docs.aws.amazon.com//AmazonS3/latest/dev/object-lock-console.html)。

   1. 如果要启用对象锁定，请在文本框中输入 *enable* 并选择 **Confirm（确认）**。

   有关 S3 对象锁定功能的更多信息，请参阅《Amazon Simple Storage Service 用户指南》**中的[使用 Amazon S3 对象锁定以锁定对象](https://docs.aws.amazon.com//AmazonS3/latest/dev/object-lock.html)。

1. 选择 **创建存储桶 **。

### 使用 AWS SDKs
<a name="create-bucket-intro"></a>

使用创建存储桶时，必须创建一个客户端，然后使用该客户端发送创建存储桶的请求。 AWS SDKs 作为最佳做法，您应在同一 AWS 区域中创建客户端和桶。如果您在创建客户端或桶时未指定区域，Amazon S3 将使用默认区域美国东部（弗吉尼亚北部）。

要创建用于访问双栈端点的客户端，必须指定。 AWS 区域有关更多信息，请参阅 [Amazon S3 双堆栈端点](https://docs.aws.amazon.com//AmazonS3/latest/dev/dual-stack-endpoints.html#dual-stack-endpoints-description)。有关可用区域的列表 AWS 区域，请参阅中的[区域和终端节点*AWS 一般参考*](https://docs.aws.amazon.com/general/latest/gr/s3.html)。

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

这些 AWS SDK 代码示例执行以下任务：
+ **通过明确指定 AWS 区域创建客户端** – 在本示例中，客户端使用 `s3.us-west-2.amazonaws.com` 终端节点与 Amazon S3 通信。您可以指定任意。 AWS 区域有关列表 AWS 区域，请参阅《*AWS 一般参考*》中的[区域和终端节点](https://docs.aws.amazon.com/general/latest/gr/s3.html)。
+ **通过仅指定桶名称来发送创建桶请求** — 客户端向 Amazon S3 发送请求，请求在您创建客户端的区域中创建桶。
+ **检索有关桶位置的信息** — Amazon S3 将桶位置信息存储在与桶关联的*位置*子资源中。

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

------
#### [ .NET ]

**适用于 .NET 的 SDK (v4)**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/S3#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /// <summary>
    /// Shows how to create a new Amazon S3 bucket.
    /// </summary>
    /// <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 async Task<bool> CreateBucketAsync(string bucketName)
    {
        try
        {
            var request = new PutBucketRequest
            {
                BucketName = bucketName,
                UseClientRegion = true,
            };

            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 的详细信息，请参阅 *适用于 .NET 的 AWS SDK API 参考[CreateBucket](https://docs.aws.amazon.com/goto/DotNetSDKV4/s3-2006-03-01/CreateBucket)*中的。

**适用于 .NET 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3#code-examples)中查找完整示例，了解如何进行设置和运行。
创建一个启用对象锁定的存储桶。  

```
    /// <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 的详细信息，请参阅 *适用于 .NET 的 AWS SDK API 参考[CreateBucket](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/CreateBucket)*中的。

------
#### [ Bash ]

**AWS CLI 使用 Bash 脚本**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/s3#code-examples)中查找完整示例，了解如何进行设置和运行。

```
###############################################################################
# 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](https://docs.aws.amazon.com/goto/aws-cli/s3-2006-03-01/CreateBucket)*中的。

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3#code-examples)中查找完整示例，了解如何进行设置和运行。

```
bool AwsDoc::S3::createBucket(const Aws::String &bucketName,
                              const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client client(clientConfig);
    Aws::S3::Model::CreateBucketRequest request;
    request.SetBucket(bucketName);

    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 的详细信息，请参阅 *适用于 C\$1\$1 的 AWS SDK API 参考[CreateBucket](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/CreateBucket)*中的。

------
#### [ CLI ]

**AWS CLI**  
**示例 1：创建存储桶**  
以下 `create-bucket` 示例创建一个名为 `amzn-s3-demo-bucket` 的存储桶：  

```
aws s3api create-bucket \
    --bucket amzn-s3-demo-bucket \
    --region us-east-1
```
输出：  

```
{
    "Location": "/amzn-s3-demo-bucket"
}
```
有关更多信息，请参阅《Amazon S3 用户指南》**中的[创建存储桶](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket-overview.html)。  
**示例 2：创建带有强制拥有者的存储桶**  
以下 `create-bucket` 示例创建一个名为 `amzn-s3-demo-bucket` 的存储桶，该存储桶对于 S3 对象所有权使用强制存储桶拥有者设置。  

```
aws s3api create-bucket \
    --bucket amzn-s3-demo-bucket \
    --region us-east-1 \
    --object-ownership BucketOwnerEnforced
```
输出：  

```
{
    "Location": "/amzn-s3-demo-bucket"
}
```
有关更多信息，请参阅 *Amazon S3 用户指南 ACLs*中的[控制对象所有权和禁用](https://docs.aws.amazon.com/AmazonS3/latest/userguide/about-object-ownership.html)。  
**示例 3：在“us-east-1”区域之外创建存储桶**  
以下 `create-bucket` 示例在 `eu-west-1` 区域中创建名为 `amzn-s3-demo-bucket` 的存储桶。`us-east-1` 之外的区域需要指定相应的 `LocationConstraint` 才能在所需区域创建存储桶。  

```
aws s3api create-bucket \
    --bucket amzn-s3-demo-bucket \
    --region eu-west-1 \
    --create-bucket-configuration LocationConstraint=eu-west-1
```
输出：  

```
{
    "Location": "http://amzn-s3-demo-bucket.s3.amazonaws.com/"
}
```
有关更多信息，请参阅《Amazon S3 用户指南》**中的[创建存储桶](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket-overview.html)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[CreateBucket](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/create-bucket.html)*中的。

------
#### [ Go ]

**适用于 Go 的 SDK V2**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/s3#code-examples)中查找完整示例，了解如何进行设置和运行。
使用默认配置创建存储桶。  

```
import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"io"
	"log"
	"os"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/s3/types"
	"github.com/aws/smithy-go"
)

// 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(ctx context.Context, name string, region string) error {
	_, err := basics.S3Client.CreateBucket(ctx, &s3.CreateBucketInput{
		Bucket: aws.String(name),
		CreateBucketConfiguration: &types.CreateBucketConfiguration{
			LocationConstraint: types.BucketLocationConstraint(region),
		},
	})
	if err != nil {
		var owned *types.BucketAlreadyOwnedByYou
		var exists *types.BucketAlreadyExists
		if errors.As(err, &owned) {
			log.Printf("You already own bucket %s.\n", name)
			err = owned
		} else if errors.As(err, &exists) {
			log.Printf("Bucket %s already exists.\n", name)
			err = exists
		}
	} else {
		err = s3.NewBucketExistsWaiter(basics.S3Client).Wait(
			ctx, &s3.HeadBucketInput{Bucket: aws.String(name)}, time.Minute)
		if err != nil {
			log.Printf("Failed attempt to wait for bucket %s to exist.\n", name)
		}
	}
	return err
}
```
创建带有对象锁定功能的存储桶，并等待该存储桶创建成功。  

```
import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/s3/types"
	"github.com/aws/smithy-go"
)

// S3Actions wraps S3 service actions.
type S3Actions struct {
	S3Client  *s3.Client
	S3Manager *manager.Uploader
}



// CreateBucketWithLock creates a new S3 bucket with optional object locking enabled
// and waits for the bucket to exist before returning.
func (actor S3Actions) CreateBucketWithLock(ctx context.Context, bucket string, region string, enableObjectLock bool) (string, error) {
	input := &s3.CreateBucketInput{
		Bucket: aws.String(bucket),
		CreateBucketConfiguration: &types.CreateBucketConfiguration{
			LocationConstraint: types.BucketLocationConstraint(region),
		},
	}

	if enableObjectLock {
		input.ObjectLockEnabledForBucket = aws.Bool(true)
	}

	_, err := actor.S3Client.CreateBucket(ctx, input)
	if err != nil {
		var owned *types.BucketAlreadyOwnedByYou
		var exists *types.BucketAlreadyExists
		if errors.As(err, &owned) {
			log.Printf("You already own bucket %s.\n", bucket)
			err = owned
		} else if errors.As(err, &exists) {
			log.Printf("Bucket %s already exists.\n", bucket)
			err = exists
		}
	} else {
		err = s3.NewBucketExistsWaiter(actor.S3Client).Wait(
			ctx, &s3.HeadBucketInput{Bucket: aws.String(bucket)}, time.Minute)
		if err != nil {
			log.Printf("Failed attempt to wait for bucket %s to exist.\n", bucket)
		}
	}

	return bucket, err
}
```
+  有关 API 的详细信息，请参阅 *适用于 Go 的 AWS SDK API 参考[CreateBucket](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3#Client.CreateBucket)*中的。

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)中查找完整示例，了解如何进行设置和运行。
创建存储桶。  

```
    /**
     * Creates an S3 bucket asynchronously.
     *
     * @param bucketName the name of the S3 bucket to create
     * @return a {@link CompletableFuture} that completes when the bucket is created and ready
     * @throws RuntimeException if there is a failure while creating the bucket
     */
    public CompletableFuture<Void> createBucketAsync(String bucketName) {
        CreateBucketRequest bucketRequest = CreateBucketRequest.builder()
            .bucket(bucketName)
            .build();

        CompletableFuture<CreateBucketResponse> response = getAsyncClient().createBucket(bucketRequest);
        return response.thenCompose(resp -> {
            S3AsyncWaiter s3Waiter = getAsyncClient().waiter();
            HeadBucketRequest bucketRequestWait = HeadBucketRequest.builder()
                .bucket(bucketName)
                .build();

            CompletableFuture<WaiterResponse<HeadBucketResponse>> waiterResponseFuture =
                s3Waiter.waitUntilBucketExists(bucketRequestWait);
            return waiterResponseFuture.thenAccept(waiterResponse -> {
                waiterResponse.matched().response().ifPresent(headBucketResponse -> {
                    logger.info(bucketName + " is ready");
                });
            });
        }).whenComplete((resp, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Failed to create bucket", ex);
            }
        });
    }
```
创建一个启用对象锁定的存储桶。  

```
    // 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 的详细信息，请参阅 *AWS SDK for Java 2.x API 参考[CreateBucket](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/CreateBucket)*中的。

------
#### [ JavaScript ]

**适用于 JavaScript (v3) 的软件开发工具包**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/s3#code-examples)中查找完整示例，了解如何进行设置和运行。
创建存储桶。  

```
import {
  BucketAlreadyExists,
  BucketAlreadyOwnedByYou,
  CreateBucketCommand,
  S3Client,
  waitUntilBucketExists,
} from "@aws-sdk/client-s3";

/**
 * Create an Amazon S3 bucket.
 * @param {{ bucketName: string }} config
 */
export const main = async ({ bucketName }) => {
  const client = new S3Client({});

  try {
    const { Location } = await client.send(
      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: bucketName,
      }),
    );
    await waitUntilBucketExists({ client }, { Bucket: bucketName });
    console.log(`Bucket created with location ${Location}`);
  } catch (caught) {
    if (caught instanceof BucketAlreadyExists) {
      console.error(
        `The bucket "${bucketName}" already exists in another AWS account. Bucket names must be globally unique.`,
      );
    }
    // WARNING: If you try to create a bucket in the North Virginia region,
    // and you already own a bucket in that region with the same name, this
    // error will not be thrown. Instead, the call will return successfully
    // and the ACL on that bucket will be reset.
    else if (caught instanceof BucketAlreadyOwnedByYou) {
      console.error(
        `The bucket "${bucketName}" already exists in this AWS account.`,
      );
    } else {
      throw caught;
    }
  }
};
```
+  有关更多信息，请参阅《适用于 JavaScript 的 AWS SDK 开发人员指南》[https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/s3-example-creating-buckets.html#s3-example-creating-buckets-new-bucket-2](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/s3-example-creating-buckets.html#s3-example-creating-buckets-new-bucket-2)。
+  有关 API 的详细信息，请参阅 *适用于 JavaScript 的 AWS SDK API 参考[CreateBucket](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/CreateBucketCommand)*中的。

------
#### [ Kotlin ]

**适用于 Kotlin 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/s3#code-examples)中查找完整示例，了解如何进行设置和运行。

```
suspend fun createNewBucket(bucketName: String) {
    val request =
        CreateBucketRequest {
            bucket = bucketName
        }

    S3Client.fromEnvironment { region = "us-east-1" }.use { s3 ->
        s3.createBucket(request)
        println("$bucketName is ready")
    }
}
```
+  有关 API 的详细信息，请参阅适用[CreateBucket](https://sdk.amazonaws.com/kotlin/api/latest/index.html)于 K *otlin 的AWS SDK API 参考*。

------
#### [ PHP ]

**适用于 PHP 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/s3#code-examples)中查找完整示例，了解如何进行设置和运行。
创建存储桶。  

```
        $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 的详细信息，请参阅 *适用于 PHP 的 AWS SDK API 参考[CreateBucket](https://docs.aws.amazon.com/goto/SdkForPHPV3/s3-2006-03-01/CreateBucket)*中的。

------
#### [ Python ]

**适用于 Python 的 SDK（Boto3）**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/s3_basics#code-examples)中查找完整示例，了解如何进行设置和运行。
使用默认设置创建存储桶。  

```
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 的详细信息，请参阅适用[CreateBucket](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/CreateBucket)于 *Python 的AWS SDK (Boto3) API 参考*。

------
#### [ Ruby ]

**适用于 Ruby 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/s3#code-examples)中查找完整示例，了解如何进行设置和运行。

```
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("amzn-s3-demo-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 的详细信息，请参阅 *适用于 Ruby 的 AWS SDK API 参考[CreateBucket](https://docs.aws.amazon.com/goto/SdkForRubyV3/s3-2006-03-01/CreateBucket)*中的。

------
#### [ Rust ]

**适用于 Rust 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/s3#code-examples)中查找完整示例，了解如何进行设置和运行。

```
pub async fn create_bucket(
    client: &aws_sdk_s3::Client,
    bucket_name: &str,
    region: &aws_config::Region,
) -> Result<Option<aws_sdk_s3::operation::create_bucket::CreateBucketOutput>, S3ExampleError> {
    let constraint = aws_sdk_s3::types::BucketLocationConstraint::from(region.to_string().as_str());
    let cfg = aws_sdk_s3::types::CreateBucketConfiguration::builder()
        .location_constraint(constraint)
        .build();
    let create = client
        .create_bucket()
        .create_bucket_configuration(cfg)
        .bucket(bucket_name)
        .send()
        .await;

    // BucketAlreadyExists and BucketAlreadyOwnedByYou are not problems for this task.
    create.map(Some).or_else(|err| {
        if err
            .as_service_error()
            .map(|se| se.is_bucket_already_exists() || se.is_bucket_already_owned_by_you())
            == Some(true)
        {
            Ok(None)
        } else {
            Err(S3ExampleError::from(err))
        }
    })
}
```
+  有关 API 的详细信息，请参阅适用[CreateBucket](https://docs.rs/aws-sdk-s3/latest/aws_sdk_s3/client/struct.Client.html#method.create_bucket)于 *Rust 的AWS SDK API 参考*。

------
#### [ SAP ABAP ]

**适用于 SAP ABAP 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/s3#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    TRY.
        " determine our region from our session
        DATA(lv_region) = CONV /aws1/s3_bucketlocationcnstrnt( lo_session->get_region( ) ).
        DATA lo_constraint TYPE REF TO /aws1/cl_s3_createbucketconf.
        " When in the us-east-1 region, you must not specify a constraint
        " In all other regions, specify the region as the constraint
        IF lv_region = 'us-east-1'.
          CLEAR lo_constraint.
        ELSE.
          lo_constraint = NEW /aws1/cl_s3_createbucketconf( lv_region ).
        ENDIF.

        lo_s3->createbucket(
            iv_bucket = iv_bucket_name
            io_createbucketconfiguration  = lo_constraint ).
        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](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)于 S *AP 的AWS SDK ABAP API 参考*。

------
#### [ Swift ]

**适用于 Swift 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/s3/basics#code-examples)中查找完整示例，了解如何进行设置和运行。

```
import AWSS3

    public func createBucket(name: String) async throws {
        var input = CreateBucketInput(
            bucket: name
        )
        
        // For regions other than "us-east-1", you must set the locationConstraint in the createBucketConfiguration.
        // For more information, see LocationConstraint in the S3 API guide.
        // https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateBucket.html#API_CreateBucket_RequestBody
        if let region = configuration.region {
            if region != "us-east-1" {
                input.createBucketConfiguration = S3ClientTypes.CreateBucketConfiguration(locationConstraint: S3ClientTypes.BucketLocationConstraint(rawValue: region))
            }
        }

        do {
            _ = try await client.createBucket(input: input)
        }
        catch let error as BucketAlreadyOwnedByYou {
            print("The bucket '\(name)' already exists and is owned by you. You may wish to ignore this exception.")
            throw error
        }
        catch {
            print("ERROR: ", dump(error, name: "Creating a bucket"))
            throw error
        }
    }
```
+  有关 API 的详细信息，请参阅适用于 S *wift 的AWS SDK API 参考[CreateBucket](https://sdk.amazonaws.com/swift/api/awss3/latest/documentation/awss3/s3client/createbucket(input:))*中。

------

**注意**  
您也可以使用另一个账户中的 Amazon S3 存储桶，但您可能需要为该存储桶创建策略以便向 AWS Config授予访问权限。有关向 Amazon S3 存储桶授予权限的信息，请参阅，[AWS Config 传送渠道的 Amazon S3 存储桶的权限](s3-bucket-policy.md)然后转至。[第 2 步：创建 Amazon SNS 主题](#gs-cli-create-snstopic)

## 第 2 步：创建 Amazon SNS 主题
<a name="gs-cli-create-snstopic"></a>

如果您的账户中已经存在 Amazon SNS 主题并且您想要使用该主题，请跳过本步骤并转至。[步骤 3：创建 IAM 角色](#gs-cli-create-iamrole)

### 使用 SNS 控制台
<a name="create-snstopic"></a>

**创建 Amazon SNS 主题**

1. [在 v3/home 上打开亚马逊 SNS 控制台。https://console.aws.amazon.com/sns/](https://console.aws.amazon.com/sns/v3/home)

1. 请执行以下操作之一：
   + 如果 AWS 账户 之前未在您的主题下创建过任何主题，请阅读主页上对 Amazon SNS 的描述。
   + 如果 AWS 账户 之前在您的下方创建过主题，请在导航面板上选择**主题**。

1. 在 **Topics**（主页）页面上，选择 **Create topic**（创建主题）。

1. 在 **Create topic**（创建主题）页面上，在 **Details**（详细信息）部分中，执行以下操作：

   1. 对于 **Type**（类型），选择主题类型（**标准**或者**FIFO**）。

   1. 输入主题的**名称**。对于 [FIFO 主题](https://docs.aws.amazon.com/sns/latest/dg/sns-fifo-topics.html)，将 **.fifo** 添加到名称的末尾。

   1. （可选）输入主题的**显示名称**。

   1. （可选）对于 FIFO 主题，您可以选择**基于内容的消息重复数据删除**以启用默认的消息重复数据删除。有关更多信息，请参阅 [FIFO 主题的消息重复数据删除](https://docs.aws.amazon.com/sns/latest/dg/fifo-message-dedup.html)。

1. （可选）展开**加密**部分并执行以下操作。有关更多信息，请参阅[静态加密](https://docs.aws.amazon.com/sns/latest/dg/sns-server-side-encryption.html)。

   1. 选择**启用加密**。

   1. 指定客户主密钥（CMK）。有关更多信息，请参阅[关键术语](https://docs.aws.amazon.com/sns/latest/dg/sns-server-side-encryption.html#sse-key-terms)。

      对于每个 CMK 类型，都会显示 **Description（描述）**、**Account（账户）**和 **CMK ARN**。
**重要**  
如果您不是 CMK 的拥有者，或者您登录的账户没有 `kms:ListAliases` 和 `kms:DescribeKey` 权限，则无法在 Amazon SNS 控制台上查看有关 CMK 的信息。  
要求 CMK 拥有者授予您这些权限。有关更多信息，请参阅 *AWS Key Management Service 开发人员指南*中的 [AWS KMS API 权限：操作和资源参考](https://docs.aws.amazon.com/kms/latest/developerguide/kms-api-permissions-reference.html)。
      + 默认情况下，Amazon **SNS 的 AWS 托管 CMK（默认alias/aws/sns）处于**选中状态。
**注意**  
记住以下内容：  
首次使用为主题 AWS KMS 指定适用于 Amazon SNS 的 AWS 托管 CMK 时，会为 Amazon SNS 创建 AWS 托管 CMK。 AWS 管理控制台 
或者，在启用 SSE 的情况下首次对主题使用`Publish`操作时， AWS KMS 会为 Amazon SNS 创建 AWS 托管 CMK。
      + 要使用您的自定义 CMK AWS 账户，请选择**客户主密钥 (CMK)** 字段，然后从列表中选择自定义 CMK。
**注意**  
有关创建自定义密钥的说明 CMKs，请参阅《*AWS Key Management Service 开发者指南》*中的[创建密钥](https://docs.aws.amazon.com/kms/latest/developerguide/create-keys.html)
      + 要使用来自 AWS 账户 您 AWS 或其他账户的自定义 CMK ARN，请将其输入到**客户主密钥 (CM** K) 字段。

1. （可选）默认情况下，只有主题拥有者才能发布或订阅主题。要配置其他访问权限，请展开**访问策略**部分。有关更多信息，请参阅 [Amazon SNS 中的 Identity and Access Management](https://docs.aws.amazon.com/sns/latest/dg/sns-authentication-and-access-control.html) 和[用于 Amazon SNS 访问控制的示例案例](https://docs.aws.amazon.com/sns/latest/dg/sns-access-policy-use-cases.html)。
**注意**  
使用控制台创建主题时，默认策略使用 `aws:SourceOwner` 条件键。此密钥类似于。`aws:SourceAccount`

1. （可选）要配置 Amazon SNS 重试失败消息传输尝试的方式，请展开 **Delivery retry policy（HTTP/S）**（传输重试策略（HTTP/S））部分。有关更多信息，请参阅 [Amazon SNS 消息传输重试](https://docs.aws.amazon.com/sns/latest/dg/sns-message-delivery-retries.html)。

1. （可选）要配置 Amazon SNS 如何记录向其发送的消息 CloudWatch，请展开**传送状态记录部分**。有关更多信息，请参阅 [Amazon SNS 消息传输状态](https://docs.aws.amazon.com/sns/latest/dg/sns-topic-attributes.html)。

1. （可选）要将元数据标签添加到主题中，请展开**标签**部分，输入一个**键**和**值**（可选），然后选择**添加标签**。有关更多信息，请参阅 [Amazon SNS 主题标记](https://docs.aws.amazon.com/sns/latest/dg/sns-tags.html)。

1. 选择**创建主题**。

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

   主题的**名称**、**ARN**、（可选）**显示名称**和**主题所有者**的 AWS 账户 ID 将显示在**详细信息**部分中。

1. 将主题 ARN 复制到剪贴板，例如：

   ```
   arn:aws:sns:us-east-2:123456789012:MyTopic
   ```

**使用电子邮件地址订阅 Amazon SNS 主题**

1. [在 v3/home 上打开亚马逊 SNS 控制台。https://console.aws.amazon.com/sns/](https://console.aws.amazon.com/sns/v3/home)

1. 在左侧导航窗格中，选择**订阅**。

1. 在**订阅**页面上，选择**创建订阅**。

1. 在**创建订阅**页上的**详细信息**部分，执行以下操作：

   1. 对于 **Topic ARN**（主题 ARN），选择主题的 Amazon Resource Name（ARN）。

   1. 对于 **Protocol**（协议），选择终端节点类型。可用的终端节点类型包括：
      + [HTTP/HTTPS](https://docs.aws.amazon.com/sns/latest/dg/sns-http-https-endpoint-as-subscriber.html)
      + [电子邮件/电子邮件-JSON](https://docs.aws.amazon.com/sns/latest/dg/sns-email-notifications.html)
      + [Amazon Data Firehose](https://docs.aws.amazon.com/sns/latest/dg/sns-firehose-as-subscriber.html)
      + [Amazon SQS](https://docs.aws.amazon.com/sns/latest/dg/sns-sqs-as-subscriber.html)
**注意**  
要订阅到 [SNS FIFO 主题](https://docs.aws.amazon.com/sns/latest/dg/sns-fifo-topics.html)，请选择该选项。
      + [AWS Lambda](https://docs.aws.amazon.com/sns/latest/dg/sns-lambda-as-subscriber.html)
      + [平台应用程序终端节点](https://docs.aws.amazon.com/sns/latest/dg/sns-mobile-application-as-subscriber.html)
      + [短信](https://docs.aws.amazon.com/sns/latest/dg/sns-mobile-phone-number-as-subscriber.html)

   1. 对于 **Endpoint**（终端节点），输入终端节点值，例如电子邮件地址或 Amazon SQS 队列的 ARN。

   1. 仅限于 Firehose 端点：对于**订阅角色 ARN**，指定您为写入到 Firehose 传输流创建的 IAM 角色的 ARN。有关更多信息，请参阅[订阅 Firehose 传输流到 Amazon SNS 主题的先决条件](https://docs.aws.amazon.com/sns/latest/dg/prereqs-kinesis-data-firehose.html)。

   1. （可选）对于 Firehose、Amazon SQS HTTP/S 、终端节点，您还可以启用原始消息传输。有关更多信息，请参阅 [Amazon SNS 原始消息传输](https://docs.aws.amazon.com/sns/latest/dg/sns-large-payload-raw-message-delivery.html)。

   1. （可选）要配置筛选策略，请展开 **Subscription filter policy**（订阅筛选策略）部分。有关更多信息，请参阅 [Amazon SNS 订阅筛选策略](https://docs.aws.amazon.com/sns/latest/dg/sns-subscription-filter-policies.html)。

   1. （可选）要为订阅配置死信队列，请展开 **Redrive policy（dead-letter queue）**（重新驱动策略（死信队列））部分。有关更多信息，请参阅 [Amazon SNS 死信队列 (](https://docs.aws.amazon.com/sns/latest/dg/sns-dead-letter-queues.html))。DLQs

   1. 选择**创建订阅**。

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

### 使用 AWS SDKs
<a name="create-snstopic-intro"></a>

要使用 S AWS DK，必须使用您的凭据对其进行配置。有关更多信息，请参阅[《工具参考指南》和《*工具参考指南》中的共享配置AWS SDKs 和*凭据文件](https://docs.aws.amazon.com/sdkref/latest/guide/creds-config-files.html)。

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

------
#### [ .NET ]

**适用于 .NET 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SNS#code-examples)中查找完整示例，了解如何进行设置和运行。
使用特定的名称创建主题。  

```
    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 的详细信息，请参阅 *适用于 .NET 的 AWS SDK API 参考[CreateTopic](https://docs.aws.amazon.com/goto/DotNetSDKV3/sns-2010-03-31/CreateTopic)*中的。

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sns#code-examples)中查找完整示例，了解如何进行设置和运行。

```
//! 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 的详细信息，请参阅 *适用于 C\$1\$1 的 AWS SDK API 参考[CreateTopic](https://docs.aws.amazon.com/goto/SdkForCpp/sns-2010-03-31/CreateTopic)*中的。

------
#### [ CLI ]

**AWS 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"
}
```
有关更多信息，请参阅[《 AWS 命令行界面用户指南》中的在 Amazon SQS 和 Amazon SNS 中使用](https://docs.aws.amazon.com/cli/latest/userguide/cli-sqs-queue-sns-topic.html)*命令AWS 行*界面。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[CreateTopic](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/create-topic.html)*中的。

------
#### [ Go ]

**适用于 Go 的 SDK V2**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/topics_and_queues#code-examples)中查找完整示例，了解如何进行设置和运行。

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/sns"
	"github.com/aws/aws-sdk-go-v2/service/sns/types"
)

// 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(ctx context.Context, 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(ctx, &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 的详细信息，请参阅 *适用于 Go 的 AWS SDK API 参考[CreateTopic](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sns#Client.CreateTopic)*中的。

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples)中查找完整示例，了解如何进行设置和运行。

```
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 的详细信息，请参阅 *AWS SDK for Java 2.x API 参考[CreateTopic](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/CreateTopic)*中的。

------
#### [ JavaScript ]

**适用于 JavaScript (v3) 的软件开发工具包**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sns#code-examples) 中查找完整示例，了解如何进行设置和运行。
在单独的模块中创建客户端并将其导出。  

```
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;
};
```
+  有关更多信息，请参阅[《适用于 JavaScript 的 AWS SDK Developer Guide》](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/sns-examples-managing-topics.html#sns-examples-managing-topics-createtopic)。
+  有关 API 的详细信息，请参阅 *适用于 JavaScript 的 AWS SDK API 参考[CreateTopic](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sns/command/CreateTopicCommand)*中的。

------
#### [ Kotlin ]

**适用于 Kotlin 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/sns#code-examples)中查找完整示例，了解如何进行设置和运行。

```
suspend fun createSNSTopic(topicName: String): String {
    val request =
        CreateTopicRequest {
            name = topicName
        }

    SnsClient.fromEnvironment { region = "us-east-1" }.use { snsClient ->
        val result = snsClient.createTopic(request)
        return result.topicArn.toString()
    }
}
```
+  有关 API 的详细信息，请参阅适用[CreateTopic](https://sdk.amazonaws.com/kotlin/api/latest/index.html)于 K *otlin 的AWS SDK API 参考*。

------
#### [ PHP ]

**适用于 PHP 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/sns#code-examples)中查找完整示例，了解如何进行设置和运行。

```
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());
}
```
+  有关更多信息，请参阅《适用于 PHP 的 AWS SDK 开发人员指南》[https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/sns-examples-managing-topics.html#create-a-topic](https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/sns-examples-managing-topics.html#create-a-topic)。
+  有关 API 的详细信息，请参阅 *适用于 PHP 的 AWS SDK API 参考[CreateTopic](https://docs.aws.amazon.com/goto/SdkForPHPV3/sns-2010-03-31/CreateTopic)*中的。

------
#### [ Python ]

**适用于 Python 的 SDK（Boto3）**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sns#code-examples)中查找完整示例，了解如何进行设置和运行。

```
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
```

```
class SnsWrapper:
    """Wrapper class for managing Amazon SNS operations."""

    def __init__(self, sns_client: Any) -> None:
        """
        Initialize the SnsWrapper.

        :param sns_client: A Boto3 Amazon SNS client.
        """
        self.sns_client = sns_client

    @classmethod
    def from_client(cls) -> 'SnsWrapper':
        """
        Create an SnsWrapper instance using a default boto3 client.

        :return: An instance of this class.
        """
        sns_client = boto3.client('sns')
        return cls(sns_client)


    def create_topic(
        self, 
        topic_name: str, 
        is_fifo: bool = False, 
        content_based_deduplication: bool = False
    ) -> str:
        """
        Create an SNS topic.

        :param topic_name: The name of the topic to create.
        :param is_fifo: Whether to create a FIFO topic.
        :param content_based_deduplication: Whether to use content-based deduplication for FIFO topics.
        :return: The ARN of the created topic.
        :raises ClientError: If the topic creation fails.
        """
        try:
            # Add .fifo suffix for FIFO topics
            if is_fifo and not topic_name.endswith('.fifo'):
                topic_name += '.fifo'

            attributes = {}
            if is_fifo:
                attributes['FifoTopic'] = 'true'
                if content_based_deduplication:
                    attributes['ContentBasedDeduplication'] = 'true'

            response = self.sns_client.create_topic(
                Name=topic_name,
                Attributes=attributes
            )

            topic_arn = response['TopicArn']
            logger.info(f"Created topic: {topic_name} with ARN: {topic_arn}")
            return topic_arn

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            logger.error(f"Error creating topic {topic_name}: {error_code} - {e}")
            raise
```
+  有关 API 的详细信息，请参阅适用[CreateTopic](https://docs.aws.amazon.com/goto/boto3/sns-2010-03-31/CreateTopic)于 *Python 的AWS SDK (Boto3) API 参考*。

------
#### [ Ruby ]

**适用于 Ruby 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/sns#code-examples)中查找完整示例，了解如何进行设置和运行。

```
# 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
```
+  有关更多信息，请参阅《适用于 Ruby 的 AWS SDK 开发人员指南》[https://docs.aws.amazon.com/sdk-for-ruby/v3/developer-guide/sns-example-create-topic.html](https://docs.aws.amazon.com/sdk-for-ruby/v3/developer-guide/sns-example-create-topic.html)。
+  有关 API 的详细信息，请参阅 *适用于 Ruby 的 AWS SDK API 参考[CreateTopic](https://docs.aws.amazon.com/goto/SdkForRubyV3/sns-2010-03-31/CreateTopic)*中的。

------
#### [ Rust ]

**适用于 Rust 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/sns#code-examples)中查找完整示例，了解如何进行设置和运行。

```
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 的详细信息，请参阅适用[CreateTopic](https://docs.rs/aws-sdk-sns/latest/aws_sdk_sns/client/struct.Client.html#method.create_topic)于 *Rust 的AWS SDK API 参考*。

------
#### [ SAP ABAP ]

**适用于 SAP ABAP 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sns#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    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](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)于 S *AP 的AWS SDK ABAP API 参考*。

------
#### [ Swift ]

**适用于 Swift 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/sns#code-examples)中查找完整示例，了解如何进行设置和运行。

```
import AWSSNS

        let config = try await SNSClient.SNSClientConfiguration(region: region)
        let snsClient = SNSClient(config: config)

        let output = try await snsClient.createTopic(
            input: CreateTopicInput(name: name)
        )

        guard let arn = output.topicArn else {
            print("No topic ARN returned by Amazon SNS.")
            return
        }
```
+  有关 API 的详细信息，请参阅适用于 S *wift 的AWS SDK API 参考[CreateTopic](https://sdk.amazonaws.com/swift/api/awssns/latest/documentation/awssns/snsclient/createtopic(input:))*中。

------

**注意**  
您也可以使用另一个账户中的 Amazon SNS 主题，但在这种情况下，您可能需要为该主题创建策略以便向 AWS Config授予访问权限。有关向 Amazon SNS 主题授予访问权限的信息，请参阅，[Amazon SNS 主题的权限](sns-topic-policy.md)然后转至。[步骤 3：创建 IAM 角色](#gs-cli-create-iamrole)

## 步骤 3：创建 IAM 角色
<a name="gs-cli-create-iamrole"></a>

**重要**  
**（推荐）使用 AWS Config 服务相关角色**  
建议使用 AWS Config 服务相关角色:`AWSServiceRoleForConfig`。服务相关角色是预定义的，包括调用其他 AWS 服务角色 AWS Config 所需的所有权限。与 AWS Config 服务相关的配置记录器需要服务相关角色。  
有关更多信息，请参阅[为 AWS Config使用服务相关角色](https://docs.aws.amazon.com/config/latest/developerguide/using-service-linked-roles.html)。

### 使用 IAM 控制台
<a name="create-iamrole"></a>

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

**注意**  
如果您使用的是使用的 AWS 服务 AWS Config （例如 Sec AWS urity Hub 或 Cont AWS rol Tower），并且已经创建了角色，则应确保在设置时使用的 IAM 角色与已创建的 AWS Config 角色 AWS Config 保持相同的最低权限，以便其他 AWS 服务继续按预期运行。 AWS Config   
例如，如果 Cont AWS rol Tower 有一个 AWS Config 允许读取 Amazon S3 对象的 IAM 角色，则应保证在设置时使用的 IAM 角色中授予的权限相同 AWS Config。否则，它可能会干扰 AWS 控制塔的运行。  
有关的 IAM 角色的更多信息 AWS Config，请参阅 Ident [AWS ity and Access 管理](https://docs.aws.amazon.com/config/latest/developerguide/security-iam.html)。

**为 AWS 服务创建角色**

1. 登录 AWS 管理控制台 并打开 IAM 控制台，网址为[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/)。

1. 在 IAM 控制台的导航窗格中，选择**角色**，然后选择**创建角色**。

1. 对于**选择可信实体**，选择 **AWS 服务**。

1. 选择你想要的用例 AWS Config：**Config-可自定义、Config-Organizations**、**Con** **fig** **或 Config-Conformance Packs**。然后选择**下一步**。

1. 在**命名、查看和创建**页面上，查看有关您的角色的详细信息，然后选择**创建角色**。

### 使用 AWS SDKs
<a name="create-iamrole-intro"></a>

要使用 S AWS DK，必须使用您的凭据对其进行配置。有关更多信息，请参阅[《工具参考指南》和《*工具参考指南》中的共享配置AWS SDKs 和*凭据文件](https://docs.aws.amazon.com/sdkref/latest/guide/creds-config-files.html)。

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

------
#### [ .NET ]

**适用于 .NET 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/IAM#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /// <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 的详细信息，请参阅 *适用于 .NET 的 AWS SDK API 参考[CreateRole](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/CreateRole)*中的。

------
#### [ Bash ]

**AWS CLI 使用 Bash 脚本**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/iam#code-examples)中查找完整示例，了解如何进行设置和运行。

```
###############################################################################
# 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 的详细信息，请参阅*AWS CLI 命令参考[CreateRole](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/CreateRole)*中的。

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iam#code-examples)中查找完整示例，了解如何进行设置和运行。

```
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 的详细信息，请参阅 *适用于 C\$1\$1 的 AWS SDK API 参考[CreateRole](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/CreateRole)*中的。

------
#### [ CLI ]

**AWS 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` 命令。  
有关更多信息，请参阅《AWS IAM 用户指南》**中的[创建 IAM 角色](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html)。  
**示例 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 *AWS AM 用户指南*中的[修改角色最长会话持续时间 (AWS API)](https://docs.aws.amazon.com/IAM/latest/UserGuide/roles-managingrole-editing-api.html#roles-modify_max-session-duration-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"
            }
        ]
    }
}
```
有关更多信息，请参阅《AWS IAM 用户指南》**中的[标记 IAM 角色](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags_roles.html)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[CreateRole](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/create-role.html)*中的。

------
#### [ Go ]

**适用于 Go 的 SDK V2**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/iam#code-examples)中查找完整示例，了解如何进行设置和运行。

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// 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(ctx context.Context, 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(ctx, &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 的详细信息，请参阅 *适用于 Go 的 AWS SDK API 参考[CreateRole](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.CreateRole)*中的。

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iam#code-examples)中查找完整示例，了解如何进行设置和运行。

```
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 的详细信息，请参阅 *AWS SDK for Java 2.x API 参考[CreateRole](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/CreateRole)*中的。

------
#### [ JavaScript ]

**适用于 JavaScript (v3) 的软件开发工具包**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)中查找完整示例，了解如何进行设置和运行。
创建角色。  

```
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 的详细信息，请参阅 *适用于 JavaScript 的 AWS SDK API 参考[CreateRole](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreateRoleCommand)*中的。

------
#### [ PHP ]

**适用于 PHP 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/iam#code-examples)中查找完整示例，了解如何进行设置和运行。

```
$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 的详细信息，请参阅 *适用于 PHP 的 AWS SDK API 参考[CreateRole](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/CreateRole)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 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 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [CreateRole](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 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 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [CreateRole](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------
#### [ Python ]

**适用于 Python 的 SDK（Boto3）**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)中查找完整示例，了解如何进行设置和运行。

```
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 的详细信息，请参阅适用[CreateRole](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreateRole)于 *Python 的AWS SDK (Boto3) API 参考*。

------
#### [ Ruby ]

**适用于 Ruby 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)中查找完整示例，了解如何进行设置和运行。

```
  # 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 的详细信息，请参阅 *适用于 Ruby 的 AWS SDK API 参考[CreateRole](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/CreateRole)*中的。

------
#### [ Rust ]

**适用于 Rust 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/iam#code-examples)中查找完整示例，了解如何进行设置和运行。

```
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 的详细信息，请参阅适用[CreateRole](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.create_role)于 *Rust 的AWS SDK API 参考*。

------
#### [ SAP ABAP ]

**适用于 SAP ABAP 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    TRY.
        oo_result = lo_iam->createrole(
          iv_rolename = iv_role_name
          iv_assumerolepolicydocument = iv_assume_role_policy_document ).
        MESSAGE 'Role created successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamentityalrdyexex.
        MESSAGE 'Role already exists.' TYPE 'E'.
      CATCH /aws1/cx_iammalformedplydocex.
        MESSAGE 'Assume role policy document is malformed.' TYPE 'E'.
      CATCH /aws1/cx_iamlimitexceededex.
        MESSAGE 'Role limit exceeded.' TYPE 'E'.
    ENDTRY.
```
+  有关 API 的详细信息，请参阅适用[CreateRole](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)于 S *AP 的AWS SDK ABAP API 参考*。

------
#### [ Swift ]

**适用于 Swift 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/iam#code-examples)中查找完整示例，了解如何进行设置和运行。

```
import AWSIAM
import AWSS3


    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 {
            print("ERROR: createRole:", dump(error))
            throw error
        }
    }
```
+  有关 API 的详细信息，请参阅适用于 S *wift 的AWS SDK API 参考[CreateRole](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/createrole(input:))*中。

------

# 通过 AWS CLI 使用客户管理的配置记录器启动 AWS Config
<a name="gs-cli-subscribe"></a>

您可以通过创建客户管理的配置记录器来启动。AWS Config要使用 AWS CLI 创建客户管理的配置记录器，请使用以下命令：[https://docs.aws.amazon.com/cli/latest/reference/configservice/put-configuration-recorder.html](https://docs.aws.amazon.com/cli/latest/reference/configservice/put-configuration-recorder.html)、[https://docs.aws.amazon.com/cli/latest/reference/configservice/put-delivery-channel.html](https://docs.aws.amazon.com/cli/latest/reference/configservice/put-delivery-channel.html) 和 [https://docs.aws.amazon.com/cli/latest/reference/configservice/start-configuration-recorder.html](https://docs.aws.amazon.com/cli/latest/reference/configservice/start-configuration-recorder.html)。
+ `put-configuration-recorder` 命令可创建客户管理的配置记录器。
+ `put-delivery-channel` 命令可创建传输通道，AWS Config 通过该通道将配置信息传输到 S3 存储桶和 SNS 主题。
+ `start-configuration-recorder` 将启动客户管理的配置记录器。客户管理的配置记录器将开始记录您指定的资源类型的配置更改。

**Topics**
+ [注意事项](#gs-cli-subscribe-considerations)
+ [步骤 1：运行 put-configuration-recorder 命令](#gs-cli-subscribe-put-configuration-recorder)
+ [步骤 2：运行 put-delivery-channel 命令](#gs-cli-subscribe-put-delivery-channel)
+ [步骤 3：运行 start-configuration-recorder 命令](#gs-cli-subscribe-start-configuration-recorder)

## 注意事项
<a name="gs-cli-subscribe-considerations"></a>

**S3 存储桶、SNS 主题和 IAM 角色为必填项**

要创建客户管理的配置记录器，您需要创建一个 S3 存储桶、一个 SNS 主题和一个具有附加策略的 IAM 角色作为先决条件。要设置 AWS Config 的先决条件，请参阅[先决条件](https://docs.aws.amazon.com/config/latest/developerguide/gs-cli-prereq.html)。

**每个区域的每个账户配有一个客户管理的配置记录器**

每个 AWS 区域每个 AWS 账户只能有一个客户管理的配置记录器。

**每个区域的每个账户配有一个传输通道**

每个 AWS 区域每个 AWS 账户只能有一个传输通道区域。

**策略与合规结果**

[IAM 策略](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)和 [AWS Organizations 中管理的其他策略](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies.html)可能会影响 AWS Config 是否有权记录资源的配置更改。此外，规则会直接评估资源的配置，且执行评估时不会考虑这些策略。确保现行策略与您打算使用 AWS Config 的方式保持一致。

## 步骤 1：运行 put-configuration-recorder 命令
<a name="gs-cli-subscribe-put-configuration-recorder"></a>

使用 [https://docs.aws.amazon.com/cli/latest/reference/configservice/put-configuration-recorder.html](https://docs.aws.amazon.com/cli/latest/reference/configservice/put-configuration-recorder.html) 命令创建客户管理的配置记录器：

此命令使用 `--configuration-recorder` 和 `---recording-group` 字段。

```
$ aws configservice put-configuration-recorder \
--configuration-recorder file://configurationRecorder.json \
--recording-group file://recordingGroup.json
```

**`configuration-recorder` 字段**

`configurationRecorder.json` 文件指定配置记录器的 `name` 和 `roleArn` 以及默认记录频率（`recordingMode`）。您也可以使用此字段来覆盖特定资源类型的记录频率。

```
{
  "name": "default",
  "roleARN": "arn:aws:iam::123456789012:role/config-role",
  "recordingMode": {
    "recordingFrequency": CONTINUOUS or DAILY,
    "recordingModeOverrides": [ 
        { 
            "description": "Description you provide for the override",
            "recordingFrequency": CONTINUOUS or DAILY,
            "resourceTypes": [ Comma-separated list of resource types to include in the override ]
        }
    ]
  }
}
```

**`recording-group` 字段**

`recordingGroup.json` 文件指定要记录哪些资源类型。

```
{ 
    "allSupported": boolean,
    "exclusionByResourceTypes": { 
        "resourceTypes": [ Comma-separated list of resource types to exclude ]
    },
    "includeGlobalResourceTypes": boolean,
    "recordingStrategy": { 
        "useOnly": "Recording strategy for the configuration recorder"
    },
    "resourceTypes": [ Comma-separated list of resource types to include]
}
```

有关这些字段的更多信息，请参阅《AWS CLI 命令参考》**中的 [https://docs.aws.amazon.com/cli/latest/reference/configservice/put-configuration-recorder.html](https://docs.aws.amazon.com/cli/latest/reference/configservice/put-configuration-recorder.html)

## 步骤 2：运行 put-delivery-channel 命令
<a name="gs-cli-subscribe-put-delivery-channel"></a>

使用 [https://docs.aws.amazon.com/cli/latest/reference/configservice/put-delivery-channel.html](https://docs.aws.amazon.com/cli/latest/reference/configservice/put-delivery-channel.html) 命令创建传输通道：

此命令使用 `--delivery-channel` 字段。

```
$ aws configservice put-delivery-channel --delivery-channel file://deliveryChannel.json
```

**`delivery-channel` 字段**

`deliveryChannel.json` 文件指定以下内容：
+ 传输通道的 `name`
+ `s3BucketName`：AWS Config 发送配置快照的地方。
+ `snsTopicARN`：AWS Config 发送通知的地点
+ `configSnapshotDeliveryProperties`：用于设置 AWS Config 传输配置快照的频率以及它为定期规则调用评估的频率。

```
{
    "name": "default",
    "s3BucketName": "config-bucket-123456789012",
    "snsTopicARN": "arn:aws:sns:us-east-1:123456789012:config-topic",
    "configSnapshotDeliveryProperties": {
        "deliveryFrequency": "Twelve_Hours"
    }
}
```

有关这些字段的更多信息，请参阅《AWS CLI 命令参考》**中的 [https://docs.aws.amazon.com/cli/latest/reference/configservice/put-delivery-channel.html](https://docs.aws.amazon.com/cli/latest/reference/configservice/put-delivery-channel.html)

## 步骤 3：运行 start-configuration-recorder 命令
<a name="gs-cli-subscribe-start-configuration-recorder"></a>

使用 [https://docs.aws.amazon.com/cli/latest/reference/configservice/start-configuration-recorder.html](https://docs.aws.amazon.com/cli/latest/reference/configservice/start-configuration-recorder.html) 命令启动 AWS Config：

```
$ aws configservice start-configuration-recorder --configuration-recorder-name configRecorderName
```

有关这些字段的更多信息，请参阅《AWS CLI 命令参考》**中的 [https://docs.aws.amazon.com/cli/latest/reference/configservice/start-configuration-recorder.html](https://docs.aws.amazon.com/cli/latest/reference/configservice/start-configuration-recorder.html)

# 验证 AWS Config 是否已成功启动 AWS CLI
<a name="gs-cli-verify-subscribe"></a>

启动后 AWS Config，您可以使用 AWS CLI 命令检查是否 AWS Config 正在运行以及是否 AWS Config 已创建配置记录器和传送渠道。您也可以确认 AWS Config 已开始录制配置并将其传送到交付渠道。

**Topics**
+ [步骤 1：检查是否已创建传输通道](#gs-cli-verify-channel)
+ [步骤 2：检查是否已创建配置记录器](#gs-cli-verify-recorder)
+ [第 3 步：检查是否 AWS Config 已开始录制](#gs-cli-verify-config-recording)

## 步骤 1：检查是否已创建传输通道
<a name="gs-cli-verify-channel"></a>

使用 [https://docs.aws.amazon.com/cli/latest/reference/configservice/describe-delivery-channels.html](https://docs.aws.amazon.com/cli/latest/reference/configservice/describe-delivery-channels.html) 命令检查是否已配置 Amazon S3 存储桶和 Amazon SNS 主题。

您可以使用 `--delivery-channel-names` 字段来指定传输通道列表。如果未指定传输通道，则此命令将返回与该账户关联的所有传输通道的详细信息。

```
$ aws configservice describe-delivery-channels
{
    "DeliveryChannels": [
        {
            "snsTopicARN": "arn:aws:sns:us-west-2:0123456789012:my-config-topic",
            "name": "my-delivery-channel",
            "s3BucketName": "my-config-bucket"
        }
    ]
}
```

## 步骤 2：检查是否已创建配置记录器
<a name="gs-cli-verify-recorder"></a>

使用 [https://docs.aws.amazon.com/cli/latest/reference/configservice/describe-configuration-recorders.html](https://docs.aws.amazon.com/cli/latest/reference/configservice/describe-configuration-recorders.html) 命令检查配置记录器是否已创建。

您可以使用 `arn` 和 `configuration-recorder-names` 字段来指定配置记录器列表。如果未指定配置记录器，则此命令将返回与该账户关联的所有配置记录器的详细信息。

```
$ aws configservice describe-configuration-recorders
{
    "ConfigurationRecorders": [
        {
            "roleARN": "arn:aws:iam::012345678912:role/myConfigRole",
            "name": "default"
        }
    ]
}
```

## 第 3 步：检查是否 AWS Config 已开始录制
<a name="gs-cli-verify-config-recording"></a>

使用 [https://docs.aws.amazon.com/cli/latest/reference/configservice/describe-configuration-recorder-status.html](https://docs.aws.amazon.com/cli/latest/reference/configservice/describe-configuration-recorder-status.html) 命令检查配置记录器是否成功记录了范围内的资源类型。

您可以使用 `arn` 和 `configuration-recorder-names` 字段来指定配置记录器列表。如果未指定配置记录器，则此命令将返回与该账户关联的所有配置记录器的详细信息。

```
$ aws configservice describe-configuration-recorder-status
{
    "ConfigurationRecordersStatus": [
        {
            "name": "default",
            "lastStatus": "SUCCESS",
            "lastStopTime": 1414511624.914,
            "lastStartTime": 1414708460.276,
            "recording": true,
            "lastStatusChangeTime": 1414816537.148,
            "lastErrorMessage": "NA",
            "lastErrorCode": "400"
        }
    ]
}
```

`recording` 字段中的 `true` 值用于确认配置记录器已开始记录配置。 AWS Config 采用 UTC 格式来记录时间。输出显示为 Unix 时间戳。

# AWS Config与AWS SDK 一起使用
<a name="sdk-general-information-section"></a>

AWS软件开发套件 (SDKs) 可用于许多流行的编程语言。每个软件开发工具包都提供 API、代码示例和文档，使开发人员能够更轻松地以其首选语言构建应用程序。


| SDK 文档 | 代码示例 | 
| --- | --- | 
| [适用于 C\$1\$1 的 AWS SDK](https://docs.aws.amazon.com/sdk-for-cpp) | [适用于 C\$1\$1 的 AWS SDK代码示例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp) | 
| [AWS CLI](https://docs.aws.amazon.com/cli) | [AWS CLI代码示例](https://docs.aws.amazon.com/code-library/latest/ug/cli_2_code_examples.html) | 
| [适用于 Go 的 AWS SDK](https://docs.aws.amazon.com/sdk-for-go) | [适用于 Go 的 AWS SDK代码示例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2) | 
| [适用于 Java 的 AWS SDK](https://docs.aws.amazon.com/sdk-for-java) | [适用于 Java 的 AWS SDK代码示例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2) | 
| [适用于 JavaScript 的 AWS SDK](https://docs.aws.amazon.com/sdk-for-javascript) | [适用于 JavaScript 的 AWS SDK代码示例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3) | 
| [适用于 Kotlin 的 AWS SDK](https://docs.aws.amazon.com/sdk-for-kotlin) | [适用于 Kotlin 的 AWS SDK代码示例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin) | 
| [适用于 .NET 的 AWS SDK](https://docs.aws.amazon.com/sdk-for-net) | [适用于 .NET 的 AWS SDK代码示例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3) | 
| [适用于 PHP 的 AWS SDK](https://docs.aws.amazon.com/sdk-for-php) | [适用于 PHP 的 AWS SDK代码示例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php) | 
| [AWS Tools for PowerShell](https://docs.aws.amazon.com/powershell) | [AWS Tools for PowerShell代码示例](https://docs.aws.amazon.com/code-library/latest/ug/powershell_5_code_examples.html) | 
| [适用于 Python (Boto3) 的 AWS SDK](https://docs.aws.amazon.com/pythonsdk) | [适用于 Python (Boto3) 的 AWS SDK代码示例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python) | 
| [适用于 Ruby 的 AWS SDK](https://docs.aws.amazon.com/sdk-for-ruby) | [适用于 Ruby 的 AWS SDK代码示例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby) | 
| [适用于 Rust 的 AWS SDK](https://docs.aws.amazon.com/sdk-for-rust) | [适用于 Rust 的 AWS SDK代码示例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1) | 
| [适用于 SAP ABAP 的 AWS SDK](https://docs.aws.amazon.com/sdk-for-sapabap) | [适用于 SAP ABAP 的 AWS SDK代码示例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap) | 
| [适用于 Swift 的 AWS SDK](https://docs.aws.amazon.com/sdk-for-swift) | [适用于 Swift 的 AWS SDK代码示例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift) | 

**示例可用性**  
找不到所需的内容？ 通过使用此页面底部的**提供反馈**链接请求代码示例。