

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# 를 사용하여 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 CLI를 통해 AWS Config를 설정하려면 다음 섹션을 참조하세요.

**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 를 사용하여를 설정하기 전에 사전 조건으로 정책이 연결된 Amazon S3 버킷, Amazon SNS 주제 및 IAM 역할을 생성 AWS CLI해야 합니다. 그런 다음 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. **버킷 이름**에 버킷의 DNS 호환 이름을 입력합니다.

   버킷 이름은 다음과 같아야 합니다.
   + 모든 Amazon S3에서 고유해야 합니다.
   + 3\$163자 이내여야 합니다.
   + 대문자가 없어야 합니다.
   + 소문자 또는 숫자로 시작해야 합니다.

   버킷을 생성한 후에는 해당 이름을 변경할 수 없습니다. 선택하는 버킷 이름은 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. **고급 설정**을 선택하고 나타나는 메시지를 읽습니다.
**중요**  
버킷을 생성할 때만 S3 객체 잠금을 활성화할 수 있습니다. 버킷에 대해 객체 잠금을 활성화하면 나중에 비활성화할 수 없습니다. 객체 잠금을 활성화하면 버킷의 버전 관리도 활성화됩니다. 버킷에 대해 객체 잠금을 활성화한 후 객체 잠금 설정을 구성해야 버킷의 객체가 보호됩니다. 객체의 보호 구성에 대한 자세한 내용은 [Amazon S3 콘솔을 사용하여 S3 객체 잠금 구성](https://docs.aws.amazon.com//AmazonS3/latest/dev/object-lock-console.html)을 참조하세요.

   1. 객체 잠금을 활성화하려면 텍스트 상자에 **enable을 입력하고 **확인(Confirm)**을 선택합니다.

   S3 객체 잠금 기능에 대한 자세한 내용은 **Amazon Simple Storage Service 사용 설명서의 [Amazon S3 객체 잠금을 사용하여 객체 잠금](https://docs.aws.amazon.com//AmazonS3/latest/dev/object-lock.html)을 참조하세요.

1. **버킷 생성**을 선택합니다.

### AWS SDKs 사용
<a name="create-bucket-intro"></a>

 AWS SDKs를 사용하여 버킷을 생성하는 경우 클라이언트를 생성한 다음 클라이언트를 사용하여 버킷 생성 요청을 보내야 합니다. 모범 사례로서, 동일한 AWS 리전에 클라이언트 및 버킷을 만들어야 합니다. 클라이언트나 버킷을 생성할 때 리전을 지정하지 않으면 Amazon S3는 기본 리전인 미국 동부(버지니아 북부)를 사용합니다.

듀얼 스택 엔드포인트에 액세스할 클라이언트를 생성하려면를 지정해야 합니다 AWS 리전. 자세한 내용은 [Amazon S3 듀얼 스택 엔드포인트](https://docs.aws.amazon.com//AmazonS3/latest/dev/dual-stack-endpoints.html#dual-stack-endpoints-description)를 참조하세요. 사용 가능한 목록은의 [리전 및 엔드포인트](https://docs.aws.amazon.com/general/latest/gr/s3.html)를 AWS 리전참조하세요*AWS 일반 참조*.

클라이언트를 만들면 리전은 리전별 엔드포인트로 매핑됩니다. 클라이언트는 `s3.<region>.amazonaws.com` 엔드포인트를 사용하여 Amazon S3와 통신합니다. 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 ]

**SDK for .NET (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 세부 정보는 *AWS SDK for .NET API 참조*의 [CreateBucket](https://docs.aws.amazon.com/goto/DotNetSDKV4/s3-2006-03-01/CreateBucket)을 참조하세요.

**SDK for .NET**  
 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 세부 정보는 *AWS SDK for .NET API 참조*의 [CreateBucket](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/CreateBucket)을 참조하세요.

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

**AWS CLI Bash 스크립트 사용**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/s3#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
###############################################################################
# function iecho
#
# This function enables the script to display the specified text only if
# the global variable $VERBOSE is set to true.
###############################################################################
function iecho() {
  if [[ $VERBOSE == true ]]; then
    echo "$@"
  fi
}

###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

###############################################################################
# function create-bucket
#
# This function creates the specified bucket in the specified AWS Region, unless
# it already exists.
#
# Parameters:
#       -b bucket_name  -- The name of the bucket to create.
#       -r region_code  -- The code for an AWS Region in which to
#                          create the bucket.
#
# Returns:
#       The URL of the bucket that was created.
#     And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function create_bucket() {
  local bucket_name region_code response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function create_bucket"
    echo "Creates an Amazon S3 bucket. You must supply a bucket name:"
    echo "  -b bucket_name    The name of the bucket. It must be globally unique."
    echo "  [-r region_code]    The code for an AWS Region in which the bucket is created."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "b:r:h" option; do
    case "${option}" in
      b) bucket_name="${OPTARG}" ;;
      r) region_code="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done

  if [[ -z "$bucket_name" ]]; then
    errecho "ERROR: You must provide a bucket name with the -b parameter."
    usage
    return 1
  fi

  local bucket_config_arg
  # A location constraint for "us-east-1" returns an error.
  if [[ -n "$region_code" ]] && [[ "$region_code" != "us-east-1" ]]; then
    bucket_config_arg="--create-bucket-configuration LocationConstraint=$region_code"
  fi

  iecho "Parameters:\n"
  iecho "    Bucket name:   $bucket_name"
  iecho "    Region code:   $region_code"
  iecho ""

  # If the bucket already exists, we don't want to try to create it.
  if (bucket_exists "$bucket_name"); then
    errecho "ERROR: A bucket with that name already exists. Try again."
    return 1
  fi

  # shellcheck disable=SC2086
  response=$(aws s3api create-bucket \
    --bucket "$bucket_name" \
    $bucket_config_arg)

  # shellcheck disable=SC2181
  if [[ ${?} -ne 0 ]]; then
    errecho "ERROR: AWS reports create-bucket operation failed.\n$response"
    return 1
  fi
}
```
+  API 세부 정보는 **AWS CLI 명령 참조의 [CreateBucket](https://docs.aws.amazon.com/goto/aws-cli/s3-2006-03-01/CreateBucket)을 참조하세요.

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

**SDK for C\$1\$1**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

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

    if (clientConfig.region != "us-east-1") {
        Aws::S3::Model::CreateBucketConfiguration createBucketConfig;
        createBucketConfig.SetLocationConstraint(
                Aws::S3::Model::BucketLocationConstraintMapper::GetBucketLocationConstraintForName(
                        clientConfig.region));
        request.SetCreateBucketConfiguration(createBucketConfig);
    }

    Aws::S3::Model::CreateBucketOutcome outcome = client.CreateBucket(request);
    if (!outcome.IsSuccess()) {
        auto err = outcome.GetError();
        std::cerr << "Error: createBucket: " <<
                  err.GetExceptionName() << ": " << err.GetMessage() << std::endl;
    } else {
        std::cout << "Created bucket " << bucketName <<
                  " in the specified AWS Region." << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 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` 예시에서는 S3 객체 소유권에 대해 버킷 소유자 적용 설정을 사용하는 `amzn-s3-demo-bucket`이라는 버킷을 생성합니다.  

```
aws s3api create-bucket \
    --bucket amzn-s3-demo-bucket \
    --region us-east-1 \
    --object-ownership BucketOwnerEnforced
```
출력:  

```
{
    "Location": "/amzn-s3-demo-bucket"
}
```
자세한 내용은 [Amazon S3 사용자 안내서](https://docs.aws.amazon.com/AmazonS3/latest/userguide/about-object-ownership.html)의 *객체 소유권 제어 및 ACL 비활성화*를 참조하세요.  
**예시 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 세부 정보는 *AWS SDK for Go 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 ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/s3#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
버킷을 생성합니다.  

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

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

  try {
    const { Location } = await client.send(
      new CreateBucketCommand({
        // The name of the bucket. Bucket names are unique and have several other constraints.
        // See https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucketnamingrules.html
        Bucket: bucketName,
      }),
    );
    await waitUntilBucketExists({ client }, { Bucket: bucketName });
    console.log(`Bucket created with location ${Location}`);
  } catch (caught) {
    if (caught instanceof BucketAlreadyExists) {
      console.error(
        `The bucket "${bucketName}" already exists in another AWS account. Bucket names must be globally unique.`,
      );
    }
    // WARNING: If you try to create a bucket in the North Virginia region,
    // and you already own a bucket in that region with the same name, this
    // error will not be thrown. Instead, the call will return successfully
    // and the ACL on that bucket will be reset.
    else if (caught instanceof BucketAlreadyOwnedByYou) {
      console.error(
        `The bucket "${bucketName}" already exists in this AWS account.`,
      );
    } else {
      throw caught;
    }
  }
};
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/s3-example-creating-buckets.html#s3-example-creating-buckets-new-bucket-2)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [CreateBucket](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/CreateBucketCommand)을 참조하세요.

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

**SDK for Kotlin**  
 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 세부 정보는 *AWS SDK for Kotlin API 참조*의 [CreateBucket](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하세요.

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

**SDK for PHP**  
 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 세부 정보는 *AWS SDK for PHP API 참조*의 [CreateBucket](https://docs.aws.amazon.com/goto/SdkForPHPV3/s3-2006-03-01/CreateBucket)을 참조하세요.

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

**SDK for Python (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 세부 정보는 *AWS SDK for Python (Boto3) 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 세부 정보는 *AWS SDK for Ruby API 참조*의 [CreateBucket](https://docs.aws.amazon.com/goto/SdkForRubyV3/s3-2006-03-01/CreateBucket)을 참조하세요.

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

**SDK for Rust**  
 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 세부 정보는 *AWS SDK for Rust API 참조*의 [CreateBucket](https://docs.rs/aws-sdk-s3/latest/aws_sdk_s3/client/struct.Client.html#method.create_bucket)을 참조하세요.

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

**SDK for SAP ABAP API**  
 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 세부 정보는AWS *SDK for SAP ABAP API*의 [CreateBucket](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)을 참조하세요.

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

**SDK for Swift**  
 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 세부 정보는 *AWS SDK for Swift 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. **주제 생성** 페이지의 **세부 정보** 섹션에서 다음을 수행합니다.

   1. **유형**에서 주제 유형(**표준** 또는 **FIFO**을 선택합니다.

   1. 주제의 **이름**을 입력합니다. [FIFO 주제](https://docs.aws.amazon.com/sns/latest/dg/sns-fifo-topics.html)의 경우 이름 끝에 **.fifo**를 추가합니다.

   1. (선택 사항) 주제의 **표시 이름**을 입력합니다.

   1. (선택 사항) FIFO 주제의 경우 **콘텐츠 기반 메시지 중복 제거**를 선택하여 기본 메시지 중복 제거를 활성화할 수 있습니다. 자세한 내용은 [FIFO 주제에 대한 메시지 중복 제거](https://docs.aws.amazon.com/sns/latest/dg/fifo-message-dedup.html)를 참조하세요.

1. (선택 사항) **암호화** 섹션을 확장하고 다음을 수행합니다. 자세한 내용은 [저장된 데이터 암호화](https://docs.aws.amazon.com/sns/latest/dg/sns-server-side-encryption.html)를 참조하세요.

   1. **암호화 활성**을 선택합니다.

   1. 고객 마스터 키(CMK)를 지정합니다. 자세한 내용을 알아보려면 [주요 용어](https://docs.aws.amazon.com/sns/latest/dg/sns-server-side-encryption.html#sse-key-terms)를 참조하세요.

      각 CMK 유형에 대해 **설명**, **계정** 및 **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 Management Console 를 사용하여 주제에 대한 Amazon SNS용 AWS 관리형 CMK를 처음 지정하면가 Amazon SNS용 AWS 관리형 CMK를 AWS KMS 생성합니다.
또는 SSE가 활성화된 주제에 대해 `Publish` 작업을 처음 사용할 때가 Amazon SNS용 AWS 관리형 CMK를 AWS KMS 생성합니다.
      + 에서 사용자 지정 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. (선택 사항) 기본적으로 주제 소유자만 주제에 게시하거나 주제를 구독할 수 있습니다. 추가 액세스 권한을 구성하려면 **액세스 정책** 섹션을 확장합니다. 자세한 내용은 [Amazon SNS의 Identity and Access Management](https://docs.aws.amazon.com/sns/latest/dg/sns-authentication-and-access-control.html) 및 [Amazon SNS 액세스 제어의 예제 사례](https://docs.aws.amazon.com/sns/latest/dg/sns-access-policy-use-cases.html)를 참조하세요.
**참고**  
콘솔을 사용하여 주제를 생성하는 경우 기본 정책은 `aws:SourceOwner` 조건 키를 사용합니다. 이 키는 `aws:SourceAccount`와 비슷합니다.

1. (선택 사항) Amazon SNS가 실패한 메시지 전송을 재시도하는 방식을 구성하려면 **전송 재시도 정책(HTTP/S)** 섹션을 확장합니다. 자세한 내용은 [Amazon SNS 메시지 전달 재시도](https://docs.aws.amazon.com/sns/latest/dg/sns-message-delivery-retries.html)를 참조하세요.

1. (선택 사항) Amazon SNS가 CloudWatch로의 메시지 전송을 로깅하는 방식을 구성하려면 **전송 상태 로깅** 섹션을 확장합니다. 자세한 내용은 [Amazon SNS 메시지 전달 상태](https://docs.aws.amazon.com/sns/latest/dg/sns-topic-attributes.html)를 참조하세요.

1. (선택 사항) 메타데이터 태그를 주제에 추가하려면 **태그** 섹션을 확장하고, **키**와 **값**(옵션)을 입력한 다음 **태그 추가**를 선택합니다. 자세한 내용은 [Amazon SNS 주제 태그 지정](https://docs.aws.amazon.com/sns/latest/dg/sns-tags.html)을 참조하세요.

1. **주제 생성**을 선택합니다.

   주제가 생성되고 ***MyTopic*** 페이지가 표시됩니다.

   주제의 **이름**, **ARN**, (선택 사항) **표시 이름** 및 **주제 소유자** AWS 계정 ID가 **세부 정보** 섹션에 표시됩니다.

1. 다음 예와 같이 주제 ARN을 클립보드에 복사합니다.

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

**이메일 주소에서 Amazon SNS 주제를 구독하려면**

1. [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. **프로토콜**에서 엔드포인트 유형을 선택합니다.  사용 가능한 엔드포인트 유형은 다음과 같습니다.
      + [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)
      + [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. **엔드포인트**에 이메일 주소 또는 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. (선택 사항) 필터 정책을 구성하려면 **구독 필터 정책** 섹션을 확장합니다. 자세한 내용은 [Amazon SNS 구독 필터 정책](https://docs.aws.amazon.com/sns/latest/dg/sns-subscription-filter-policies.html)을 참조하세요.

   1. (선택 사항) 구독에 대한 배달 못한 편지 대기열을 구성하려면 **리드라이브 정책(배달 못한 편지 대기열)** 섹션을 확장합니다. 자세한 내용은 [Amazon SQS DLQ(Dead Letter Queue)](https://docs.aws.amazon.com/sns/latest/dg/sns-dead-letter-queues.html)를 참조하세요.

   1. **구독 생성**을 선택합니다.

      콘솔에서 구독을 만들고 구독의 **세부 정보** 페이지를 엽니다.

### AWS SDKs 사용
<a name="create-snstopic-intro"></a>

 AWS SDK를 사용하려면 자격 증명으로 구성해야 합니다. [자세한 정보는 *AWS SDK 및 도구 참조 가이드*의 공유 구성 및 자격 증명 파일](https://docs.aws.amazon.com/sdkref/latest/guide/creds-config-files.html)을 참조하세요.

다음 코드 예시는 `CreateTopic`의 사용 방법을 보여 줍니다.

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

**SDK for .NET**  
 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 세부 정보는 *AWS SDK for .NET API 참조*의 [CreateTopic](https://docs.aws.amazon.com/goto/DotNetSDKV3/sns-2010-03-31/CreateTopic)을 참조하세요.

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

**SDK for C\$1\$1**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sns#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
//! Create an Amazon Simple Notification Service (Amazon SNS) topic.
/*!
  \param topicName: An Amazon SNS topic name.
  \param topicARNResult: String to return the Amazon Resource Name (ARN) for the topic.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SNS::createTopic(const Aws::String &topicName,
                              Aws::String &topicARNResult,
                              const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SNS::SNSClient snsClient(clientConfiguration);

    Aws::SNS::Model::CreateTopicRequest request;
    request.SetName(topicName);

    const Aws::SNS::Model::CreateTopicOutcome outcome = snsClient.CreateTopic(request);

    if (outcome.IsSuccess()) {
        topicARNResult = outcome.GetResult().GetTopicArn();
        std::cout << "Successfully created an Amazon SNS topic " << topicName
                  << " with topic ARN '" << topicARNResult
                  << "'." << std::endl;

    }
    else {
        std::cerr << "Error creating topic " << topicName << ":" <<
                  outcome.GetError().GetMessage() << std::endl;
        topicARNResult.clear();
    }

    return outcome.IsSuccess();
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 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 세부 정보는 *AWS SDK for Go 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 ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sns#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
별도의 모듈에서 클라이언트를 생성하고 내보냅니다.  

```
import { SNSClient } from "@aws-sdk/client-sns";

// The AWS Region can be provided here using the `region` property. If you leave it blank
// the SDK will default to the region set in your AWS config.
export const snsClient = new SNSClient({});
```
SDK 및 클라이언트 모듈을 가져오고 API를 호출합니다.  

```
import { CreateTopicCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {string} topicName - The name of the topic to create.
 */
export const createTopic = async (topicName = "TOPIC_NAME") => {
  const response = await snsClient.send(
    new CreateTopicCommand({ Name: topicName }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '087b8ad2-4593-50c4-a496-d7e90b82cf3e',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   TopicArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:TOPIC_NAME'
  // }
  return response;
};
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/sns-examples-managing-topics.html#sns-examples-managing-topics-createtopic)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [CreateTopic](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sns/command/CreateTopicCommand)을 참조하세요.

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

**SDK for Kotlin**  
 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 세부 정보는 *AWS SDK for Kotlin API 참조*의 [CreateTopic](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하세요.

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

**SDK for PHP**  
 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());
}
```
+  자세한 정보는 [AWS SDK for PHP 개발자 안내서](https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/sns-examples-managing-topics.html#create-a-topic)를 참조하세요.
+  API 세부 정보는 *AWS SDK for PHP API 참조*의 [CreateTopic](https://docs.aws.amazon.com/goto/SdkForPHPV3/sns-2010-03-31/CreateTopic)을 참조하세요.

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

**SDK for Python (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
```
+  자세한 정보는 [AWS SDK for Ruby 개발자 안내서](https://docs.aws.amazon.com/sdk-for-ruby/v3/developer-guide/sns-example-create-topic.html)를 참조하세요.
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [CreateTopic](https://docs.aws.amazon.com/goto/SdkForRubyV3/sns-2010-03-31/CreateTopic)을 참조하세요.

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

**SDK for Rust**  
 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 세부 정보는 *AWS SDK for Rust API 참조*의 [CreateTopic](https://docs.rs/aws-sdk-sns/latest/aws_sdk_sns/client/struct.Client.html#method.create_topic)을 참조하세요.

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

**SDK for SAP ABAP API**  
 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용AWS SDK API 참조*의 [CreateTopic](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)을 참조하세요.

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

**SDK for Swift**  
 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 세부 정보는 *AWS SDK for Swift 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 콘솔을 사용하여 Amazon S3 버킷에 액세스하고, Amazon SNS 주제에 액세스하고, 지원되는 AWS 리소스에 대한 구성 세부 정보를 가져올 수 있는 AWS Config 권한을 부여하는 IAM 역할을 생성할 수 있습니다. 콘솔을 사용하여 IAM 역할을 생성하면 AWS Config 가 해당 역할에 필요한 권한을 자동으로 연결합니다.

**참고**  
가 사용하는 AWS 서비스 AWS Config (예: AWS Security Hub 또는 AWS Control Tower)를 사용했고 AWS Config 역할이 이미 생성된 경우 다른 AWS 서비스가 예상대로 계속 실행되도록 설정 시 사용하는 IAM 역할이 이미 생성된 AWS Config 역할과 동일한 최소 권한을 AWS Config 유지하는지 확인해야 합니다.  
예를 들어 AWS Control Tower에가 Amazon S3 객체를 읽을 AWS Config 수 있도록 허용하는 IAM 역할이 있는 경우 설정 시 사용하는 IAM 역할 내에서 동일한 권한이 부여되도록 해야 합니다 AWS Config. 그렇지 않으면 AWS Control Tower의 작업을 방해할 수 있습니다.  
의 IAM 역할에 대한 자세한 내용은 [AWS Identity and Access Management](https://docs.aws.amazon.com/config/latest/developerguide/security-iam.html)를 AWS Config참조하세요.

**AWS 서비스에 대한 역할을 생성하려면**

1. 에 로그인 AWS Management Console 하고 [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) IAM 콘솔을 엽니다.

1. IAM 콘솔의 탐색 창에서 **역할**을 선택하고 **역할 생성**을 선택합니다.

1. **신뢰할 수 있는 엔터티 선택(Select trusted entity)**에서 **AWS 서비스( service)**를 선택합니다.

1. **Config - Customizable**, AWS Config**Config - Organizations**, **Config** 또는 **Config - Conformance Packs** 중에서 원하는 사용 사례를 선택합니다. 그리고 **다음**을 선택합니다.

1. **이름 지정, 검토 및 생성** 페이지에서 역할에 대한 세부 정보를 검토한 후 **역할 생성**을 선택합니다.

### AWS SDKs 사용
<a name="create-iamrole-intro"></a>

 AWS SDK를 사용하려면 자격 증명으로 구성해야 합니다. [자세한 정보는 *AWS SDK 및 도구 참조 가이드*의 공유 구성 및 자격 증명 파일](https://docs.aws.amazon.com/sdkref/latest/guide/creds-config-files.html)을 참조하세요.

다음 코드 예시는 `CreateRole`의 사용 방법을 보여 줍니다.

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

**SDK for .NET**  
 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 세부 정보는 [AWS SDK for .NET API 참조](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/CreateRole)의 *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 세부 정보는 [AWS SDK for C\$1\$1 API 참조](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/CreateRole)의 *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`인 역할을 생성하고 최대 세션 지속 시간을 7,200초(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 형식의 태그(`'{"Key": "Department", "Value": "Accounting"}' '{"Key": "Location", "Value": "Seattle"}'`)에 `--tags` 파라미터 플래그를 사용합니다. 또는 `--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 세부 정보는 [AWS SDK for Go API 참조](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.CreateRole)의 *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 참조](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/CreateRole)의 *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 세부 정보는 [AWS SDK for JavaScript API 참조](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreateRoleCommand)의 *CreateRole*을 참조하세요.

------
#### [ 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 세부 정보는 [AWS SDK for PHP API 참조](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/CreateRole)의 *CreateRole*을 참조하세요.

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

**Tools for PowerShell V4**  
**예제 1: 이 예제는 `MyNewRole`이라는 새 역할을 생성하고 여기에 `NewRoleTrustPolicy.json` 파일에 있는 정책을 연결합니다. JSON 정책 파일을 성공적으로 처리하려면 `-Raw` 스위치 파라미터를 사용해야 합니다. 출력에 표시된 정책 문서는 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` 파일에 있는 정책을 연결합니다. JSON 정책 파일을 성공적으로 처리하려면 `-Raw` 스위치 파라미터를 사용해야 합니다. 출력에 표시된 정책 문서는 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 ]

**SDK for Python(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 참조*의 [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 세부 정보는 [AWS SDK for Ruby API 참조](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/CreateRole)의 *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 참조*의 [CreateRole](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.create_role)을 참조하세요.

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

**SDK for SAP ABAP API**  
 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 SDK for SAP ABAP API 참조*의 [CreateRole](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)을 참조하세요.

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

**SDK for Swift**  
 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 참조*의 [CreateRole](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/createrole(input:))을 참조하세요.

------

# AWS CLI를 사용하여 고객 관리형 구성 레코더로 AWS Config 시작
<a name="gs-cli-subscribe"></a>

고객 관리형 구성 레코더를 생성하여 AWS Config를 시작할 수 있습니다. AWS CLI를 사용하여 고객 관리형 구성 레코더를 생성하려면, [https://docs.aws.amazon.com/cli/latest/reference/configservice/put-configuration-recorder.html](https://docs.aws.amazon.com/cli/latest/reference/configservice/put-configuration-recorder.html), [https://docs.aws.amazon.com/cli/latest/reference/configservice/put-delivery-channel.html](https://docs.aws.amazon.com/cli/latest/reference/configservice/put-delivery-channel.html) 및 [https://docs.aws.amazon.com/cli/latest/reference/configservice/start-configuration-recorder.html](https://docs.aws.amazon.com/cli/latest/reference/configservice/start-configuration-recorder.html) 명령을 사용합니다.
+ 이 `put-configuration-recorder` 명령은 고객 관리형 구성 레코더를 생성합니다.
+ `put-delivery-channel` 명령은 전송 채널을 생성하여 AWS Config가 구성 정보를 S3 버킷 및 SNS 주제로 전송합니다.
+ `start-configuration-recorder`는 고객 관리형 구성 레코더를 시작합니다. 고객 관리형 구성 레코더는 지정한 리소스 유형에 대한 구성 변경 사항을 기록하기 시작합니다.

**Topics**
+ [고려 사항](#gs-cli-subscribe-considerations)
+ [1단계: put-configuration-recorder 실행](#gs-cli-subscribe-put-configuration-recorder)
+ [2단계: put-delivery-channel 명령 실행](#gs-cli-subscribe-put-delivery-channel)
+ [3단계: start-configuration-recorder 명령 실행](#gs-cli-subscribe-start-configuration-recorder)

## 고려 사항
<a name="gs-cli-subscribe-considerations"></a>

**S3 버킷, SNS 주제 및 IAM 역할이 필요**

고객 관리형 구성 레코더를 생성하려면 전제 조건으로 정책이 연결된 S3 버킷, SNS 주제 및 IAM 역할을 생성해야 합니다. AWS Config 사전 조건을 설정하려면 [사전 조건](https://docs.aws.amazon.com/config/latest/developerguide/gs-cli-prereq.html)을 참조하세요.

**리전별 계정당 고객 관리형 구성 레코더 1개**

각 AWS 리전에 대해 AWS 계정 각각 하나의 고객 관리형 구성 레코더만 가질 수 있습니다.

**리전별 계정당 전송 채널 1개**

각 AWS 리전에 대해 AWS 계정 각각 하나의 전송 채널 리전만 가질 수 있습니다.

**정책 및 규정 준수 결과**

[IAM 정책](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html) 및 [AWS Organizations에서 관리되는 기타 정책](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies.html)은 AWS Config에 리소스에 대한 구성 변경을 기록할 권한이 있는지 여부에 영향을 미칠 수 있습니다. 또한 규칙은 리소스의 구성을 직접 평가하며, 규칙은 평가를 실행할 때 이러한 정책을 고려하지 않습니다. 적용 중인 정책이 AWS Config 사용 의도와 일치하는지 확인합니다.

## 1단계: put-configuration-recorder 실행
<a name="gs-cli-subscribe-put-configuration-recorder"></a>

[https://docs.aws.amazon.com/cli/latest/reference/configservice/put-configuration-recorder.html](https://docs.aws.amazon.com/cli/latest/reference/configservice/put-configuration-recorder.html) 명령을 사용하여 고객 관리형 구성 레코더를 생성합니다.

이 명령은 `--configuration-recorder` 및 `---recording-group` 필드를 사용합니다.

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

**`configuration-recorder` 필드**

`configurationRecorder.json` 파일이 `name`, `roleArn` 및 구성 레코더(`recordingMode`)의 기본 기록 빈도를 지정합니다. 이 필드를 사용하여 특정 리소스 유형의 기록 빈도를 재정의할 수도 있습니다.

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

**`recording-group` 필드**

`recordingGroup.json` 파일은 기록되는 리소스 유형을 지정합니다.

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

이러한 필드에 대한 자세한 내용은 **AWS CLI 명령 참조의 [https://docs.aws.amazon.com/cli/latest/reference/configservice/put-configuration-recorder.html](https://docs.aws.amazon.com/cli/latest/reference/configservice/put-configuration-recorder.html) 섹션을 참조하세요.

## 2단계: put-delivery-channel 명령 실행
<a name="gs-cli-subscribe-put-delivery-channel"></a>

[https://docs.aws.amazon.com/cli/latest/reference/configservice/put-delivery-channel.html](https://docs.aws.amazon.com/cli/latest/reference/configservice/put-delivery-channel.html) 명령을 사용하여 전송 채널을 만듭니다.

이 명령은 `--delivery-channel` 필드를 사용합니다.

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

**`delivery-channel` 필드**

`deliveryChannel.json` 파일이 지정하는 것은 다음과 같습니다.
+ 전송 채널의 `name`.
+ AWS Config가 구성 스냅샷을 전송하는 `s3BucketName`.
+ AWS Config가 알림을 보내는 `snsTopicARN`.
+ AWS Config가 구성 스냅샷을 전송하는 빈도와 주기적 규칙에 대한 평가를 간접 호출하는 빈도를 설정하는 `configSnapshotDeliveryProperties`.

```
{
    "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 CLI 명령을 사용하여가 실행 AWS Config 중이고 구성 레코더와 전송 채널을 생성 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 타임스탬프로 표시됩니다.