

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 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. 開啟位於 [https://console.aws.amazon.com/s3/](https://console.aws.amazon.com/s3/) 的 Amazon 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)》。
**重要**  
避免在儲存貯體名稱中包含敏感資訊。在指向儲存貯體中之物件的 URL 中，會顯示儲存貯體名稱。

1. 在**區域中**，選擇您要儲存貯體所在的 AWS 區域。

   建議您選擇接近您的區域以充分降低延遲及成本，並因應法規要求。除非您明確地將儲存在區域中的物件傳輸到其他區域，否則物件絕對不會離開該區域。如需 Amazon S3 AWS Regions 的清單，請參閱 中的[AWS 服務端點](https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region)*Amazon Web Services 一般參考*。

1. 在 **Bucket settings for 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. 如果要啟用物件鎖定，請在文字方塊中輸入*啟用*，然後選擇**確認**。

   如需 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 區域，請參閱 中的[區域和端點](https://docs.aws.amazon.com/general/latest/gr/s3.html)*AWS 一般參考*。

建立用戶端時，區域會對應至區域特定的端點。用戶端會使用此端點來與 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 會將儲存貯體位置資訊存放在與儲存貯體相關聯的 *location* 子資源中。

下列程式碼範例示範如何使用 `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 ]

**適用於 C\$1\$1 的 SDK**  
 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 使用者指南》**中的[控制物件的所有權並停用 ACL](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 ]

**SDK for Go 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 ]

**SDK for Java 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) 的 SDK**  
 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)》。
+  如需 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 詳細資訊，請參閱*《適用於 Kotlin 的AWS SDK API 參考》*中的 [CreateBucket](https://sdk.amazonaws.com/kotlin/api/latest/index.html)。

------
#### [ 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 詳細資訊，請參閱*《適用於 Python (Boto3) 的AWS SDK API 參考》*中的 [CreateBucket](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/CreateBucket)。

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

**SDK for Ruby**  
 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 詳細資訊，請參閱 *《適用於 Rust 的AWS SDK API 參考》*中的 [CreateBucket](https://docs.rs/aws-sdk-s3/latest/aws_sdk_s3/client/struct.Client.html#method.create_bucket)。

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

**適用於 SAP ABAP 的開發套件**  
 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 詳細資訊，請參閱《適用於 SAP ABAP 的AWS SDK API 參考》**中的 [CreateBucket](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)。

------
#### [ 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 詳細資訊，請參閱 *《適用於 Swift 的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. 在 [https://console.aws.amazon.com/sns/v3/home](https://console.aws.amazon.com/sns/v3/home) 開啟 Amazon SNS 主控台。

1. 執行以下任意一項：
   + 如果 AWS 帳戶 之前沒有在您的 下建立任何主題，請閱讀 首頁上的 Amazon SNS 說明。
   + 如果 AWS 帳戶 之前已在 下建立主題，請在導覽面板上選擇**主題**。

1. 在**主題**頁面上，選擇**建立主題**。

1. 在 **Create topic** (建立主題) 頁面上，於 **Details** (詳細資訊) 區段中，執行以下作業：

   1. 對於 **Type** (類型)，選擇主題類型 (**Standard** (標準)或**FIFO**。

   1. 輸入新主題的**名稱**。對於[FIFO 主題](https://docs.aws.amazon.com/sns/latest/dg/sns-fifo-topics.html)，新增**.fifo**到名稱的結尾。

   1. (選用) 為主題輸入 **Display name** (顯示名稱)。

   1. (選用) 對於 FIFO 主題，您可以選擇**內容型訊息重複資料刪除功能**，以啟用預設的重複訊息刪除功能。如需詳細資訊，請參閱《[刪除重複 FIFO 主題的郵件](https://docs.aws.amazon.com/sns/latest/dg/fifo-message-dedup.html)》。

1. (選用) 展開 **Encryption** (加密) 區段並執行下列動作。如需詳細資訊，請參閱[靜態加密](https://docs.aws.amazon.com/sns/latest/dg/sns-server-side-encryption.html)。

   1. 選擇 **Enable encryption** (啟用加密)。

   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 **（預設） alias/aws/sns** 的 AWS 受管 CMK。
**注意**  
請謹記以下幾點：  
第一次使用 AWS 管理主控台 為主題指定 Amazon SNS 的 AWS 受管 CMK 時， 會為 Amazon SNS AWS KMS 建立 AWS 受管 CMK。
或者，當您第一次在已啟用 SSE 的主題上使用 `Publish`動作時， 會 AWS KMS 建立 Amazon SNS 的 AWS 受管 CMK。
      + 若要從 使用自訂 CMK AWS 帳戶，請選擇**客戶主金鑰 (CMK)** 欄位，然後從清單中選擇自訂 CMK。
**注意**  
如需建立自訂 CMK 的說明，請參閱 *AWS Key Management Service 開發人員指南*中的[建立金鑰](https://docs.aws.amazon.com/kms/latest/developerguide/create-keys.html)
      + 若要從 AWS 帳戶 或從另一個 AWS 帳戶使用自訂 CMK ARN，請在**客戶主金鑰 (CMK)** 欄位中輸入它。

1. (選用) 根據預設，只有主題擁有者可以發布或訂閱主題。若要設定其他存取許可，請展開 **Access policy** (存取政策) 區段。如需詳細資訊，請參閱《[Amazon SNS 中的身分識別和存取管理](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，請展開 **Delivery status logging** (傳遞狀態記錄) 區段。如需詳細資訊，請參閱 [Amazon SNS 訊息傳遞狀態](https://docs.aws.amazon.com/sns/latest/dg/sns-topic-attributes.html)。

1. (選用) 若要將中繼資料標籤新增至主題，請展開 **Tags** (標籤) 區段，輸入 **Key**(金鑰) 和 **Value** (值) (選用)，然後選擇 **Add tag** (新增標籤)。如需詳細資訊，請參閱《[標記 Amazon SNS 主題](https://docs.aws.amazon.com/sns/latest/dg/sns-tags.html)》。

1. 請選擇**建立主題**。

   該主題隨即建立，並且 ***MyTopic*** 頁面即會顯示。

   主題的 **Name** (名稱)、**ARN**、選用的 **Display name** (顯示名稱) 以及 **Topic owner** (主題擁有者) 的 AWS 帳戶 ID 會顯示在 **Details** (詳細資訊) 區段中。

1. 將主題 ARN 複製到剪貼簿，例如：

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

**訂閱 Amazon SNS 主題的電子郵件地址**

1. 在 [https://console.aws.amazon.com/sns/v3/home](https://console.aws.amazon.com/sns/v3/home) 開啟 Amazon SNS 主控台。

1. 在左導覽窗格中，選擇**訂閱**。

1. 在**訂閱**頁面，選擇**建立訂閱**。

1. 在**建立訂閱**頁面上，於**詳細資訊**區段中，執行以下作業：

   1. 對於**ARN 主題**，選擇主題的 Amazon 資源名稱 (ARN)。

   1. 在 **Protocol** (通訊協定)，選擇端點類型。可用的端點類型為：
      + [HTTP/HTTPS](https://docs.aws.amazon.com/sns/latest/dg/sns-http-https-endpoint-as-subscriber.html)
      + [Email/Email-JSON](https://docs.aws.amazon.com/sns/latest/dg/sns-email-notifications.html) (電子郵件/電子郵件-JSON)
      + [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)
      + [SMS](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 無效字母佇列 (DLQ)](https://docs.aws.amazon.com/sns/latest/dg/sns-dead-letter-queues.html)》。

   1. 選擇**建立訂閱**。

      主控台會建立訂閱並開啟訂閱的 **Details** (詳細資訊) 頁面

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

若要使用 AWS 開發套件，您必須使用登入資料進行設定。如需詳細資訊，請參閱 *AWS SDK和工具參考指南*中的[共享的配置和認證文件](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 ]

**適用於 C\$1\$1 的 SDK**  
 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 ]

**SDK for Go 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 ]

**SDK for Java 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) 的 SDK**  
 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 開發人員指南》](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 詳細資訊，請參閱《適用於 Kotlin 的AWS SDK API 參考》[https://sdk.amazonaws.com/kotlin/api/latest/index.html](https://sdk.amazonaws.com/kotlin/api/latest/index.html)中的 *CreateTopic*。

------
#### [ 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)》。
+  如需 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 詳細資訊，請參閱 *AWS SDK for Python (Boto3) API 參考*中的 [CreateTopic](https://docs.aws.amazon.com/goto/boto3/sns-2010-03-31/CreateTopic)。

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

**SDK for Ruby**  
 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)》。
+  如需 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 詳細資訊，請參閱*適用於 Rust API 的AWS SDK 參考*中的 [CreateTopic](https://docs.rs/aws-sdk-sns/latest/aws_sdk_sns/client/struct.Client.html#method.create_topic)。

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

**適用於 SAP ABAP 的開發套件**  
 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 詳細資訊，請參閱《適用於 SAP ABAP API 的AWS SDK 參考》**中的 [CreateTopic](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)。

------
#### [ 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 詳細資訊，請參閱《適用於 Swift 的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 Config 所需的所有許可 AWS 服務。 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 角色，授予 AWS Config 許可來存取 Amazon S3 儲存貯體、存取 Amazon SNS 主題，以及取得支援 AWS 資源的組態詳細資訊。當您使用主控台建立 IAM 角色時， AWS Config 會自動為您將必要的許可連接至角色。

**注意**  
如果您已使用 AWS 的服務 AWS Config （例如 AWS Security Hub 或 AWS Control Tower) 且已建立 AWS Config 角色，則您應該確保在設定 時所使用的 IAM 角色 AWS Config 保有與已建立 AWS Config 的角色相同的最低權限，以便其他服務 AWS 繼續如預期執行。  
例如，如果 AWS Control Tower 具有允許 AWS Config 讀取 Amazon S3 物件的 IAM 角色，您應該保證在設定時使用的 IAM 角色中授予相同的許可 AWS Config。否則，可能會干擾 AWS Control Tower 的操作。  
如需 IAM 角色的詳細資訊 AWS Config，請參閱 [AWS Identity and Access Management](https://docs.aws.amazon.com/config/latest/developerguide/security-iam.html)。

**為 AWS 服務建立角色**

1. 登入 AWS 管理主控台 並開啟位於 https：//[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 的 IAM 主控台。

1. 在 IAM 主控台的導覽窗格中，選擇 **Roles** (角色)，然後選擇 **Create role** (建立角色)。

1. 對於 **Select trusted entity** (選取信任的實體) 區段，選擇 **AWS service** (AWS 服務)。

1. 選擇您想要的使用案例 AWS Config：**Config - 可自訂**、**Config - Organizations**、**Config** 或 **Config - Conformance Packs**。然後選擇**下一步**。

1. 在 **名稱、檢閱和建立** 頁面中，檢閱角色的詳細資訊，然後選擇 **建立角色**。

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

若要使用 AWS 開發套件，您必須使用登入資料進行設定。如需詳細資訊，請參閱 *AWS SDK和工具參考指南*中的[共享的配置和認證文件](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 Reference* 中的 [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 Reference* 中的 [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"
                }
            ]
        }
    }
}
```
如需詳細資訊，請參閱《*AWS IAM 使用者指南*》中的[修改角色最大工作階段持續時間 (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 ]

**SDK for Go 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 Reference* 中的 [CreateRole](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.CreateRole)。

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

**SDK for Java 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 Reference* 中的 [CreateRole](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/CreateRole)。

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

**SDK for 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 ]

**SDK for PHP**  
 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 Reference* 中的 [CreateRole](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/CreateRole)。

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

**Tools for 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 參考 (V4)》**中的 [CreateRole](https://docs.aws.amazon.com/powershell/v4/reference)。

**Tools for 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 參考 (V5)》**中的 [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 詳細資訊，請參閱 *AWS SDK for Python (Boto3) API Reference* 中的 [CreateRole](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreateRole)。

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

**SDK for Ruby**  
 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 Reference* 中的 [CreateRole](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/CreateRole)。

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

**SDK for Rust**  
 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 詳細資訊，請參閱 *AWS SDK for Rust API reference* 中的 [CreateRole](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.create_role)。

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

**適用於 SAP ABAP 的開發套件**  
 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 詳細資訊，請參閱《適用於 *AWS SAP ABAP 的 SDK API 參考*》中的 [CreateRole](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)。

------
#### [ 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 詳細資訊，請參閱 *AWS SDK for Swift API reference* 中的 [CreateRole](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/createrole(input:))。

------

# 從使用 AWS Config 的客戶受管組態記錄器開始 AWS CLI
<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 Config 具有記錄資源組態變更的許可。 [AWS Organizations](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies.html)此外，規則會直接評估資源的組態，而規則在執行評估時不會考慮這些政策。確定有效政策符合您打算使用的方式 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`的 。
+  AWS Config 傳送組態快照`s3BucketName`的 。
+  AWS Config 傳送通知`snsTopicARN`的 位置
+ `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 時間戳記。