

# AWS CLI의 안내식 명령 예제
<a name="cli-chap-services"></a>

AWS Command Line Interface(AWS CLI)는 명령줄 쉘의 명령을 사용하여 다양한 AWS 서비스와 상호 작용할 수 있는 오픈 소스 도구입니다. 이 섹션에서는 AWS CLI를 활용하여 일부 AWS 서비스에 액세스하는 방법을 보여주는 안내 예제를 제공합니다. 여기에는 상위 수준 `aws s3` 명령과 같은 일부 사용자 지정 AWS CLI 명령이 포함됩니다. 이러한 명령 예제는 일부 AWS 서비스에 사용되는 일반적인 작업을 보여 주며 자세한 내용은 추가 리소스를 제공합니다.

숙련된 AWS 사용자든 처음 AWS CLI를 사용하는 사용자든 이 사용 설명서는 AWS 운영을 간소화하는 데 도움이 되는 리소스입니다.

각 AWS 서비스에 대해 사용 가능한 모든 명령어에 대한 전체 참조는 [AWS CLI 버전 2 참조 안내서](https://docs.aws.amazon.com/cli/latest/reference/index.html)를 참조하세요. 또한 [기본 제공 명령줄 도움말](cli-usage-help.md)을 활용하여 AWS 서비스, AWS CLI의 명령, 옵션 및 기능 배열을 탐색할 수 있습니다.

이 섹션에서 사용할 수 없는 더 많은 명령 예제는 [AWS CLI 명령 예제](cli_code_examples.md) 섹션을 참조하세요. 이러한 예제는 [AWS CLI 버전 2 참조 안내서](https://docs.aws.amazon.com/cli/latest/reference/index.html)에서도 확인할 수 있는 오픈 소스 명령어 예제입니다. 명령 예제는 *GitHub*의 [AWS CLI](https://github.com/aws/aws-cli/tree/develop/awscli/examples) 리포지토리에서 호스팅됩니다.



 오픈 소스 bash 스크립팅 예제는 [Bash 스크립트와 함께 AWS CLI 사용 예제](bash_code_examples.md) 섹션을 참조하세요. Bash 스크립팅 예제는 *GitHub*의 [AWS 코드 예제 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples)에서 호스팅됩니다.

**Topics**
+ [DynamoDB](cli-services-dynamodb.md)
+ [Amazon EC2](cli-services-ec2.md)
+ [Amazon Glacier](cli-services-glacier.md)
+ [IAM](cli-services-iam.md)
+ [Amazon S3](cli-services-s3.md)
+ [Amazon SNS](cli-services-sns.md)

# AWS CLI의 Amazon DynamoDB 사용
<a name="cli-services-dynamodb"></a>

AWS Command Line Interface(AWS CLI)는 Amazon DynamoDB를 포함한 AWS 데이터베이스 서비스를 모두 지원합니다. 테이블 생성과 같이 특별 작업을 수행할 때 AWS CLI를 사용할 수 있습니다. 또한 이를 사용하여 DynamoDB 작업을 유틸리티 스크립트 내에 포함할 수 있습니다.

DynamoDB와 함께 AWS CLI를 사용하는 방법에 대한 자세한 내용은 *AWS CLI 명령 참조*에서 ```[dynamodb](https://docs.aws.amazon.com/cli/latest/reference/dynamodb/index.html)` 섹션을 참조하세요.

DynamoDB에 대한 AWS CLI 명령을 나열하려면 다음 명령을 사용합니다.

```
$ aws dynamodb help
```

**Topics**
+ [사전 조건](#cli-services-dynamodb-prereqs)
+ [DynamoDB 테이블 생성 및 사용](#cli-services-dynamodb-using)
+ [DynamoDB Local 사용](#cli-services-dynamodb-local)
+ [리소스](#cli-services-dynamodb-resources)

## 사전 조건
<a name="cli-services-dynamodb-prereqs"></a>

`dynamodb` 명령을 실행하려면 다음을 수행해야 합니다.
+ AWS CLI를 설치하고 구성합니다. 자세한 내용은 [최신 버전의 AWS CLI 설치 또는 업데이트](getting-started-install.md) 및 [AWS CLI에 대한 인증 및 액세스 보안 인증](cli-chap-authentication.md)(을)를 참조하세요.

## DynamoDB 테이블 생성 및 사용
<a name="cli-services-dynamodb-using"></a>

명령줄 형식은 DynamoDB 명령 이름과 해당 명령에 대한 파라미터 순서로 구성됩니다. AWS CLI는 파라미터 값의 CLI [간편 구문](cli-usage-shorthand.md)과 전체 JSON을 지원합니다.

다음 예제에서는 `MusicCollection`이라는 테이블을 생성합니다.

```
$ aws dynamodb create-table \
    --table-name MusicCollection \
    --attribute-definitions AttributeName=Artist,AttributeType=S AttributeName=SongTitle,AttributeType=S \
    --key-schema AttributeName=Artist,KeyType=HASH AttributeName=SongTitle,KeyType=RANGE \
    --provisioned-throughput ReadCapacityUnits=1,WriteCapacityUnits=1
```

다음 예제와 유사한 명령을 사용하여 새 줄을 테이블에 추가할 수 있습니다. 본 예제에서 간편 구문과 JSON이 함께 사용됩니다.

```
$ aws dynamodb put-item \
    --table-name MusicCollection \
    --item '{
        "Artist": {"S": "No One You Know"},
        "SongTitle": {"S": "Call Me Today"} ,
        "AlbumTitle": {"S": "Somewhat Famous"} 
      }' \
    --return-consumed-capacity TOTAL
{
    "ConsumedCapacity": {
        "CapacityUnits": 1.0,
        "TableName": "MusicCollection"
    }
}
```

```
$ aws dynamodb put-item \
    --table-name MusicCollection \
    --item '{ 
        "Artist": {"S": "Acme Band"}, 
        "SongTitle": {"S": "Happy Day"} , 
        "AlbumTitle": {"S": "Songs About Life"} 
      }' \
    --return-consumed-capacity TOTAL
{
    "ConsumedCapacity": {
        "CapacityUnits": 1.0,
        "TableName": "MusicCollection"
    }
}
```

한 줄 명령에서는 유효한 JSON을 작성하기가 어려울 수 있습니다. 이를 쉽게 하기 위해 AWS CLI는 JSON 파일을 읽을 수 있습니다. 예를 들어 `expression-attributes.json`이라는 파일에 저장된 JSON 코드 조각을 고려해 보세요.

```
{
  ":v1": {"S": "No One You Know"},
  ":v2": {"S": "Call Me Today"}
}
```

이 파일을 사용하면 `query`를 사용하여 AWS CLI 요청을 발행할 수 있습니다. 다음 예제에서는 `expression-attributes.json` 파라미터의 값으로 `--expression-attribute-values` 파일의 콘텐츠가 사용됩니다.

```
$ aws dynamodb query --table-name MusicCollection \
    --key-condition-expression "Artist = :v1 AND SongTitle = :v2" \
    --expression-attribute-values file://expression-attributes.json
{
    "Count": 1,
    "Items": [
        {
            "AlbumTitle": {
                "S": "Somewhat Famous"
            },
            "SongTitle": {
                "S": "Call Me Today"
            },
            "Artist": {
                "S": "No One You Know"
            }
        }
    ],
    "ScannedCount": 1,
    "ConsumedCapacity": null
}
```

## DynamoDB Local 사용
<a name="cli-services-dynamodb-local"></a>

DynamoDB에 더해 DynamoDB Local에도 AWS CLI를 사용할 수 있습니다. DynamoDB Local은 DynamoDB 서비스를 모방하는 클라이언트 측 소형 데이터베이스 및 서버입니다. DynamoDB Local을 사용하면 DynamoDB 웹 서비스의 테이블 또는 데이터를 조작하지 않고도 DynamoDB API를 사용하는 애플리케이션을 쓸 수 있습니다. 그 대신 모든 API 작업이 로컬 데이터베이스로 재라우팅됩니다. 이를 통해 프로비저닝된 처리량, 데이터 스토리지 및 데이터 전송 요금을 절감할 수 있습니다.

DynamoDB Local 및 AWS CLI와 함께 이를 사용하는 방법에 대한 자세한 내용은 [Amazon DynamoDB 개발자 안내서](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/)에서 다음 섹션을 참조하세요.
+ [DynamoDB Local](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Tools.DynamoDBLocal.html)
+ [DynamoDB Local과 함께 AWS CLI 사용](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Tools.CLI.html#UsingWithDDBLocal)

## 리소스
<a name="cli-services-dynamodb-resources"></a>

**AWS CLI 참조: **
+ [https://docs.aws.amazon.com/cli/latest/reference/dynamodb/index.html](https://docs.aws.amazon.com/cli/latest/reference/dynamodb/index.html)
+ [https://docs.aws.amazon.com/cli/latest/reference/dynamodb/create-table.html](https://docs.aws.amazon.com/cli/latest/reference/dynamodb/create-table.html)
+ [https://docs.aws.amazon.com/cli/latest/reference/dynamodb/put-item.html](https://docs.aws.amazon.com/cli/latest/reference/dynamodb/put-item.html)
+ [https://docs.aws.amazon.com/cli/latest/reference/dynamodb/query.html](https://docs.aws.amazon.com/cli/latest/reference/dynamodb/query.html)

**서비스 참조:**
+ Amazon DynamoDB 개발자 안내서의 [DynamoDB Local](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Tools.DynamoDBLocal.html)
+ Amazon DynamoDB 개발자 안내서의 [AWS CLI에서 DynamoDB Local 사용](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Tools.CLI.html#UsingWithDDBLocal)

# AWS CLI에서 Amazon EC2 사용
<a name="cli-services-ec2"></a>


| Amazon Elastic Compute Cloud 소개 | 
| --- | 
|  [![AWS Videos](http://img.youtube.com/vi/https://www.youtube.com/embed/TsRBftzZsQo/0.jpg)](http://www.youtube.com/watch?v=https://www.youtube.com/embed/TsRBftzZsQo)  | 

Amazon Elastic Compute Cloud(Amazon EC2)는 확장성과 유연성이 뛰어난 가상 컴퓨팅 환경을 제공합니다. Amazon EC2를 사용하면 다양한 컴퓨팅 요구 사항을 충족하기 위해 Amazon EC2 인스턴스라고 하는 가상 서버를 프로비저닝하고 관리할 수 있습니다.

Amazon EC2 인스턴스는 CPU, 메모리, 스토리지 및 네트워킹 기능의 다양한 구성으로 사용자 지정할 수 있는 가상 머신입니다. 애플리케이션 요구 사항에 따라 가볍고 비용 효율적인 옵션부터 강력한 고성능 인스턴스까지 다양한 인스턴스 유형 중에서 선택할 수 있습니다. 이러한 유연성을 통해 컴퓨팅 요구 사항을 충족하여 성능과 비용 효율성을 최적화할 수 있습니다.

또한 Amazon EC2는 컴퓨팅 리소스를 효과적으로 관리할 수 있는 다양한 기능을 제공합니다. 여기에는 새 인스턴스를 빠르게 시작하고, 신속한 배포를 위해 사용자 지정 머신 이미지(AMI)를 생성하고, 필요에 따라 컴퓨팅 용량을 늘리거나 줄일 수 있는 기능이 포함됩니다.

AWS Command Line Interface(AWS CLI)를 사용하여 Amazon EC2의 기능에 액세스할 수 있습니다. Amazon EC2에 대한 AWS CLI 명령을 나열하려면 다음 명령을 사용합니다.

```
aws ec2 help
```

명령을 실행하기 전에 기본 자격 증명을 설정합니다. 자세한 내용은 [AWS CLI 설정 구성](cli-chap-configure.md) 섹션을 참조하세요.

이 주제에서는 Amazon EC2에 대한 일반적인 태스크를 수행하는 짧은 형식의 AWS CLI 명령 예제를 보여줍니다.

긴 형식의 AWS CLI 명령 예제는 *GitHub*에서 [AWS CLI 코드 예제 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli)를 참조하세요.

**Topics**
+ [AWS CLI에서 Amazon EC2 키 페어 생성, 표시 및 삭제](cli-services-ec2-keypairs.md)
+ [AWS CLI에서 Amazon EC2 보안 그룹 생성, 구성 및 삭제](cli-services-ec2-sg.md)
+ [AWS CLI에서 Amazon EC2 인스턴스 시작, 나열 및 삭제](cli-services-ec2-instances.md)
+ [AWS CLI에서 bash 스크립트로 Amazon EC2 인스턴스 유형 변경](cli-services-ec2-instance-type-script.md)

# AWS CLI에서 Amazon EC2 키 페어 생성, 표시 및 삭제
<a name="cli-services-ec2-keypairs"></a>

AWS Command Line Interface(AWS CLI)를 사용하여 Amazon Elastic Compute Cloud(Amazon EC2)에 대한 키 페어를 생성, 표시 및 삭제할 수 있습니다. 키 페어를 사용하여 Amazon EC2 인스턴스에 연결합니다. 인스턴스를 생성할 때 Amazon EC2에 키 페어를 제공한 다음, 인스턴스에 연결할 때 해당 키 페어를 사용하여 인증할 수 있습니다.

**참고**  
추가 명령 예제는 [AWS CLI 참조 가이드](https://docs.aws.amazon.com/cli/latest/reference/index.html)를 참조하세요.

**Topics**
+ [사전 조건](#cli-services-ec2-keypairs-prereqs)
+ [키 페어 생성](#creating-a-key-pair)
+ [키 페어 표시](#displaying-a-key-pair)
+ [키 페어 삭제](#deleting-a-key-pair)
+ [참조](#cli-services-ec2-keypairs-references)

## 사전 조건
<a name="cli-services-ec2-keypairs-prereqs"></a>

`ec2` 명령을 실행하려면 다음을 수행해야 합니다.
+ AWS CLI를 설치하고 구성합니다. 자세한 내용은 [최신 버전의 AWS CLI 설치 또는 업데이트](getting-started-install.md) 및 [AWS CLI에 대한 인증 및 액세스 보안 인증](cli-chap-authentication.md) 섹션을 참조하세요.
+ Amazon EC2 액세스를 허용하도록 IAM 권한을 설정합니다. Amazon EC2의 IAM 권한에 대한 자세한 내용은 **Amazon EC2 사용 설명서의 [Amazon EC2에 대한 IAM 정책](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-policies-for-amazon-ec2.html)을 참조하세요.

## 키 페어 생성
<a name="creating-a-key-pair"></a>

키 페어를 생성하려면 `[aws ec2 create-key-pair](https://docs.aws.amazon.com/cli/latest/reference/ec2/create-key-pair.html)` 명령과 함께 `--query` 옵션 및 `--output text` 옵션을 사용하여 프라이빗 키를 직접 파일에 파이프합니다.

```
$ aws ec2 create-key-pair --key-name MyKeyPair --query 'KeyMaterial' --output text > MyKeyPair.pem
```

PowerShell의 경우 `> file` 리디렉션이 UTF-8 인코딩으로 기본 지정되는데, 일부 SSH 클라이언트에서는 이 인코딩을 사용할 수 없습니다. 따라서 `out-file` 명령으로 파이프하여 출력을 변환하고, 명시적으로 인코딩을 `ascii`로 설정해야 합니다.

```
PS C:\>aws ec2 create-key-pair --key-name MyKeyPair --query 'KeyMaterial' --output text | out-file -encoding ascii -filepath MyKeyPair.pem
```

결과로 나온 `MyKeyPair.pem` 파일은 다음과 같습니다.

```
-----BEGIN RSA PRIVATE KEY-----
EXAMPLEKEYKCAQEAy7WZhaDsrA1W3mRlQtvhwyORRX8gnxgDAfRt/gx42kWXsT4rXE/b5CpSgie/
vBoU7jLxx92pNHoFnByP+Dc21eyyz6CvjTmWA0JwfWiW5/akH7iO5dSrvC7dQkW2duV5QuUdE0QW
Z/aNxMniGQE6XAgfwlnXVBwrerrQo+ZWQeqiUwwMkuEbLeJFLhMCvYURpUMSC1oehm449ilx9X1F
G50TCFeOzfl8dqqCP6GzbPaIjiU19xX/azOR9V+tpUOzEL+wmXnZt3/nHPQ5xvD2OJH67km6SuPW
oPzev/D8V+x4+bHthfSjR9Y7DvQFjfBVwHXigBdtZcU2/wei8D/HYwIDAQABAoIBAGZ1kaEvnrqu
/uler7vgIn5m7lN5LKw4hJLAIW6tUT/fzvtcHK0SkbQCQXuriHmQ2MQyJX/0kn2NfjLV/ufGxbL1
mb5qwMGUnEpJaZD6QSSs3kICLwWUYUiGfc0uiSbmJoap/GTLU0W5Mfcv36PaBUNy5p53V6G7hXb2
bahyWyJNfjLe4M86yd2YK3V2CmK+X/BOsShnJ36+hjrXPPWmV3N9zEmCdJjA+K15DYmhm/tJWSD9
81oGk9TopEp7CkIfatEATyyZiVqoRq6k64iuM9JkA3OzdXzMQexXVJ1TLZVEH0E7bhlY9d8O1ozR
oQs/FiZNAx2iijCWyv0lpjE73+kCgYEA9mZtyhkHkFDpwrSM1APaL8oNAbbjwEy7Z5Mqfql+lIp1
YkriL0DbLXlvRAH+yHPRit2hHOjtUNZh4Axv+cpg09qbUI3+43eEy24B7G/Uh+GTfbjsXsOxQx/x
p9otyVwc7hsQ5TA5PZb+mvkJ5OBEKzet9XcKwONBYELGhnEPe7cCgYEA06Vgov6YHleHui9kHuws
ayav0elc5zkxjF9nfHFJRry21R1trw2Vdpn+9g481URrpzWVOEihvm+xTtmaZlSp//lkq75XDwnU
WA8gkn6O3QE3fq2yN98BURsAKdJfJ5RL1HvGQvTe10HLYYXpJnEkHv+Unl2ajLivWUt5pbBrKbUC
gYBjbO+OZk0sCcpZ29sbzjYjpIddErySIyRX5gV2uNQwAjLdp9PfN295yQ+BxMBXiIycWVQiw0bH
oMo7yykABY7Ozd5wQewBQ4AdSlWSX4nGDtsiFxWiI5sKuAAeOCbTosy1s8w8fxoJ5Tz1sdoxNeGs
Arq6Wv/G16zQuAE9zK9vvwKBgF+09VI/1wJBirsDGz9whVWfFPrTkJNvJZzYt69qezxlsjgFKshy
WBhd4xHZtmCqpBPlAymEjr/TOlbxyARmXMnIOWIAnNXMGB4KGSyl1mzSVAoQ+fqR+cJ3d0dyPl1j
jjb0Ed/NY8frlNDxAVHE8BSkdsx2f6ELEyBKJSRr9snRAoGAMrTwYneXzvTskF/S5Fyu0iOegLDa
NWUH38v/nDCgEpIXD5Hn3qAEcju1IjmbwlvtW+nY2jVhv7UGd8MjwUTNGItdb6nsYqM2asrnF3qS
VRkAKKKYeGjkpUfVTrW0YFjXkfcrR/V+QFL5OndHAKJXjW7a4ejJLncTzmZSpYzwApc=
-----END RSA PRIVATE KEY-----
```

프라이빗 키가 AWS에 저장되지 않고 이 키가 ***생성될 때만*** 검색할 수 있습니다. 나중에 복구할 수 없습니다. 대신, 프라이빗 키를 잃어버리면 새 키 페어를 생성해야 합니다.

Linux 컴퓨터에서 인스턴스에 연결하는 경우, 사용자만 프라이빗 키 파일을 읽을 수 있도록 다음 명령으로 해당 권한을 설정하는 것이 좋습니다.

```
$ chmod 400 MyKeyPair.pem
```

## 키 페어 표시
<a name="displaying-a-key-pair"></a>

키 페어에서 "지문"이 생성되고 이 지문을 사용하여 로컬 시스템에 있는 프라이빗 키가 AWS에 저장된 퍼블릭 키와 일치하는지 확인할 수 있습니다.

지문은 프라이빗 키의 DER 인코딩된 사본에서 가져온 SHA1 해시입니다. 이 값은 키 페어가 생성될 때 캡처되어 퍼블릭 키와 함께 AWS에 저장됩니다. Amazon EC2 콘솔에서 또는 AWS CLI 명령 `[aws ec2 describe-key-pairs](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-key-pairs.html)`를 실행하여 지문을 볼 수 있습니다.

다음 예제는 `MyKeyPair`의 지문을 표시합니다.

```
$ aws ec2 describe-key-pairs --key-name MyKeyPair
{
    "KeyPairs": [
        {
            "KeyName": "MyKeyPair",
            "KeyFingerprint": "1f:51:ae:28:bf:89:e9:d8:1f:25:5d:37:2d:7d:b8:ca:9f:f5:f1:6f"
        }
    ]
}
```

키 및 지문에 대한 자세한 내용은 **Amazon EC2 사용 설명서의 [Amazon EC2 키 페어](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html)를 참조하세요.

## 키 페어 삭제
<a name="deleting-a-key-pair"></a>

키 페어를 삭제하려면 *`MyKeyPair`*를 삭제할 페어의 이름으로 바꾸어 `[aws ec2 delete-key-pair](https://docs.aws.amazon.com/cli/latest/reference/ec2/delete-key-pair.html)` 명령을 실행합니다.

```
$ aws ec2 delete-key-pair --key-name MyKeyPair
```

## 참조
<a name="cli-services-ec2-keypairs-references"></a>

**AWS CLI 참조:** 
+ `[aws ec2](https://docs.aws.amazon.com/cli/latest/reference/ec2/index.html)`
+ `[aws ec2 create-key-pair](https://docs.aws.amazon.com/cli/latest/reference/ec2/create-key-pair.html)`
+ `[aws ec2 delete-key-pair](https://docs.aws.amazon.com/cli/latest/reference/ec2/delete-key-pair.html)`
+ `[aws ec2 describe-key-pairs](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-key-pairs.html)`

**기타 참조:**
+ [Amazon Elastic Compute Cloud 설명서](https://docs.aws.amazon.com/ec2/)
+ AWS SDK 및 AWS CLI 코드 예제를 보고 기여하려면 *GitHub*에서 [AWS 코드 예제 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/)를 참조하세요.

# AWS CLI에서 Amazon EC2 보안 그룹 생성, 구성 및 삭제
<a name="cli-services-ec2-sg"></a>

기본적으로 방화벽 역할을 하는 Amazon Elastic Compute Cloud(Amazon EC2) 인스턴스에 대한 보안 그룹과 함께, 들어오고 나가는 네트워크 트래픽을 결정하는 규칙을 생성할 수 있습니다.

AWS Command Line Interface(AWS CLI)를 사용하여 새 보안 그룹을 만들고, 기존 보안 그룹에 규칙을 추가하고, 보안 그룹을 삭제합니다.

**참고**  
추가 명령 예제는 [AWS CLI 참조 가이드](https://docs.aws.amazon.com/cli/latest/reference/index.html)를 참조하세요.

**Topics**
+ [사전 조건](#cli-services-ec2-sg-prereqs)
+ [보안 그룹 생성](#creating-a-security-group)
+ [보안 그룹에 규칙 추가](#configuring-a-security-group)
+ [보안 그룹 삭제](#deleting-a-security-group)
+ [참조](#cli-services-ec2-sg-references)

## 사전 조건
<a name="cli-services-ec2-sg-prereqs"></a>

`ec2` 명령을 실행하려면 다음을 수행해야 합니다.
+ AWS CLI를 설치하고 구성합니다. 자세한 내용은 [최신 버전의 AWS CLI 설치 또는 업데이트](getting-started-install.md) 및 [AWS CLI에 대한 인증 및 액세스 보안 인증](cli-chap-authentication.md) 섹션을 참조하세요.
+ Amazon EC2 액세스를 허용하도록 IAM 권한을 설정합니다. Amazon EC2의 IAM 권한에 대한 자세한 내용은 **Amazon EC2 사용 설명서의 [Amazon EC2에 대한 IAM 정책](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-policies-for-amazon-ec2.html)을 참조하세요.

## 보안 그룹 생성
<a name="creating-a-security-group"></a>

Virtual Private Cloud(VPC)와 관련된 보안 그룹을 생성할 수 있습니다.

다음 `[aws ec2 create-security-group](https://docs.aws.amazon.com/cli/latest/reference/ec2/create-security-group.html)` 예제에서는 지정된 VPC에 대한 보안 그룹을 생성하는 방법을 보여줍니다.

```
$ aws ec2 create-security-group --group-name my-sg --description "My security group" --vpc-id vpc-1a2b3c4d
{
    "GroupId": "sg-903004f8"
}
```

보안 그룹에 대한 초기 정보를 보려면 `[aws ec2 describe-security-groups](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-security-groups.html)` 명령을 실행합니다. EC2-VPC 보안 그룹은 이름이 아닌 `vpc-id`를 통해서만 참조할 수 있습니다.

```
$ aws ec2 describe-security-groups --group-ids sg-903004f8
{
    "SecurityGroups": [
        {
            "IpPermissionsEgress": [
                {
                    "IpProtocol": "-1",
                    "IpRanges": [
                        {
                            "CidrIp": "0.0.0.0/0"
                        }
                    ],
                    "UserIdGroupPairs": []
                }
            ],
            "Description": "My security group"
            "IpPermissions": [],
            "GroupName": "my-sg",
            "VpcId": "vpc-1a2b3c4d",
            "OwnerId": "123456789012",
            "GroupId": "sg-903004f8"
        }
    ]
}
```

## 보안 그룹에 규칙 추가
<a name="configuring-a-security-group"></a>

Amazon EC2 인스턴스를 실행할 때 이미지에 연결하는 방법에 맞는 수신 네트워크 트래픽을 허용하려면 보안 그룹의 규칙을 활성화해야 합니다.

예를 들어 Windows 인스턴스를 시작할 경우, RDP(Remote Desktop Protocol)를 지원하기 위해 일반적으로 TCP 포트 3389에서 인바운드 트래픽을 허용하는 규칙을 추가합니다. Linux 인스턴스를 시작할 경우, SSH 연결을 지원하기 위해 일반적으로 TCP 포트 22에서 인바운드 트래픽을 허용하는 규칙을 추가합니다.

`[aws ec2 authorize-security-group-ingress](https://docs.aws.amazon.com/cli/latest/reference/ec2/authorize-security-group-ingress.html)` 명령을 사용하여 보안 그룹에 규칙을 추가합니다. 이 명령의 필수 파라미터가 컴퓨터 또는 컴퓨터가 연결된 네트워크(주소 범위의 형식)의 퍼블릭 IP 주소([CIDR](https://wikipedia.org/wiki/Classless_Inter-Domain_Routing) 표기법 사용)입니다.

**참고**  
다음 서비스를 제공합니다. [https://checkip.global.api.aws/](https://checkip.global.api.aws/)으로 퍼블릭 IP 주소 확인을 활성화할 수 있습니다. IP 주소를 식별하는 데 도움이 되는 다른 서비스를 찾으려면 브라우저를 사용하여 "*내 IP 주소*"를 검색합니다. 동적 IP 주소를 사용하여(프라이빗 네트워크의 NAT 게이트웨이를 통해) 방화벽 뒤에서 연결하거나 ISP를 통해 연결하면 주소가 주기적으로 변경될 수 있습니다. 이 경우 클라이언트 컴퓨터에서 사용하는 IP 주소 범위를 알아야 합니다.

다음 예제에서는 사용자의 IP 주소를 사용하여 ID가 `sg-903004f8`인 EC2-VPC 보안 그룹에 RDP(TCP 포트 3389)에 대한 규칙을 추가하는 방법을 보여줍니다.

시작하려면 IP 주소를 찾습니다.

```
$ curl https://checkip.amazonaws.com
x.x.x.x
```

그런 다음 `[aws ec2 authorize-security-group-ingress](https://docs.aws.amazon.com/cli/latest/reference/ec2/authorize-security-group-ingress.html)` 명령을 실행하여 IP 주소를 보안 그룹에 추가할 수 있습니다.

```
$ aws ec2 authorize-security-group-ingress --group-id sg-903004f8 --protocol tcp --port 3389 --cidr x.x.x.x/x
```

다음 명령은 동일한 보안 그룹의 인스턴스에 SSH를 활성화하는 다른 규칙을 추가합니다.

```
$ aws ec2 authorize-security-group-ingress --group-id sg-903004f8 --protocol tcp --port 22 --cidr x.x.x.x/x
```

보안 그룹의 변경 사항을 보려면 `[aws ec2 describe-security-groups](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-security-groups.html)` 명령을 실행합니다.

```
$ aws ec2 describe-security-groups --group-ids sg-903004f8
{
    "SecurityGroups": [
        {
            "IpPermissionsEgress": [
                {
                    "IpProtocol": "-1",
                    "IpRanges": [
                        {
                            "CidrIp": "0.0.0.0/0"
                        }
                    ],
                    "UserIdGroupPairs": []
                }
            ],
            "Description": "My security group"
            "IpPermissions": [
                {
                    "ToPort": 22,
                    "IpProtocol": "tcp",
                    "IpRanges": [
                        {
                            "CidrIp": "x.x.x.x/x"
                        }
                    ]
                    "UserIdGroupPairs": [],
                    "FromPort": 22
                }
            ],
            "GroupName": "my-sg",
            "OwnerId": "123456789012",
            "GroupId": "sg-903004f8"
        }
    ]
}
```

## 보안 그룹 삭제
<a name="deleting-a-security-group"></a>

보안 그룹을 삭제하려면 `[aws ec2 delete-security-group](https://docs.aws.amazon.com/cli/latest/reference/ec2/delete-security-group.html)` 명령을 실행합니다.

**참고**  
환경에 현재 연결되어 있는 경우 보안 그룹을 삭제할 수 없습니다.

다음 명령 예제는 EC2-VPC 보안 그룹을 삭제합니다.

```
$ aws ec2 delete-security-group --group-id sg-903004f8
```

## 참조
<a name="cli-services-ec2-sg-references"></a>

**AWS CLI 참조:** 
+ `[aws ec2](https://docs.aws.amazon.com/cli/latest/reference/ec2/index.html)`
+ `[aws ec2 authorize-security-group-ingress](https://docs.aws.amazon.com/cli/latest/reference/ec2/authorize-security-group-ingress.html)`
+ `[aws ec2 create-security-group](https://docs.aws.amazon.com/cli/latest/reference/ec2/create-security-group.html)`
+ `[aws ec2 delete-security-group](https://docs.aws.amazon.com/cli/latest/reference/ec2/delete-security-group.html)`
+ `[aws ec2 describe-security-groups](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-security-groups.html)`

**기타 참조:**
+ [Amazon Elastic Compute Cloud 설명서](https://docs.aws.amazon.com/ec2/)
+ AWS SDK 및 AWS CLI 코드 예제를 보고 기여하려면 *GitHub*에서 [AWS 코드 예제 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/)를 참조하세요.

# AWS CLI에서 Amazon EC2 인스턴스 시작, 나열 및 삭제
<a name="cli-services-ec2-instances"></a>

AWS Command Line Interface(AWS CLI)를 사용하여 Amazon Elastic Compute Cloud(Amazon EC2) 인스턴스를 시작, 나열 및 삭제할 수 있습니다. 시작하는 인스턴스가 AWS 프리 티어에 해당되지 않는 경우 인스턴스를 시작한 후에 요금이 청구되고 유휴 상태를 포함해 인스턴스가 실행된 시간에 대해 과금됩니다.

**참고**  
추가 명령 예제는 [AWS CLI 참조 가이드](https://docs.aws.amazon.com/cli/latest/reference/index.html)를 참조하세요.

**Topics**
+ [사전 조건](#cli-services-ec2-instances-prereqs)
+ [인스턴스 시작](#launching-instances)
+ [인스턴스에 블록 디바이스 추가](#block-device-mapping)
+ [인스턴스에 태그 추가](#tagging-instances)
+ [인스턴스에 연결합니다](#connecting-to-instances)
+ [인스턴스 나열](#listing-instances)
+ [인스턴스 삭제](#terminating-instances)
+ [참조](#cli-services-ec2-instances-references)

## 사전 조건
<a name="cli-services-ec2-instances-prereqs"></a>

이 주제의 `ec2` 명령을 실행하려면 다음을 수행해야 합니다.
+ AWS CLI를 설치하고 구성합니다. 자세한 내용은 [최신 버전의 AWS CLI 설치 또는 업데이트](getting-started-install.md) 및 [AWS CLI에 대한 인증 및 액세스 보안 인증](cli-chap-authentication.md) 섹션을 참조하세요.
+ Amazon EC2 액세스를 허용하도록 IAM 권한을 설정합니다. Amazon EC2의 IAM 권한에 대한 자세한 내용은 **Amazon EC2 사용 설명서의 [Amazon EC2에 대한 IAM 정책](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-policies-for-amazon-ec2.html)을 참조하세요.
+ [키 페어](cli-services-ec2-keypairs.md) 및 [보안 그룹](cli-services-ec2-sg.md)을 생성합니다.
+ Amazon Machine Image(AMI)를 선택하고 AMI ID를 기록합니다. 자세한 내용은 [https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/finding-an-ami.html](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/finding-an-ami.html)Amazon EC2 사용 설명서의 *적합한 AMI 찾기*를 참조하세요.

## 인스턴스 시작
<a name="launching-instances"></a>

선택한 AMI를 사용하여 Amazon EC2 인스턴스를 시작하려면 `[aws ec2 run-instances](https://docs.aws.amazon.com/cli/latest/reference/ec2/run-instances.html)` 명령을 사용합니다. Virtual Private Cloud(VPC)에서 인스턴스를 시작할 수 있습니다.

처음에는 인스턴스가 `pending` 상태로 표시되지만 몇 분 후에 `running` 상태로 변경됩니다.

다음 예제는 지정한 VPC 서브넷에서 `t2.micro` 인스턴스를 시작하는 방법을 보여줍니다. *기울임꼴* 파라미터 값을 사용자의 값으로 바꾸세요.

```
$ aws ec2 run-instances --image-id ami-xxxxxxxx --count 1 --instance-type t2.micro --key-name MyKeyPair --security-group-ids sg-903004f8 --subnet-id subnet-6e7f829e
{
    "OwnerId": "123456789012",
    "ReservationId": "r-5875ca20",
    "Groups": [
        {
            "GroupName": "my-sg",
            "GroupId": "sg-903004f8"
        }
    ],
    "Instances": [
        {
            "Monitoring": {
                "State": "disabled"
            },
            "PublicDnsName": null,
            "Platform": "windows",
            "State": {
                "Code": 0,
                "Name": "pending"
            },
            "EbsOptimized": false,
            "LaunchTime": "2013-07-19T02:42:39.000Z",
            "PrivateIpAddress": "10.0.1.114",
            "ProductCodes": [],
            "VpcId": "vpc-1a2b3c4d",
            "InstanceId": "i-5203422c",
            "ImageId": "ami-173d747e",
            "PrivateDnsName": "ip-10-0-1-114.ec2.internal",
            "KeyName": "MyKeyPair",
            "SecurityGroups": [
                {
                    "GroupName": "my-sg",
                    "GroupId": "sg-903004f8"
                }
            ],
            "ClientToken": null,
            "SubnetId": "subnet-6e7f829e",
            "InstanceType": "t2.micro",
            "NetworkInterfaces": [
                {
                    "Status": "in-use",
                    "SourceDestCheck": true,
                    "VpcId": "vpc-1a2b3c4d",
                    "Description": "Primary network interface",
                    "NetworkInterfaceId": "eni-a7edb1c9",
                    "PrivateIpAddresses": [
                        {
                            "PrivateDnsName": "ip-10-0-1-114.ec2.internal",
                            "Primary": true,
                            "PrivateIpAddress": "10.0.1.114"
                        }
                    ],
                    "PrivateDnsName": "ip-10-0-1-114.ec2.internal",
                    "Attachment": {
                        "Status": "attached",
                        "DeviceIndex": 0,
                        "DeleteOnTermination": true,
                        "AttachmentId": "eni-attach-52193138",
                        "AttachTime": "2013-07-19T02:42:39.000Z"
                    },
                    "Groups": [
                        {
                            "GroupName": "my-sg",
                            "GroupId": "sg-903004f8"
                        }
                    ],
                    "SubnetId": "subnet-6e7f829e",
                    "OwnerId": "123456789012",
                    "PrivateIpAddress": "10.0.1.114"
                }              
            ],
            "SourceDestCheck": true,
            "Placement": {
                "Tenancy": "default",
                "GroupName": null,
                "AvailabilityZone": "us-west-2b"
            },
            "Hypervisor": "xen",
            "BlockDeviceMappings": [
                {
                    "DeviceName": "/dev/sda1",
                    "Ebs": {
                        "Status": "attached",
                        "DeleteOnTermination": true,
                        "VolumeId": "vol-877166c8",
                        "AttachTime": "2013-07-19T02:42:39.000Z"
                    }
                }              
            ],
            "Architecture": "x86_64",
            "StateReason": {
                "Message": "pending",
                "Code": "pending"
            },
            "RootDeviceName": "/dev/sda1",
            "VirtualizationType": "hvm",
            "RootDeviceType": "ebs",
            "Tags": [
                {
                    "Value": "MyInstance",
                    "Key": "Name"
                }
            ],
            "AmiLaunchIndex": 0
        }
    ]
}
```

## 인스턴스에 블록 디바이스 추가
<a name="block-device-mapping"></a>

실행된 각 인스턴스에는 연관된 루트 디바이스 볼륨이 있습니다. 블록 디바이스 매핑을 사용하면 실행될 때 인스턴스에 연결할 추가 Amazon Elastic Block Store(Amazon EBS) 볼륨 또는 인스턴스 스토어 볼륨을 지정할 수 있습니다.

인스턴스에 블록 디바이스를 추가하려면 `--block-device-mappings`를 사용할 때 `run-instances` 옵션을 지정합니다.

다음 예제 파라미터는 크기가 20GB인 표준 Amazon EBS 볼륨을 프로비저닝하고, 식별자 `/dev/sdf`를 사용하여 인스턴스에 이를 매핑합니다.

```
--block-device-mappings "[{\"DeviceName\":\"/dev/sdf\",\"Ebs\":{\"VolumeSize\":20,\"DeleteOnTermination\":false}}]"
```

다음 예제에서는 기존 스냅샷을 기반으로 `/dev/sdf`에 매핑된 Amazon EBS 볼륨을 추가합니다. 스냅샷은 볼륨에 로드되는 이미지를 나타냅니다. 스냅샷을 지정할 때 볼륨 크기를 지정할 필요가 없습니다. 이미지를 담을 만큼 충분히 큽니다. 그러나 크기를 지정하는 경우 스냅샷의 크기보다 크거나 같아야 합니다.

```
--block-device-mappings "[{\"DeviceName\":\"/dev/sdf\",\"Ebs\":{\"SnapshotId\":\"snap-a1b2c3d4\"}}]"
```

다음 예제에서는 인스턴스에 두 개의 볼륨을 추가합니다. 인스턴스에 사용 가능한 볼륨 수는 인스턴스 유형에 따라 다릅니다.

```
--block-device-mappings "[{\"DeviceName\":\"/dev/sdf\",\"VirtualName\":\"ephemeral0\"},{\"DeviceName\":\"/dev/sdg\",\"VirtualName\":\"ephemeral1\"}]"
```

다음 예제에서는 매핑(`/dev/sdj`)을 생성하지만 인스턴스에 볼륨을 프로비저닝하지 않습니다.

```
--block-device-mappings "[{\"DeviceName\":\"/dev/sdj\",\"NoDevice\":\"\"}]"
```

자세한 내용은 *Amazon EC2 사용 설명서*의 [블록 디바이스 매핑](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html)을 참조하세요.

## 인스턴스에 태그 추가
<a name="tagging-instances"></a>

태그는 AWS 리소스에 할당하는 레이블입니다. 이를 통해 다양한 용도로 사용할 수 있는 메타데이터를 리소스에 추가할 수 있습니다. 자세한 내용은 **Amazon EC2 사용 설명서의 [리소스에 태그 지정](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html)을 참조하세요.

다음 예제에서는 `[aws ec2 create-tags](https://docs.aws.amazon.com/cli/latest/reference/ec2/create-tags.html)` 명령을 사용하여 키 이름이 "`Name`"이고 값이 "`MyInstance`"인 태그를 지정된 인스턴스에 추가하는 방법을 보여줍니다.

```
$ aws ec2 create-tags --resources i-5203422c --tags Key=Name,Value=MyInstance
```

## 인스턴스에 연결합니다
<a name="connecting-to-instances"></a>

인스턴스가 실행될 때 실행 중인 인스턴스에 연결하여 바로 앞에 있는 컴퓨터를 사용하는 것처럼 인스턴스를 사용할 수 있습니다. 자세한 내용은 **Amazon EC2 사용 설명서의 [Amazon EC2 인스턴스에 연결](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connect-to-linux-instance.html)을 참조하세요.

## 인스턴스 나열
<a name="listing-instances"></a>

AWS CLI를 사용하여 인스턴스를 나열하고 정보를 확인할 수 있습니다. 모든 인스턴스를 나열하거나 관심이 있는 인스턴스에 따라 결과를 필터링할 수 있습니다.

다음 예제에서는 `[aws ec2 describe-instances](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html)` 명령을 사용하는 방법을 보여줍니다.

다음 명령은 모든 인스턴스를 나열합니다.

```
$ aws ec2 describe-instances
```

다음 명령은 목록을 `t2.micro` 인스턴스로만 필터링하고 각 매치에 대한 `InstanceId` 값만 출력합니다.

```
$ aws ec2 describe-instances --filters "Name=instance-type,Values=t2.micro" --query "Reservations[].Instances[].InstanceId"
[
    "i-05e998023d9c69f9a"
]
```

다음 명령은 `Name=MyInstance` 태그가 있는 인스턴스를 나열합니다.

```
$ aws ec2 describe-instances --filters "Name=tag:Name,Values=MyInstance"
```

다음 명령은 `ami-x0123456`, `ami-y0123456` 및 `ami-z0123456` AMI를 사용해 시작된 인스턴스를 나열합니다.

```
$ aws ec2 describe-instances --filters "Name=image-id,Values=ami-x0123456,ami-y0123456,ami-z0123456"
```

## 인스턴스 삭제
<a name="terminating-instances"></a>

더 이상 필요하지 않은 경우 AWS CLI를 사용하여 Amazon EC2 인스턴스를 종료(삭제)할 수 있습니다.

**중요**  
**인스턴스 종료는 영구적이며 취소할 수 없습니다.**  
종료한 인스턴스는 더 이상 연결할 수 없으며 복구할 수 없습니다. 연결된 Amazon EBS 볼륨도 종료 시 삭제하도록 구성한 경우 영구적으로 삭제되며 복구할 수 없습니다. 인스턴스 저장소 볼륨에 저장된 데이터는 모두 영구적으로 손실됩니다. 자세한 내용은 [인스턴스 종료 작동 방식](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/how-ec2-instance-termination-works.html)식을 참조하세요.  
인스턴스를 종료하기 전에 종료 후에도 보존해야 하는 모든 데이터를 영구 스토리지에 백업했는지 확인하세요.

인스턴스 상태가 `shutting-down` 또는 `terminated`로 변경되는 즉시 해당 인스턴스에 대한 반복적인 요금 부과가 중단됩니다. 나중에 인스턴스에 다시 연결하려면 `terminate-instances` 대신 [stop-instances](https://docs.aws.amazon.com/cli/v1/reference/ec2/stop-instances.html)를 사용합니다. 자세한 내용은 *Amazon EC2 사용 설명서*의 [인스턴스 종료](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html)를 참조하세요.

다음 예제에서는 `[aws ec2 terminate-instances](https://docs.aws.amazon.com/cli/latest/reference/ec2/terminate-instances.html)` 명령을 사용하여 인스턴스를 삭제하는 방법을 보여줍니다.

```
$ aws ec2 terminate-instances --instance-ids i-5203422c
{
    "TerminatingInstances": [
        {
            "InstanceId": "i-5203422c",
            "CurrentState": {
                "Code": 32,
                "Name": "shutting-down"
            },
            "PreviousState": {
                "Code": 16,
                "Name": "running"
            }
        }
    ]
}
```

## 참조
<a name="cli-services-ec2-instances-references"></a>

**AWS CLI 참조:** 
+ `[aws ec2](https://docs.aws.amazon.com/cli/latest/reference/ec2/index.html)`
+ `[aws ec2 create-tags](https://docs.aws.amazon.com/cli/latest/reference/ec2/create-tags.html)`
+ `[aws ec2 describe-instances](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html)`
+ `[aws ec2 run-instances](https://docs.aws.amazon.com/cli/latest/reference/ec2/run-instances.html)`
+ `[aws ec2 terminate-instances](https://docs.aws.amazon.com/cli/latest/reference/ec2/terminate-instances.html)`

**기타 참조:**
+ [Amazon Elastic Compute Cloud 설명서](https://docs.aws.amazon.com/ec2/)
+ AWS SDK 및 AWS CLI 코드 예제를 보고 기여하려면 *GitHub*에서 [AWS 코드 예제 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/)를 참조하세요.

# AWS CLI에서 bash 스크립트로 Amazon EC2 인스턴스 유형 변경
<a name="cli-services-ec2-instance-type-script"></a>

Amazon EC2에 대한 이 bash 스크립팅 예제에서는 AWS Command Line Interface(AWS CLI)를 사용하여 Amazon EC2 인스턴스의 인스턴스 유형을 변경합니다. 인스턴스가 실행 중인 경우 인스턴스를 중지하고, 인스턴스 유형을 변경한 다음, 요청된 경우 인스턴스를 다시 시작합니다. 셸 스크립트는 명령줄 인터페이스에서 실행되도록 설계된 프로그램입니다.

**참고**  
추가 명령 예제는 [AWS CLI 참조 가이드](https://docs.aws.amazon.com/cli/latest/reference/index.html)를 참조하세요.

**Topics**
+ [시작하기 전에](#cli-services-ec2-instance-type-script-prereqs)
+ [이 예제 정보](#cli-services-ec2-instance-type-script-about)
+ [파라미터](#cli-services-ec2-instance-type-script-params)
+ [파일](#cli-services-ec2-instance-type-script-files.title)
+ [참조](#cli-services-ec2-instance-type-script-references)

## 시작하기 전에
<a name="cli-services-ec2-instance-type-script-prereqs"></a>

아래 예제 중 하나를 실행하려면 먼저 다음 작업을 완료해야 합니다.
+ AWS CLI를 설치하고 구성합니다. 자세한 내용은 [최신 버전의 AWS CLI 설치 또는 업데이트](getting-started-install.md) 및 [AWS CLI에 대한 인증 및 액세스 보안 인증](cli-chap-authentication.md) 섹션을 참조하세요.
+ 사용하는 프로파일에는 예제에서 수행하는 AWS 작업을 허용하는 권한이 있어야 합니다.
+ 중지 및 수정 권한이 있는 계정에서 실행 중인 Amazon EC2 인스턴스입니다. 테스트 스크립트를 실행하면 테스트 스크립트가 인스턴스를 시작하고 유형을 변경하여 인스턴스를 테스트한 다음 인스턴스를 종료합니다.
+ AWS 모범 사례로서 이 코드에 최소 권한을 부여하거나 태스크를 수행하는 데 필요한 권한만 부여하세요. 자세한 내용은 *AWS Identity and Access Management(IAM) 사용 설명서*에서 [최소 권한 부여](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege)를 참조하세요.
+ 이 코드는 일부 AWS 리전에서 테스트되지 않았습니다. 일부 AWS 서비스는 특정 리전에서만 사용할 수 있습니다. 자세한 내용은 *AWS 일반 참조 안내서*에서 [서비스 엔드포인트 및 할당량](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html)을 참조하세요.
+ 이 코드를 실행하면 AWS 계정에 요금이 발생할 수 있습니다. 이 스크립트에 의해 생성된 모든 리소스를 사용한 후 제거하는 것은 사용자의 책임입니다.

## 이 예제 정보
<a name="cli-services-ec2-instance-type-script-about"></a>

이 예제는 다른 스크립트나 명령줄에서 `change_ec2_instance_type.sh`할 수 있는 셸 스크립트 파일 `source`의 함수로 작성됩니다. 각 스크립트 파일에는 각 함수를 설명하는 주석이 들어 있습니다. 함수가 메모리에 있으면 명령줄에서 함수를 호출할 수 있습니다. 예를 들어, 다음 명령은 지정된 인스턴스의 유형을 `t2.nano`로 변경합니다.

```
$ source ./change_ec2_instance_type.sh
$ ./change_ec2_instance_type -i *instance-id* -t new-type
```

전체 예제 및 다운로드 가능한 스크립트 파일은 *GitHub*에서 *AWS 코드 예제 리포지토리*의 [Amazon EC2 인스턴스 유형 변경](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2/change-ec2-instance-type)을 참조하세요.

## 파라미터
<a name="cli-services-ec2-instance-type-script-params"></a>

**-i** - *(문자열)* 수정할 인스턴스 ID를 지정합니다.

**-t** - *(문자열)* 전환할 Amazon EC2 인스턴스 유형을 지정합니다.

**-r** - *(스위치)* 기본적으로 설정되지 않습니다. `-r`이 설정된 경우 유형 스위치 뒤에 인스턴스를 다시 시작합니다.

**-f** - *(스위치)* 기본적으로 스크립트는 스위치를 만들기 전에 인스턴스를 종료할지 확인하는 메시지를 사용자에게 표시합니다. `-f`가 설정된 경우, 함수는 유형 스위치를 만들기 위해 인스턴스를 종료하기 전에 사용자에게 메시지를 표시하지 않습니다

**-v** - *(스위치)* 기본적으로 스크립트는 자동으로 작동하며 오류가 발생한 경우에만 출력을 표시합니다. `-v`가 설정된 경우 함수는 작업 전체 상태를 표시합니다.

## 파일
<a name="cli-services-ec2-instance-type-script-files.title"></a>

**`change_ec2_instance_type.sh`**  
기본 스크립트 파일에는 다음 작업을 수행하는 `change_ec2_instance_type()` 함수가 포함되어 있습니다.  
+ 지정된 Amazon EC2 인스턴스가 있는지 확인합니다.
+ `-f`를 선택하지 않으면 인스턴스를 중지하기 전에 사용자에게 경고합니다.
+ 인스턴스 유형을 변경합니다.
+ `-r`을 설정하면 인스턴스를 다시 시작하고 인스턴스가 실행 중인지 확인합니다.
*GitHub*에서 `[change\$1ec2\$1instance\$1type.sh](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/aws-cli/bash-linux/ec2/change-ec2-instance-type/change_ec2_instance_type.sh)`에 대한 코드를 확인하세요.

**`test_change_ec2_instance_type.sh`**  
파일 `test_change_ec2_instance_type.sh` 스크립트는 `change_ec2_instance_type` 함수에 대한 다양한 코드 경로를 테스트합니다. 테스트 스크립트의 모든 단계가 올바르게 작동하는 경우 테스트 스크립트는 생성한 모든 리소스를 제거합니다.  
다음 파라미터와 함께 테스트 스크립트를 실행할 수 있습니다.  
+ **-v** - *(스위치)* 각 테스트는 실행 시 통과/실패 상태를 표시합니다. 기본적으로 테스트는 자동으로 실행되며 출력에는 최종 전체 통과/실패 상태만 포함됩니다.
+ **-i** - *(스위치)* 각 테스트 후에 스크립트가 일시 중지되어 각 단계의 중간 결과를 찾아볼 수 있습니다. Amazon EC2 콘솔을 사용하여 인스턴스의 현재 상태를 검사할 수 있습니다. 프롬프트에서 *Enter* 키를 누르면 스크립트가 다음 단계로 진행됩니다.
*GitHub*에서 `[test\$1change\$1ec2\$1instance\$1type.sh](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/aws-cli/bash-linux/ec2/change-ec2-instance-type/test_change_ec2_instance_type.sh)`에 대한 코드를 확인하세요.

**`awsdocs_general.sh`**  
스크립트 파일 `awsdocs_general.sh`에는 AWS CLI에 대한 고급 예제에서 사용되는 범용 함수가 들어 있습니다.  
*GitHub*에서 `[awsdocs\$1general.sh](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/aws-cli/bash-linux/ec2/change-ec2-instance-type/awsdocs_general.sh)`에 대한 코드를 확인하세요.

## 참조
<a name="cli-services-ec2-instance-type-script-references"></a>

**AWS CLI 참조:** 
+ `[aws ec2](https://docs.aws.amazon.com/cli/v1/reference/ec2/index.html)`
+ `[aws ec2 describe-instances](https://docs.aws.amazon.com/cli/v1/reference/ec2/describe-instances.html)`
+ `[aws ec2 modify-instance-attribute](https://docs.aws.amazon.com/cli/v1/reference/ec2/modify-instance-attribute.html)`
+ `[aws ec2 start-instances](https://docs.aws.amazon.com/cli/v1/reference/ec2/start-instances.html)`
+ `[aws ec2 stop-instances](https://docs.aws.amazon.com/cli/v1/reference/ec2/stop-instances.html)`
+ `[aws ec2 wait instance-running](https://docs.aws.amazon.com/cli/v1/reference/ec2/wait/instance-running.html)`
+ `[aws ec2 wait instance-stopped](https://docs.aws.amazon.com/cli/v1/reference/ec2/wait/instance-stopped.html)`

**기타 참조:**
+ [Amazon Elastic Compute Cloud 설명서](https://docs.aws.amazon.com/ec2/)
+ AWS SDK 및 AWS CLI 코드 예제를 보고 기여하려면 *GitHub*에서 [AWS 코드 예제 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/)를 참조하세요.

# AWS CLI에서 Amazon Glacier 사용
<a name="cli-services-glacier"></a>


| Amazon Glacier 소개 | 
| --- | 
|    | 

이 주제에서는 Amazon Glacier에 대한 일반적인 태스크를 수행하는 AWS CLI 명령의 예제를 보여줍니다. 이 예제는 AWS CLI를 사용하여 대용량 파일을 분할하고 명령줄에서 업로드하여 Amazon Glacier로 업로드 방법을 보여줍니다.

AWS Command Line Interface(AWS CLI)를 사용하여 Amazon Glacier의 기능에 액세스할 수 있습니다. Amazon Glacier에 대한 AWS CLI 명령을 나열하려면 다음 명령을 사용합니다.

```
aws glacier help
```

**참고**  
명령 참조 및 추가 예제는 *AWS CLI 명령 참조*의 `[aws glacier](https://docs.aws.amazon.com/cli/latest/reference/glacier/index.html)` 섹션을 참조하세요.

**Topics**
+ [사전 조건](#cli-services-glacier-prereqs)
+ [Amazon Glacier 볼트 생성](#cli-services-glacier-vault)
+ [파일 업로드 준비](#cli-services-glacier-prep)
+ [멀티파트 업로드 및 파일 업로드 시작](#cli-services-glacier-initiate)
+ [업로드 완료](#cli-services-glacier-complete)
+ [리소스](#cli-services-glacier-resources)

## 사전 조건
<a name="cli-services-glacier-prereqs"></a>

`glacier` 명령을 실행하려면 다음을 수행해야 합니다.
+ AWS CLI를 설치하고 구성합니다. 자세한 내용은 [최신 버전의 AWS CLI 설치 또는 업데이트](getting-started-install.md) 및 [AWS CLI에 대한 인증 및 액세스 보안 인증](cli-chap-authentication.md) 섹션을 참조하세요.
+ 이 자습서에서는 Linux 및 macOS를 비롯한 UNIX 계열 운영 체제에 일반적으로 사전 설치된 몇 가지 명령줄 도구를 사용합니다. Windows 사용자는 [Cygwin](https://www.cygwin.com/)을 설치하고 Cygwin 터미널에서 명령을 실행하여 동일한 도구를 사용할 수 있습니다. 동일한 기능을 수행하는 Windows 기본 명령 및 유틸리티가 표시되어 있습니다(사용 가능한 경우).

## Amazon Glacier 볼트 생성
<a name="cli-services-glacier-vault"></a>

`[create-vault](https://docs.aws.amazon.com/cli/latest/reference/glacier/create-vault.html)` 명령을 사용하여 볼트를 생성합니다.

```
$ aws glacier create-vault --account-id - --vault-name myvault
{
    "location": "/123456789012/vaults/myvault"
}
```

**참고**  
모든 Amazon Glacier 명령에는 계정 ID 파라미터가 필요합니다. 현재 계정을 사용하려면 하이픈 문자(`--account-id -`)를 사용합니다.

## 파일 업로드 준비
<a name="cli-services-glacier-prep"></a>

테스트 업로드를 위한 파일을 생성합니다. 다음 명령은 3MiB의 임의 데이터를 포함하는 *largefile*이라는 파일을 생성합니다.

**Linux 또는 macOS**:

```
$ dd if=/dev/urandom of=largefile bs=3145728 count=1
1+0 records in
1+0 records out
3145728 bytes (3.1 MB) copied, 0.205813 s, 15.3 MB/s
```

`dd`는 입력 파일에서 출력 파일로 많은 바이트를 복사하는 유틸리티입니다. 앞의 예제에서는 시스템 디바이스 파일 `/dev/urandom`을 임의 데이터 소스로 사용합니다. `fsutil`은 Windows에서 유사한 함수를 수행합니다.

**Windows**

```
C:\> fsutil file createnew largefile 3145728
File C:\temp\largefile is created
```

그런 다음 파일 분할기를 사용하여 파일을 1MB(1,048,576바이트)의 청크로 분할합니다.

```
$ split -b 1048576 --verbose largefile chunk
creating file `chunkaa'
creating file `chunkab'
creating file `chunkac'
```

## 멀티파트 업로드 및 파일 업로드 시작
<a name="cli-services-glacier-initiate"></a>

`[initiate-multipart-upload](https://docs.aws.amazon.com/cli/latest/reference/glacier/initiate-multipart-upload.html)` 명령을 사용하여 Amazon Glacier에서 멀티파트 업로드를 생성합니다.

```
$ aws glacier initiate-multipart-upload --account-id - --archive-description "multipart upload test" --part-size 1048576 --vault-name myvault
{
    "uploadId": "19gaRezEXAMPLES6Ry5YYdqthHOC_kGRCT03L9yetr220UmPtBYKk-OssZtLqyFu7sY1_lR7vgFuJV6NtcV5zpsJ",
    "location": "/123456789012/vaults/myvault/multipart-uploads/19gaRezEXAMPLES6Ry5YYdqthHOC_kGRCT03L9yetr220UmPtBYKk-OssZtLqyFu7sY1_lR7vgFuJV6NtcV5zpsJ"
}
```

Amazon Glacier에서 멀티파트 업로드를 구성하려면 각 파트의 크기(바이트, 이 예제에서는 1MiB), 볼트 이름 및 계정 ID가 필요합니다. 작업이 완료되면 AWS CLI에서 업로드 ID를 출력합니다. 나중에 사용하기 위해 업로드 ID를 셸 변수에 저장합니다.

**Linux 또는 macOS**

```
$ UPLOADID="19gaRezEXAMPLES6Ry5YYdqthHOC_kGRCT03L9yetr220UmPtBYKk-OssZtLqyFu7sY1_lR7vgFuJV6NtcV5zpsJ"
```

**Windows**

```
C:\> set UPLOADID="19gaRezEXAMPLES6Ry5YYdqthHOC_kGRCT03L9yetr220UmPtBYKk-OssZtLqyFu7sY1_lR7vgFuJV6NtcV5zpsJ"
```

그런 다음 `[upload-multipart-part](https://docs.aws.amazon.com/cli/latest/reference/glacier/upload-multipart-part.html)` 명령을 사용하여 세 개의 파트를 각각 업로드합니다.

```
$ aws glacier upload-multipart-part --upload-id $UPLOADID --body chunkaa --range 'bytes 0-1048575/*' --account-id - --vault-name myvault
{
    "checksum": "e1f2a7cd6e047fa606fe2f0280350f69b9f8cfa602097a9a026360a7edc1f553"
}
$ aws glacier upload-multipart-part --upload-id $UPLOADID --body chunkab --range 'bytes 1048576-2097151/*' --account-id - --vault-name myvault
{
    "checksum": "e1f2a7cd6e047fa606fe2f0280350f69b9f8cfa602097a9a026360a7edc1f553"
}
$ aws glacier upload-multipart-part --upload-id $UPLOADID --body chunkac --range 'bytes 2097152-3145727/*' --account-id - --vault-name myvault
{
    "checksum": "e1f2a7cd6e047fa606fe2f0280350f69b9f8cfa602097a9a026360a7edc1f553"
}
```

**참고**  
앞의 예에서는 Linux에서 달러 기호(`$`)를 사용하여 `UPLOADID` 셸 변수의 내용을 참조합니다. Windows 명령줄에서는 변수 이름의 양쪽에 퍼센트 기호(%)를 사용합니다(예: `%UPLOADID%`).

Amazon Glacier에서 올바른 순서로 다시 수집할 수 있도록 각 파트를 업로드할 때 각 파트의 바이트 범위를 지정해야 합니다. 각 조각은 1,048,576바이트입니다. 따라서 첫 번째 조각은 0-1048575바이트, 두 번째 조각은 1048576-2097151바이트, 세 번째 조각은 2097152-3145727바이트를 차지합니다.

## 업로드 완료
<a name="cli-services-glacier-complete"></a>

Amazon Glacier에서 업로드된 모든 조각이 AWS에 도달했는지 확인하려면 원본 파일의 트리 해시가 필요합니다.

트리 해시를 계산하려면 파일을 1MiB 파트로 분할하고 각 조각의 이진 SHA-256 해시를 계산합니다. 그런 다음 해시 목록을 쌍으로 분할하고, 2개의 이진 해시를 각 쌍으로 결합하며, 결과의 해시를 가져옵니다. 하나의 해시만 남을 때까지 이 프로세스를 반복합니다. 임의 레벨에서 홀수 해시가 있을 경우 수정하지 않고 다음 레벨로 승격시킵니다.

명령줄 유틸리티를 사용할 때 트리 해시를 올바로 계산하는 핵심은 각 해시를 이진 형식으로 저장하고 마지막 단계에서만 16진수로 변환하는 것입니다. 트리의 16진수 버전 해시를 결합하거나 해시할 경우 잘못된 결과가 발생할 수 있습니다.

**참고**  
Windows 사용자는 `type` 대신 `cat` 명령을 사용할 수 있습니다. OpenSSL은 [OpenSSL.org](https://www.openssl.org/source/)에서 Windows용으로 제공됩니다.

**트리 해시를 계산하려면**

1. 아직 분할하지 않은 경우, 원본 파일을 1MiB로 분할합니다.

   ```
   $ split --bytes=1048576 --verbose largefile chunk
   creating file `chunkaa'
   creating file `chunkab'
   creating file `chunkac'
   ```

1. 각 청크의 이진 SHA-256 해시를 계산 및 저장합니다.

   ```
   $ openssl dgst -sha256 -binary chunkaa > hash1
   $ openssl dgst -sha256 -binary chunkab > hash2
   $ openssl dgst -sha256 -binary chunkac > hash3
   ```

1. 처음 2개 해시를 결합하고 결과의 이진 해시를 가져옵니다.

   ```
   $ cat hash1 hash2 > hash12
   $ openssl dgst -sha256 -binary hash12 > hash12hash
   ```

1. 청크 `aa` 및 `ab`의 상위 해시를 청크 `ac`의 해시와 결합하고 결과를 해시합니다. 이때는 16진수가 출력됩니다. 결과를 셸 변수에 저장합니다.

   ```
   $ cat hash12hash hash3 > hash123
   $ openssl dgst -sha256 hash123
   SHA256(hash123)= 9628195fcdbcbbe76cdde932d4646fa7de5f219fb39823836d81f0cc0e18aa67
   $ TREEHASH=9628195fcdbcbbe76cdde932d4646fa7de5f219fb39823836d81f0cc0e18aa67
   ```

마지막으로 `[complete-multipart-upload](https://docs.aws.amazon.com/cli/latest/reference/glacier/complete-multipart-upload.html)` 명령을 사용하여 업로드를 완료합니다. 이 명령에서는 원본 파일의 크기(바이트), 최종 트리 해시 값(16진수) 및 계정 ID와 볼트 이름을 사용합니다.

```
$ aws glacier complete-multipart-upload --checksum $TREEHASH --archive-size 3145728 --upload-id $UPLOADID --account-id - --vault-name myvault
{
    "archiveId": "d3AbWhE0YE1m6f_fI1jPG82F8xzbMEEZmrAlLGAAONJAzo5QdP-N83MKqd96Unspoa5H5lItWX-sK8-QS0ZhwsyGiu9-R-kwWUyS1dSBlmgPPWkEbeFfqDSav053rU7FvVLHfRc6hg",
    "checksum": "9628195fcdbcbbe76cdde932d4646fa7de5f219fb39823836d81f0cc0e18aa67",
    "location": "/123456789012/vaults/myvault/archives/d3AbWhE0YE1m6f_fI1jPG82F8xzbMEEZmrAlLGAAONJAzo5QdP-N83MKqd96Unspoa5H5lItWX-sK8-QS0ZhwsyGiu9-R-kwWUyS1dSBlmgPPWkEbeFfqDSav053rU7FvVLHfRc6hg"
}
```

`[describe-vault](https://docs.aws.amazon.com/cli/latest/reference/glacier/describe-vault.html)` 명령을 사용하여 볼트 상태를 확인할 수도 있습니다.

```
$ aws glacier describe-vault --account-id - --vault-name myvault
{
    "SizeInBytes": 3178496,
    "VaultARN": "arn:aws:glacier:us-west-2:123456789012:vaults/myvault",
    "LastInventoryDate": "2018-12-07T00:26:19.028Z",
    "NumberOfArchives": 1,
    "CreationDate": "2018-12-06T21:23:45.708Z",
    "VaultName": "myvault"
}
```

**참고**  
볼트 상태는 매일 한 번 정도 업데이트됩니다. 자세한 내용은 [볼트 작업](https://docs.aws.amazon.com/amazonglacier/latest/dev/working-with-vaults.html)을 참조하세요.

이제 생성한 청크 및 해시 파일을 안전하게 제거할 수 있습니다.

```
$ rm chunk* hash*
```

멀티파트 업로드에 대한 자세한 내용은 *Amazon Glacier 개발자 안내서*에서 [파트로 대용량 아카이브 업로드](https://docs.aws.amazon.com/amazonglacier/latest/dev/uploading-archive-mpu.html) 및 [체크섬 컴퓨팅](https://docs.aws.amazon.com/amazonglacier/latest/dev/checksum-calculations.html)을 참조하세요.

## 리소스
<a name="cli-services-glacier-resources"></a>

**AWS CLI 참조:** 
+ `[aws glacier](https://docs.aws.amazon.com/cli/latest/reference/glacier/index.html)`
+ `[aws glacier complete-multipart-upload](https://docs.aws.amazon.com/cli/latest/reference/glacier/complete-multipart-upload.html)`
+ `[aws glacier create-vault](https://docs.aws.amazon.com/cli/latest/reference/glacier/create-vault.html)`
+ `[aws glacier describe-vault](https://docs.aws.amazon.com/cli/latest/reference/glacier/describe-vault.html)`
+ `[aws glacier initiate-multipart-upload](https://docs.aws.amazon.com/cli/latest/reference/glacier/initiate-multipart-upload.html)`

**서비스 참조:**
+ [Amazon Glacier 개발자 안내서](https://docs.aws.amazon.com/amazonglacier/latest/dev/)
+ *Amazon Glacier 개발자 안내서*의 [대용량 아카이브를 여러 부분으로 나누어 업로드](https://docs.aws.amazon.com/amazonglacier/latest/dev/uploading-archive-mpu.html)
+ *Amazon Glacier 개발자 안내서*의 [체크섬 계산](https://docs.aws.amazon.com/amazonglacier/latest/dev/checksum-calculations.html)
+ *Amazon Glacier 개발자 안내서*의 [볼트 작업](https://docs.aws.amazon.com/amazonglacier/latest/dev/working-with-vaults.html)

# AWS CLI에서 IAM 사용
<a name="cli-services-iam"></a>


| AWS Identity and Access Management 소개 | 
| --- | 
|    | 

AWS Command Line Interface(AWS CLI)를 사용하여 AWS Identity and Access Management(IAM) 기능에 액세스할 수 있습니다. IAM에 대한 AWS CLI 명령을 나열하려면 다음 명령을 사용합니다.

```
aws iam help
```

이 주제에서는 IAM에 대한 일반적인 태스크를 수행하는 AWS CLI 명령의 예제를 보여줍니다.

명령을 실행하기 전에 기본 자격 증명을 설정합니다. 자세한 내용은 [AWS CLI 설정 구성](cli-chap-configure.md) 단원을 참조하세요.

IAM 서비스에 대한 자세한 내용은 [AWS Identity and Access Management 사용 설명서](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html)를 참조하세요.

**Topics**
+ [IAM 사용자 및 그룹 생성](#cli-services-iam-new-user-group)
+ [사용자에게 IAM 관리형 정책 연결](#cli-services-iam-policy)
+ [IAM 사용자의 초기 암호 설정](#cli-services-iam-set-pw)
+ [IAM 사용자의 액세스 키 생성](#cli-services-iam-create-creds)

## IAM 사용자 및 그룹 생성
<a name="cli-services-iam-new-user-group"></a>

**그룹을 생성하고 이 그룹에 새 사용자를 추가하려면**

1. [https://docs.aws.amazon.com/cli/latest/reference/iam/create-group.html](https://docs.aws.amazon.com/cli/latest/reference/iam/create-group.html) 명령을 사용하여 그룹을 생성합니다.

   ```
   $ aws iam create-group --group-name MyIamGroup
   {
       "Group": {
           "GroupName": "MyIamGroup",
           "CreateDate": "2018-12-14T03:03:52.834Z",
           "GroupId": "AGPAJNUJ2W4IJVEXAMPLE",
           "Arn": "arn:aws:iam::123456789012:group/MyIamGroup",
           "Path": "/"
       }
   }
   ```

1. [https://docs.aws.amazon.com/cli/latest/reference/iam/create-user.html](https://docs.aws.amazon.com/cli/latest/reference/iam/create-user.html) 명령을 사용하여 사용자를 생성합니다.

   ```
   $ aws iam create-user --user-name MyUser
   {
       "User": {
           "UserName": "MyUser",
           "Path": "/",
           "CreateDate": "2018-12-14T03:13:02.581Z",
           "UserId": "AIDAJY2PE5XUZ4EXAMPLE",
           "Arn": "arn:aws:iam::123456789012:user/MyUser"
       }
   }
   ```

1. [https://docs.aws.amazon.com/cli/latest/reference/iam/add-user-to-group.html](https://docs.aws.amazon.com/cli/latest/reference/iam/add-user-to-group.html) 명령을 사용하여 사용자를 그룹에 추가합니다.

   ```
   $ aws iam add-user-to-group --user-name MyUser --group-name MyIamGroup
   ```

1. `MyIamGroup` 그룹에 `MyUser`가 포함되어 있는지 확인하려면 [https://docs.aws.amazon.com/cli/latest/reference/iam/get-group.html](https://docs.aws.amazon.com/cli/latest/reference/iam/get-group.html) 명령을 사용합니다.

   ```
   $ aws iam get-group --group-name MyIamGroup
   {
       "Group": {
           "GroupName": "MyIamGroup",
           "CreateDate": "2018-12-14T03:03:52Z",
           "GroupId": "AGPAJNUJ2W4IJVEXAMPLE",
           "Arn": "arn:aws:iam::123456789012:group/MyIamGroup",
           "Path": "/"
       },
       "Users": [
           {
               "UserName": "MyUser",
               "Path": "/",
               "CreateDate": "2018-12-14T03:13:02Z",
               "UserId": "AIDAJY2PE5XUZ4EXAMPLE",
               "Arn": "arn:aws:iam::123456789012:user/MyUser"
           }
       ],
       "IsTruncated": "false"
   }
   ```

## 사용자에게 IAM 관리형 정책 연결
<a name="cli-services-iam-policy"></a>

이 예제의 정책은 사용자에게 "파워 유저 액세스"를 제공합니다.

**사용자에게 IAM 관리형 정책을 연결하려면**

1. 연결할 정책의 Amazon 리소스 이름(ARN)을 확인합니다. 다음 명령은 `list-policies`를 사용하여 이름이 `PowerUserAccess`인 정책의 ARN을 찾습니다. 그런 다음 해당 ARN을 환경 변수에 저장합니다.

   ```
   $ export POLICYARN=$(aws iam list-policies --query 'Policies[?PolicyName==`PowerUserAccess`].{ARN:Arn}' --output text)       ~
   $ echo $POLICYARN
   arn:aws:iam::aws:policy/PowerUserAccess
   ```

1. 정책을 연결하려면 [https://docs.aws.amazon.com/cli/latest/reference/iam/attach-user-policy.html](https://docs.aws.amazon.com/cli/latest/reference/iam/attach-user-policy.html) 명령을 사용하고 정책 ARN을 보유하는 환경 변수를 참조합니다.

   ```
   $ aws iam attach-user-policy --user-name MyUser --policy-arn $POLICYARN
   ```

1. [https://docs.aws.amazon.com/cli/latest/reference/iam/list-attached-user-policies.html](https://docs.aws.amazon.com/cli/latest/reference/iam/list-attached-user-policies.html) 명령을 실행하여 정책이 사용자에게 연결되었는지 확인합니다.

   ```
   $ aws iam list-attached-user-policies --user-name MyUser
   {
       "AttachedPolicies": [
           {
               "PolicyName": "PowerUserAccess",
               "PolicyArn": "arn:aws:iam::aws:policy/PowerUserAccess"
           }
       ]
   }
   ```

자세한 내용은 [액세스 관리 리소스](https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-additional-resources.html)를 참조하세요. 이 주제에서는 권한 및 정책 개요에 대한 링크와 Amazon S3, Amazon EC2 및 기타 서비스에 액세스하기 위한 정책 예에 대한 링크를 제공합니다.

## IAM 사용자의 초기 암호 설정
<a name="cli-services-iam-set-pw"></a>

다음 명령은 `[create-login-profile](https://docs.aws.amazon.com/cli/latest/reference/iam/create-login-profile.html)`을 사용하여 지정된 사용자의 초기 암호를 설정합니다. 처음으로 로그인한 사용자는 본인만 아는 암호로 변경해야 합니다.

```
$ aws iam create-login-profile --user-name MyUser --password My!User1Login8P@ssword --password-reset-required
{
    "LoginProfile": {
        "UserName": "MyUser",
        "CreateDate": "2018-12-14T17:27:18Z",
        "PasswordResetRequired": true
    }
}
```

`update-login-profile` 명령을 사용하여 사용자의 암호를 *변경*합니다.

```
$ aws iam update-login-profile --user-name MyUser --password My!User1ADifferentP@ssword
```

## IAM 사용자의 액세스 키 생성
<a name="cli-services-iam-create-creds"></a>

[https://docs.aws.amazon.com/cli/latest/reference/iam/create-access-key.html](https://docs.aws.amazon.com/cli/latest/reference/iam/create-access-key.html) 명령을 사용하여 사용자를 위한 액세스 키를 생성할 수 있습니다. 액세스 키는 액세스 키 ID와 비밀 키로 구성된 보안 자격 증명 세트입니다.

사용자는 한 번에 두 개의 액세스 키만 생성할 수 있습니다. 세 번째 세트를 생성하려 할 경우 이 명령은 `LimitExceeded` 오류를 반환합니다.

```
$ aws iam create-access-key --user-name MyUser
{
    "AccessKey": {
        "UserName": "MyUser",
        "AccessKeyId": "AKIAIOSFODNN7EXAMPLE",
        "Status": "Active",
        "SecretAccessKey": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
        "CreateDate": "2018-12-14T17:34:16Z"
    }
}
```

[https://docs.aws.amazon.com/cli/latest/reference/iam/delete-access-key.html](https://docs.aws.amazon.com/cli/latest/reference/iam/delete-access-key.html) 명령을 사용하여 사용자를 위한 액세스 키를 삭제합니다. 액세스 키 ID를 사용하여 삭제할 액세스 키를 지정합니다.

```
$ aws iam delete-access-key --user-name MyUser --access-key-id AKIAIOSFODNN7EXAMPLE
```

# AWS CLI에서 Amazon S3 사용
<a name="cli-services-s3"></a>


| Amazon Simple Storage Service(Amazon S3) 소개 | 
| --- | 
|    | 

AWS Command Line Interface(AWS CLI)를 사용하여 Amazon Simple Storage Service(Amazon S3)의 기능에 액세스할 수 있습니다. Amazon S3는 확장성과 내구성이 뛰어난 객체 스토리지 서비스입니다. Amazon S3는 사실상 무제한의 스토리지 용량을 제공하도록 설계되어 다양한 데이터 스토리지 및 관리 요구 사항을 충족하는 이상적인 솔루션입니다.

Amazon S3를 사용하면 작은 파일부터 대용량 데이터세트에 이르기까지 모든 종류의 데이터를 객체 형태로 저장하고 검색할 수 있습니다. 각 객체는 버킷이라는 컨테이너에 저장되며, AWS Management Console을 통해 또는 AWS SDK, 도구 및 AWS CLI를 통해 프로그래밍 방식으로 액세스하고 관리할 수 있습니다.

기본 스토리지를 비롯하여 Amazon S3는 수명 주기 관리, 버전 관리, 확장성 및 보안을 비롯한 다양한 기능을 제공합니다. 다른 AWS 서비스와 통합되어 필요에 따라 확장할 수 있는 클라우드 기반 솔루션을 구축할 수 있습니다.

AWS CLI는 Amazon S3에 액세스하기 위한 2가지 티어의 명령을 제공합니다.
+ **s3** - 객체 및 버킷 생성, 조작, 삭제, 동기화 등 일반적인 태스크 수행을 간소화하는 AWS CLI 전용 사용자 지정 상위 수준 명령입니다.
+ **s3api** - 모든 Amazon S3 API 작업에 대한 직접 액세스를 제공하며, 이를 통해 고급 작업을 수행할 수 있습니다.

**Topics**
+ [AWS CLI에서 상위 수준(s3) 명령 사용](cli-services-s3-commands.md)
+ [AWS CLI에서 API 수준(s3api) 명령 사용](cli-services-s3-apicommands.md)
+ [AWS CLI의 Amazon S3 버킷 수명 주기에 대한 스크립팅 예제](cli-services-s3-lifecycle-example.md)

# AWS CLI에서 상위 수준(s3) 명령 사용
<a name="cli-services-s3-commands"></a>

이 주제에서는 AWS CLI에서 [https://docs.aws.amazon.com/cli/latest/reference/s3/index.html](https://docs.aws.amazon.com/cli/latest/reference/s3/index.html) 명령을 사용하여 Amazon S3 버킷과 객체를 관리하는 데 사용할 수 있는 몇 가지 명령을 설명합니다. 이 주제에서 다루지 않은 명령과 추가 명령 예제는 *AWS CLI 참조*에 있는 [https://docs.aws.amazon.com/cli/latest/reference/s3/index.html](https://docs.aws.amazon.com/cli/latest/reference/s3/index.html) 명령을 참조하세요.

상위 수준 `aws s3` 명령은 Amazon S3 객체 관리를 간소화합니다. 이 명령을 사용하면 명령 자체 내에서와 로컬 디렉터리를 사용하여 Amazon S3의 내용을 관리할 수 있습니다.

**Topics**
+ [사전 조건](#using-s3-commands-prereqs)
+ [시작하기 전에](#using-s3-commands-before)
+ [버킷 만들기](#using-s3-commands-managing-buckets-creating)
+ [버킷 및 객체 나열](#using-s3-commands-listing-buckets)
+ [버킷 삭제](#using-s3-commands-delete-buckets)
+ [객체 삭제](#using-s3-commands-delete-objects)
+ [객체 이동](#using-s3-commands-managing-objects-move)
+ [객체 복사](#using-s3-commands-managing-objects-copy)
+ [객체 동기화](#using-s3-commands-managing-objects-sync)
+ [s3 명령에 자주 사용되는 옵션](#using-s3-commands-managing-objects-param)
+ [리소스](#using-s3-commands-managing-buckets-references)

## 사전 조건
<a name="using-s3-commands-prereqs"></a>

`s3` 명령을 실행하려면 다음을 수행해야 합니다.
+ AWS CLI를 설치하고 구성합니다. 자세한 내용은 [최신 버전의 AWS CLI 설치 또는 업데이트](getting-started-install.md) 및 [AWS CLI에 대한 인증 및 액세스 보안 인증](cli-chap-authentication.md) 섹션을 참조하세요.
+ 사용하는 프로파일에는 예제에서 수행하는 AWS 작업을 허용하는 권한이 있어야 합니다.
+ 다음 Amazon S3 용어를 이해하세요.
  + **버킷** - 최상위 Amazon S3 폴더입니다.
  + **접두사** - 버킷의 Amazon S3 폴더입니다.
  + **객체** - Amazon S3 버킷에서 호스팅되는 모든 항목입니다.

## 시작하기 전에
<a name="using-s3-commands-before"></a>

이 섹션에서는 `aws s3` 명령을 사용하기 전에 주의해야 할 몇 가지 사항에 대해 설명합니다.

### 대용량 객체 업로드
<a name="using-s3-commands-before-large"></a>

`aws s3` 명령을 사용하여 Amazon S3 버킷에 대용량 객체를 업로드하면 AWS CLI에서 자동으로 멀티파트 업로드를 수행합니다. 이러한 `aws s3` 명령을 사용할 때는 실패한 업로드를 재개할 수 없습니다.

시간 초과로 인해 멀티파트 업로드가 실패하거나 AWS CLI에서 수동으로 취소할 경우 AWS CLI는 업로드를 중지하고 생성된 모든 파일을 정리합니다. 이 프로세스는 몇 분 정도 걸릴 수 있습니다.

kill 명령이나 시스템 오류로 인해 멀티파트 업로드 또는 정리 프로세스가 취소되면 생성된 파일은 Amazon S3 버킷에 남아 있습니다. 멀티파트 업로드를 정리하려면 [s3api abort-multipart-upload](https://docs.aws.amazon.com/cli/latest/reference/s3api/abort-multipart-upload.html) 명령을 사용합니다.

### 멀티파트 복사의 파일 속성 및 태그
<a name="using-s3-commands-before-tags"></a>

`aws s3` 네임스페이스에서 AWS CLI 버전 1 버전의 명령을 사용하여 한 Amazon S3 버킷 위치에서 다른 Amazon S3 버킷 위치로 파일을 복사하고 해당 작업에서 [멀티파트 복사](https://docs.aws.amazon.com/AmazonS3/latest/userguide/CopyingObjctsMPUapi.html)를 사용하는 경우 소스 객체의 파일 속성은 대상 객체로 복사되지 않습니다.

기본적으로 멀티파트 복사를 수행하는 `s3` 네임스페이스의 AWS CLI 버전 2 명령은 모든 태그 및 속성 세트(`content-type`, `content-language`, `content-encoding`, `content-disposition`, `cache-control`, `expires`, `metadata`)를 소스에서 대상 복사로 전송합니다.

이렇게 하면 AWS CLI 버전 1을 사용한 경우 만들어지지 않았던 Amazon S3 엔드포인트에 대한 추가 AWS API 호출이 가능합니다. 여기에는 `HeadObject`, `GetObjectTagging` 및 `PutObjectTagging`이 포함됩니다.

AWS CLI 버전 2 명령에서 이 기본 동작을 변경해야 하는 경우 `--copy-props` 파라미터를 사용하여 다음 옵션 중 하나를 지정합니다.
+ **default** - 기본값입니다. 소스 객체에 연결된 모든 태그와 비 멀티파트 복사에 사용되는 `--metadata-directive` 파라미터에 포함된 속성(`content-type`, `content-language`, `content-encoding`, `content-disposition`, `cache-control`, `expires` 및 `metadata`)이 복사에 포함되도록 지정합니다.
+ **metadata-directive** - 비 멀티파트 복사에 사용되는 `--metadata-directive` 파라미터에 포함된 속성만 복사에 포함되도록 지정합니다. 태그는 복사하지 않습니다.
+ **none** - 소스 객체의 속성이 복사에 포함되지 않도록 지정합니다.

## 버킷 만들기
<a name="using-s3-commands-managing-buckets-creating"></a>

[https://docs.aws.amazon.com/cli/latest/reference/s3/mb.html](https://docs.aws.amazon.com/cli/latest/reference/s3/mb.html) 명령을 사용하여 버킷을 만듭니다. 버킷 이름은 ***글로벌로*** 고유(모든 Amazon S3에서 고유)해야 하며 DNS를 준수해야 합니다.

버킷 이름에는 소문자, 숫자, 하이픈, 마침표가 포함될 수 있습니다. 버킷 이름은 문자나 숫자로만 시작하고 끝날 수 있으며 하이픈이나 다른 마침표 옆에 마침표가 포함될 수 없습니다.

**구문**:

```
$ aws s3 mb <target> [--options]
```

### s3 mb 예제
<a name="using-s3-commands-managing-buckets-creating-examples"></a>

다음 예제에서는 `s3://amzn-s3-demo-bucket` 버킷을 생성합니다.

```
$ aws s3 mb s3://amzn-s3-demo-bucket
```

## 버킷 및 객체 나열
<a name="using-s3-commands-listing-buckets"></a>

버킷, 폴더 또는 객체를 나열하려면 [https://docs.aws.amazon.com/cli/latest/reference/s3/ls.html](https://docs.aws.amazon.com/cli/latest/reference/s3/ls.html) 명령을 사용합니다. 대상 또는 옵션 없이 명령을 사용하면 모든 버킷이 나열됩니다.

**구문**:

```
$ aws s3 ls <target> [--options]
```

이 명령과 함께 사용할 몇 가지 일반적인 옵션 및 예제는 [s3 명령에 자주 사용되는 옵션](#using-s3-commands-managing-objects-param) 섹션을 참조하세요. 사용 가능한 옵션의 전체 목록은 *AWS CLI 명령 참조*에서 [https://docs.aws.amazon.com/cli/latest/reference/s3/ls.html](https://docs.aws.amazon.com/cli/latest/reference/s3/ls.html) 섹션을 참조하세요.

### s3 ls 예제
<a name="using-s3-commands-managing-objects-list-examples"></a>

다음 예제에서는 모든 Amazon S3 버킷을 나열합니다.

```
$ aws s3 ls
2018-12-11 17:08:50 amzn-s3-demo-bucket1
2018-12-14 14:55:44 amzn-s3-demo-bucket2
```

다음 명령은 버킷에 있는 모든 객체와 접두사를 나열합니다. 이 예제 출력에서 접두사 `example/`에는 `MyFile1.txt`라는 이름의 파일이 하나 있습니다.

```
$ aws s3 ls s3://amzn-s3-demo-bucket
                           PRE example/
2018-12-04 19:05:48          3 MyFile1.txt
```

명령에 특정 접두사를 포함하여 출력을 필터링할 수 있습니다. 다음 명령은 *bucket-name/example/*에 있는 객체(즉, 접두사 *example/*을 기준으로 필터링된 *bucket-name*에 있는 객체)를 나열합니다.

```
$ aws s3 ls s3://amzn-s3-demo-bucket/example/
2018-12-06 18:59:32          3 MyFile1.txt
```

특정 리전의 버킷과 객체만 표시하려면 `--region` 옵션을 사용합니다.

```
$ aws s3 ls --region us-east-2
2018-12-06 18:59:32          3 MyFile1.txt
```

버킷 및 객체 목록이 많은 경우 `--max-items` 또는 `--page-size` 옵션을 사용하여 결과를 페이지 매김할 수 있습니다. `--max-items` 옵션은 직접 호출에서 반환되는 총 버킷 및 객체 수를 제한하고 `--page-size` 옵션은 페이지에 나열된 버킷 및 객체 수를 제한합니다.

```
$ aws s3 ls --max-items 100 --page-size 10
```

페이지 매김에 대한 자세한 내용은 [--page-size 파라미터를 사용하는 방법](cli-usage-pagination.md#cli-usage-pagination-pagesize) 및 [--max-items 파라미터를 사용하는 방법](cli-usage-pagination.md#cli-usage-pagination-maxitems) 섹션을 참조하세요.

## 버킷 삭제
<a name="using-s3-commands-delete-buckets"></a>

버킷을 삭제하려면 [https://docs.aws.amazon.com/cli/latest/reference/s3/rb.html](https://docs.aws.amazon.com/cli/latest/reference/s3/rb.html) 명령을 사용합니다.

**구문**:

```
$ aws s3 rb <target> [--options]
```

### s3 rb 예제
<a name="using-s3-commands-removing-buckets-examples"></a>

다음 예제에서는 `s3://amzn-s3-demo-bucket` 버킷을 제거합니다.

```
$ aws s3 rb s3://amzn-s3-demo-bucket
```

기본적으로 작업에 성공하려면 버킷이 비어 있어야 합니다. 비어 있지 않은 버킷을 제거하려면 `--force` 옵션을 포함시켜야 합니다. 이전에 삭제했지만 보관된 객체가 포함되어 있는 버전 지정된 버킷을 사용할 경우 이 명령을 사용하여 버킷을 제거할 수 *없습니다*. 먼저 모든 내용을 제거해야 합니다.

다음 예제에서는 버킷의 모든 객체와 접두사를 삭제한 다음 버킷을 삭제합니다.

```
$ aws s3 rb s3://amzn-s3-demo-bucket --force
```

## 객체 삭제
<a name="using-s3-commands-delete-objects"></a>

버킷이나 로컬 디렉터리의 객체를 삭제하려면 [https://docs.aws.amazon.com/cli/latest/reference/s3/rm.html](https://docs.aws.amazon.com/cli/latest/reference/s3/rm.html) 명령을 사용합니다.

**구문**:

```
$ aws s3 rm  <target> [--options]
```

이 명령과 함께 사용할 몇 가지 일반적인 옵션 및 예제는 [s3 명령에 자주 사용되는 옵션](#using-s3-commands-managing-objects-param) 섹션을 참조하세요. 전체 옵션 목록은 *AWS CLI 명령 참조*에서 [https://docs.aws.amazon.com/cli/latest/reference/s3/rm.html](https://docs.aws.amazon.com/cli/latest/reference/s3/rm.html) 섹션을 참조하세요.

### s3 rm 예제
<a name="using-s3-commands-delete-objects-examples"></a>

다음 예제에서는 `filename.txt`에서 `s3://amzn-s3-demo-bucket/example` 파일을 삭제합니다.

```
$ aws s3 rm s3://amzn-s3-demo-bucket/example/filename.txt
```

다음 예제에서는 `s3://amzn-s3-demo-bucket/example` 옵션을 사용하여 `--recursive`에서 모든 객체를 삭제합니다.

```
$ aws s3 rm s3://amzn-s3-demo-bucket/example --recursive
```

## 객체 이동
<a name="using-s3-commands-managing-objects-move"></a>

[https://docs.aws.amazon.com/cli/latest/reference/s3/mv.html](https://docs.aws.amazon.com/cli/latest/reference/s3/mv.html) 명령을 사용하여 버킷이나 로컬 디렉터리에서 객체를 이동합니다. `s3 mv` 명령은 소스 객체 또는 파일을 지정된 대상에 복사한 다음 소스 객체 또는 파일을 삭제합니다.

**구문**:

```
$ aws s3 mv <source> <target> [--options]
```

이 명령과 함께 사용할 몇 가지 일반적인 옵션 및 예제는 [s3 명령에 자주 사용되는 옵션](#using-s3-commands-managing-objects-param) 섹션을 참조하세요. 사용 가능한 옵션의 전체 목록은 *AWS CLI 명령 참조*에서 [https://docs.aws.amazon.com/cli/latest/reference/s3/mv.html](https://docs.aws.amazon.com/cli/latest/reference/s3/mv.html) 섹션을 참조하세요.

**주의**  
Amazon S3 소스 또는 대상 URI에서 어떤 유형의 액세스 포인트 ARN 또는 액세스 포인트 별칭을 사용하는 경우, 소스 및 대상 Amazon S3 URI가 서로 다른 기본 버킷으로 확인되도록 각별히 주의해야 합니다. 소스 버킷과 대상 버킷이 동일한 경우 소스 파일이나 객체를 그 자체로 옮길 수 있어 실수로 소스 파일이나 객체가 삭제될 수 있습니다. 소스 버킷과 대상 버킷이 동일하지 않은지 확인하려면 `--validate-same-s3-paths` 파라미터를 사용하거나 환경 변수 ``AWS_CLI_S3_MV_VALIDATE_SAME_S3_PATHS``를 `true`로 설정하세요.

### s3 mv 예제
<a name="using-s3-commands-managing-objects-move-examples"></a>

다음 예제에서는 `s3://amzn-s3-demo-bucket/example`에서 모든 객체를 `s3://amzn-s3-demo-bucket/`으로 이동합니다.

```
$ aws s3 mv s3://amzn-s3-demo-bucket/example s3://amzn-s3-demo-bucket/
```

다음 예제에서는 `s3 mv` 명령을 사용하여 현재 작업 디렉터리에서 Amazon S3 버킷으로 로컬 파일을 이동합니다.

```
$ aws s3 mv filename.txt s3://amzn-s3-demo-bucket
```

다음 예제에서는 Amazon S3 버킷에서 현재 작업 디렉터리로 파일을 이동합니다. 여기서 `./`는 현재 작업 디렉터리를 지정합니다.

```
$ aws s3 mv s3://amzn-s3-demo-bucket/filename.txt ./
```

## 객체 복사
<a name="using-s3-commands-managing-objects-copy"></a>

[https://docs.aws.amazon.com/cli/latest/reference/s3/cp.html](https://docs.aws.amazon.com/cli/latest/reference/s3/cp.html) 명령을 사용하여 버킷이나 로컬 디렉터리에서 객체를 복사합니다.

**구문**:

```
$ aws s3 cp <source> <target> [--options]
```

표준 입력(`stdin`) 또는 표준 출력(`stdout`)으로의 파일 스트리밍을 위해 dash 파라미터를 사용할 수 있습니다.

**주의**  
PowerShell을 사용하는 경우 셸은 CRLF의 인코딩을 변경하거나, 파이프 입력이나 출력 또는 리디렉션된 출력에 CRLF를 추가할 수 있습니다.

`s3 cp` 명령은 다음 구문을 사용하여 `stdin`에서 지정된 버킷으로 파일 스트림을 업로드합니다.

**구문**:

```
$ aws s3 cp - <target> [--options]
```

`s3 cp` 명령은 다음 구문을 사용하여 `stdout`에 대한 Amazon S3 파일 스트림을 다운로드합니다.

**구문**:

```
$ aws s3 cp <target> [--options] -
```

이 명령과 함께 사용할 몇 가지 일반적인 옵션 및 예제는 [s3 명령에 자주 사용되는 옵션](#using-s3-commands-managing-objects-param) 섹션을 참조하세요. 전체 옵션 목록은 *AWS CLI 명령 참조*에서 [https://docs.aws.amazon.com/cli/latest/reference/s3/cp.html](https://docs.aws.amazon.com/cli/latest/reference/s3/cp.html) 섹션을 참조하세요.

### `s3 cp` 예제
<a name="using-s3-commands-managing-objects-copy-examples"></a>

다음 예제에서는 `s3://amzn-s3-demo-bucket/example`에서 `s3://amzn-s3-demo-bucket/`으로 모든 객체를 복사합니다.

```
$ aws s3 cp s3://amzn-s3-demo-bucket/example s3://amzn-s3-demo-bucket/
```

다음 예제에서는 `s3 cp` 명령을 사용하여 현재 작업 디렉터리에서 Amazon S3 버킷으로 로컬 파일을 복사합니다.

```
$ aws s3 cp filename.txt s3://amzn-s3-demo-bucket
```

다음 예제에서는 Amazon S3 버킷에서 현재 작업 디렉터리로 파일을 복사합니다. 여기서 `./`는 현재 작업 디렉터리를 지정합니다.

```
$ aws s3 cp s3://amzn-s3-demo-bucket/filename.txt ./
```

다음 예제에서는 echo를 사용하여 "hello world" 텍스트를 `s3://bucket-name/filename.txt` 파일로 스트리밍합니다.

```
$ echo "hello world" | aws s3 cp - s3://amzn-s3-demo-bucket/filename.txt
```

다음 예제에서는 `s3://amzn-s3-demo-bucket/filename.txt` 파일을 `stdout`으로 스트리밍하고 내용을 콘솔로 인쇄합니다.

```
$ aws s3 cp s3://amzn-s3-demo-bucket/filename.txt -
hello world
```

다음 예제에서는 `s3://bucket-name/pre`의 내용을 `stdout`으로 스트리밍하고, `bzip2` 명령을 사용하여 파일을 압축하고 `key.bz2`라는 새 압축 파일을 `s3://bucket-name`에 업로드합니다.

```
$ aws s3 cp s3://amzn-s3-demo-bucket/pre - | bzip2 --best | aws s3 cp - s3://amzn-s3-demo-bucket/key.bz2
```

## 객체 동기화
<a name="using-s3-commands-managing-objects-sync"></a>

[https://docs.aws.amazon.com/cli/latest/reference/s3/sync.html](https://docs.aws.amazon.com/cli/latest/reference/s3/sync.html) 명령은 버킷과 디렉터리의 콘텐츠 또는 두 버킷의 콘텐츠를 동기화합니다. 일반적으로 `s3 sync`는 원본과 대상 간에 누락되거나 오래된 파일 또는 객체를 복사합니다. 하지만 `--delete` 옵션을 제공하여 원본에 없는 파일이나 객체를 대상에서 제거할 수도 있습니다.

**구문**:

```
$ aws s3 sync <source> <target> [--options]
```

이 명령과 함께 사용할 몇 가지 일반적인 옵션 및 예제는 [s3 명령에 자주 사용되는 옵션](#using-s3-commands-managing-objects-param) 섹션을 참조하세요. 전체 옵션 목록은 *AWS CLI 명령 참조*에서 [https://docs.aws.amazon.com/cli/latest/reference/s3/sync.html](https://docs.aws.amazon.com/cli/latest/reference/s3/sync.html) 섹션을 참조하세요.

### s3 동기화 예제
<a name="using-s3-commands-managing-objects-sync-examples"></a>

다음 예제에서는 *amzn-s3-demo-bucket*이라는 버킷에 있는 *path*라는 Amazon S3 접두사의 내용을 현재 작업 디렉터리와 동기화합니다.

`s3 sync`는 대상에 있는 동일한 이름의 파일과 크기 또는 수정 시간이 다른 모든 파일을 업데이트합니다. 출력에는 동기화 중에 수행된 특정 작업이 표시됩니다. 이 작업은 하위 디렉터리 `MySubdirectory`와 해당 내용을 `s3://amzn-s3-demo-bucket/path/MySubdirectory`와 반복적으로 동기화합니다.

```
$ aws s3 sync . s3://amzn-s3-demo-bucket/path
upload: MySubdirectory\MyFile3.txt to s3://amzn-s3-demo-bucket/path/MySubdirectory/MyFile3.txt
upload: MyFile2.txt to s3://amzn-s3-demo-bucket/path/MyFile2.txt
upload: MyFile1.txt to s3://amzn-s3-demo-bucket/path/MyFile1.txt
```

다음 예제에서는 이전 예제를 확장하여 `--delete` 옵션을 사용하는 방법을 보여줍니다.

```
// Delete local file
$ rm ./MyFile1.txt

// Attempt sync without --delete option - nothing happens
$ aws s3 sync . s3://amzn-s3-demo-bucket/path

// Sync with deletion - object is deleted from bucket
$ aws s3 sync . s3://amzn-s3-demo-bucket/path --delete
delete: s3://amzn-s3-demo-bucket/path/MyFile1.txt

// Delete object from bucket
$ aws s3 rm s3://amzn-s3-demo-bucket/path/MySubdirectory/MyFile3.txt
delete: s3://amzn-s3-demo-bucket/path/MySubdirectory/MyFile3.txt

// Sync with deletion - local file is deleted
$ aws s3 sync s3://amzn-s3-demo-bucket/path . --delete
delete: MySubdirectory\MyFile3.txt

// Sync with Infrequent Access storage class
$ aws s3 sync . s3://amzn-s3-demo-bucket/path --storage-class STANDARD_IA
```

`--delete` 옵션을 사용할 때 `--exclude` 및 `--include` 옵션은 `s3 sync` 작업 중에 삭제할 파일 또는 객체를 필터링할 수 있습니다. 이 경우 파라미터 문자열은 대상 디렉터리 또는 버킷의 맥락에서 삭제에서 제외하거나 삭제를 위해 포함할 파일을 지정해야 합니다. 다음은 그 한 예입니다.

```
Assume local directory and s3://amzn-s3-demo-bucket/path currently in sync and each contains 3 files:
MyFile1.txt
MyFile2.rtf
MyFile88.txt
'''

// Sync with delete, excluding files that match a pattern. MyFile88.txt is deleted, while remote MyFile1.txt is not.
$ aws s3 sync . s3://amzn-s3-demo-bucket/path --delete --exclude "path/MyFile?.txt"
delete: s3://amzn-s3-demo-bucket/path/MyFile88.txt
'''

// Sync with delete, excluding MyFile2.rtf - local file is NOT deleted
$ aws s3 sync s3://amzn-s3-demo-bucket/path . --delete --exclude "./MyFile2.rtf"
download: s3://amzn-s3-demo-bucket/path/MyFile1.txt to MyFile1.txt
'''

// Sync with delete, local copy of MyFile2.rtf is deleted
$ aws s3 sync s3://amzn-s3-demo-bucket/path . --delete
delete: MyFile2.rtf
```

## s3 명령에 자주 사용되는 옵션
<a name="using-s3-commands-managing-objects-param"></a>

다음 옵션은 이 주제에서 설명하는 명령에 자주 사용됩니다. 명령에 사용할 수 있는 옵션의 전체 목록은 [AWS CLI 버전 2 참조 가이드](https://docs.aws.amazon.com/cli/latest/reference/index.html)의 특정 명령을 참조하세요.

**acl**  
`s3 sync` 및 `s3 cp`는 `--acl` 옵션을 사용할 수 있습니다. 이렇게 하면 Amazon S3에 복사된 파일에 대한 액세스 권한을 설정할 수 있습니다. `--acl` 옵션에는 `private`, `public-read` 및 `public-read-write` 값을 적용할 수 있습니다. 자세한 내용은 *Amazon S3 사용 설명서*의 [미리 제공된 ACL](https://docs.aws.amazon.com/AmazonS3/latest/userguide/acl-overview.html#canned-acl)을 참조하세요.  

```
$ aws s3 sync . s3://amzn-s3-demo-bucket/path --acl public-read
```

**exclude**  
`s3 cp`, `s3 mv`, `s3 sync` 또는 `s3 rm` 명령을 사용하는 경우 `--exclude` 또는 `--include` 옵션을 사용하여 결과를 필터링할 수 있습니다. `--exclude` 옵션은 명령에서 객체만 제외하도록 규칙을 설정하고 옵션은 지정된 순서대로 적용됩니다. 방법은 다음 예제와 같습니다.  

```
Local directory contains 3 files:
MyFile1.txt
MyFile2.rtf
MyFile88.txt

// Exclude all .txt files, resulting in only MyFile2.rtf being copied
$ aws s3 cp . s3://amzn-s3-demo-bucket/path --exclude "*.txt"

// Exclude all .txt files but include all files with the "MyFile*.txt" format, resulting in, MyFile1.txt, MyFile2.rtf, MyFile88.txt being copied
$ aws s3 cp . s3://amzn-s3-demo-bucket/path --exclude "*.txt" --include "MyFile*.txt"

// Exclude all .txt files, but include all files with the "MyFile*.txt" format, but exclude all files with the "MyFile?.txt" format resulting in, MyFile2.rtf and MyFile88.txt being copied
$ aws s3 cp . s3://amzn-s3-demo-bucket/path --exclude "*.txt" --include "MyFile*.txt" --exclude "MyFile?.txt"
```

**포함**  
`s3 cp`, `s3 mv`, `s3 sync` 또는 `s3 rm` 명령을 사용하는 경우 `--exclude` 또는 `--include` 옵션을 사용하여 결과를 필터링할 수 있습니다. `--include` 옵션은 명령에 지정된 객체만 포함하도록 규칙을 설정하며 옵션은 지정된 순서대로 적용됩니다. 방법은 다음 예제와 같습니다.  

```
Local directory contains 3 files:
MyFile1.txt
MyFile2.rtf
MyFile88.txt

// Include all .txt files, resulting in MyFile1.txt and MyFile88.txt being copied
$ aws s3 cp . s3://amzn-s3-demo-bucket/path --include "*.txt"

// Include all .txt files but exclude all files with the "MyFile*.txt" format, resulting in no files being copied
$ aws s3 cp . s3://amzn-s3-demo-bucket/path --include "*.txt" --exclude "MyFile*.txt"

// Include all .txt files, but exclude all files with the "MyFile*.txt" format, but include all files with the "MyFile?.txt" format resulting in MyFile1.txt being copied

$ aws s3 cp . s3://amzn-s3-demo-bucket/path --include "*.txt" --exclude "MyFile*.txt" --include "MyFile?.txt"
```

**권한 부여**  
`s3 cp`, `s3 mv` 및 `s3 sync` 명령에는 지정된 사용자 또는 그룹에게 객체에 대한 권한을 부여하기 위해 사용할 수 있는 `--grants` 옵션이 포함됩니다. 다음 구문을 사용하여 `--grants` 옵션을 권한 목록으로 설정합니다. `Permission`, `Grantee_Type` 및 `Grantee_ID`를 사용자의 값으로 바꿉니다.  
**구문**:  

```
--grants Permission=Grantee_Type=Grantee_ID
         [Permission=Grantee_Type=Grantee_ID ...]
```
각 값에는 다음 요소가 포함됩니다.  
+ *Permission* - 부여된 권한을 지정합니다. `read`, `readacl`, `writeacl` 또는 `full`로 설정할 수 있습니다.
+ *Grantee\$1Type* - 피부여자 식별 방법을 지정합니다. `uri`, `emailaddress` 또는 `id`로 설정할 수 있습니다.
+ *Grantee\$1ID* - *Grantee\$1Type*을 기준으로 피부여자를 지정합니다.
  + `uri` – 그룹의 URI입니다. 자세한 내용은 [피부여자란?](https://docs.aws.amazon.com/AmazonS3/latest/userguide/ACLOverview.html#SpecifyingGrantee)을 참조하세요.
  + `emailaddress` - 계정의 이메일 주소입니다.
  + `id` - 계정의 정식 ID입니다.
Amazon S3 액세스 제어에 대한 자세한 내용은 [액세스 제어](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingAuthAccess.html)를 참조하세요.  
다음 예제에서는 버킷에 객체를 복사합니다. 여기서는 모든 사람에게 객체에 대한 `read` 권한을 부여하고 `full`과 연결된 계정에 `read` 권한(`readacl`, `writeacl` 및 `user@example.com`)을 부여합니다.  

```
$ aws s3 cp file.txt s3://amzn-s3-demo-bucket/ --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers full=emailaddress=user@example.com
```
Amazon S3에 업로드하는 객체에 대해 기본값이 아닌 스토리지 클래스(`REDUCED_REDUNDANCY` 또는 `STANDARD_IA`)를 지정할 수도 있습니다. 이렇게 하려면 `--storage-class` 옵션을 사용합니다.  

```
$ aws s3 cp file.txt s3://amzn-s3-demo-bucket/ --storage-class REDUCED_REDUNDANCY
```

**no-overwrite**  
`s3 cp`, `s3 mv` 및 `s3 sync` 명령에는 대상에 이미 존재하는 객체를 덮어쓰지 않도록 하는 `--no-overwrite` 옵션이 포함되어 있습니다.  
다음 예제에서는 객체가 로컬 디렉터리에 아직 없는 경우에만 버킷에서 로컬 디렉터리로 객체를 복사합니다.  

```
$ aws s3 cp --no-overwrite s3://amzn-s3-demo-bucket/file.txt file.txt
```
다음 예제에서는 로컬 디렉터리의 파일을 버킷에 재귀적으로 복사합니다. 버킷에 아직 존재하지 않는 파일만 복사합니다.  

```
$ aws s3 cp --recursive --no-overwrite /path/to/demo-files/ s3://amzn-s3-demo-bucket/demo-files/
```
다음 예제에서는 버킷 대상 위치에 객체가 아직 없는 경우에만 로컬 디렉터리에서 버킷으로 객체를 이동합니다.  

```
$ aws s3 mv --no-overwrite file.txt s3://amzn-s3-demo-bucket/file.txt
```
다음 예제에서는 로컬 디렉터리의 파일을 버킷에 동기화합니다. 대상 버킷에 아직 존재하지 않는 파일만 동기화됩니다.  

```
$ aws s3 sync --no-overwrite /path/to/demo-files/ s3://amzn-s3-demo-bucket/demo-files/
```

**recursive**  
이 옵션을 사용하면 지정된 디렉터리 또는 접두사 아래의 모든 파일 또는 객체에 대해 명령이 수행됩니다. 다음 예제에서는 `s3://amzn-s3-demo-bucket/path` 및 모든 내용을 삭제합니다.  

```
$ aws s3 rm s3://amzn-s3-demo-bucket/path --recursive
```

## 리소스
<a name="using-s3-commands-managing-buckets-references"></a>

**AWS CLI 참조:** 
+ [https://docs.aws.amazon.com/cli/latest/reference/s3/index.html](https://docs.aws.amazon.com/cli/latest/reference/s3/index.html)
+ [https://docs.aws.amazon.com/cli/latest/reference/s3/cp.html](https://docs.aws.amazon.com/cli/latest/reference/s3/cp.html)
+ [https://docs.aws.amazon.com/cli/latest/reference/s3/mb.html](https://docs.aws.amazon.com/cli/latest/reference/s3/mb.html)
+ [https://docs.aws.amazon.com/cli/latest/reference/s3/mv.html](https://docs.aws.amazon.com/cli/latest/reference/s3/mv.html)
+ [https://docs.aws.amazon.com/cli/latest/reference/s3/ls.html](https://docs.aws.amazon.com/cli/latest/reference/s3/ls.html)
+ [https://docs.aws.amazon.com/cli/latest/reference/s3/rb.html](https://docs.aws.amazon.com/cli/latest/reference/s3/rb.html)
+ [https://docs.aws.amazon.com/cli/latest/reference/s3/rm.html](https://docs.aws.amazon.com/cli/latest/reference/s3/rm.html)
+ [https://docs.aws.amazon.com/cli/latest/reference/s3/sync.html](https://docs.aws.amazon.com/cli/latest/reference/s3/sync.html)

**서비스 참조:**
+ **Amazon S3 사용 설명서의 [Amazon S3 버킷 작업](https://docs.aws.amazon.com//AmazonS3/latest/userguide/UsingBucket.html)
+ **Amazon S3 사용 설명서의 [Amazon S3 버킷 작업](https://docs.aws.amazon.com//AmazonS3/latest/userguide/UsingObjects.html)
+ **Amazon S3 사용 설명서의 [접두사 및 구분 기호를 사용하여 계층적 구조로 키 나열](https://docs.aws.amazon.com//AmazonS3/latest/userguide/ListingKeysHierarchy.html)
+ **Amazon S3 사용 설명서의 [AWS SDK for .NET(낮은 수준)를 사용하여 S3 버킷에 대한 멀티파트 업로드 중단](https://docs.aws.amazon.com//AmazonS3/latest/userguide/LLAbortMPUnet.html)

# AWS CLI에서 API 수준(s3api) 명령 사용
<a name="cli-services-s3-apicommands"></a>

API 수준 명령(`s3api` 명령 세트에 포함됨)을 사용하면 Amazon Simple Storage Service(Amazon S3) API에 직접 액세스할 수 있으며 상위 수준 `s3` 명령에 표시되지 않는 일부 작업을 활성화할 수 있습니다. 이러한 명령은 서비스의 기능에 대한 API 수준 액세스를 제공하는 다른 AWS 서비스와 동등합니다. `s3` 명령어에 대한 자세한 내용은 [AWS CLI에서 상위 수준(s3) 명령 사용](cli-services-s3-commands.md) 섹션을 참조하세요.

이 주제에서는 Amazon S3 API에 매핑되는 하위 수준 명령을 사용하는 방법을 보여주는 예제를 제공합니다. 또한 각 S3 API 명령에 대한 예제는 [AWS CLI 버전 2 참조 가이드](https://docs.aws.amazon.com/cli/latest/reference/s3api/index.html)의 `s3api` 섹션에서 찾을 수 있습니다.

**Topics**
+ [사전 조건](#cli-services-s3-apicommands-prereqs)
+ [사용자 지정 ACL 적용](#cli-services-s3-apicommands-acls)
+ [로깅 정책 구성](#cli-services-s3-apicommands-logpol)
+ [리소스](#cli-services-s3-apicommands-resources)

## 사전 조건
<a name="cli-services-s3-apicommands-prereqs"></a>

`s3api` 명령을 실행하려면 다음을 수행해야 합니다.
+ AWS CLI를 설치하고 구성합니다. 자세한 내용은 [최신 버전의 AWS CLI 설치 또는 업데이트](getting-started-install.md) 및 [AWS CLI에 대한 인증 및 액세스 보안 인증](cli-chap-authentication.md) 섹션을 참조하세요.
+ 사용하는 프로파일에는 예제에서 수행하는 AWS 작업을 허용하는 권한이 있어야 합니다.
+ 다음 Amazon S3 용어를 이해하세요.
  + **버킷** - 최상위 Amazon S3 폴더입니다.
  + **접두사** - 버킷의 Amazon S3 폴더입니다.
  + **객체** - Amazon S3 버킷에서 호스팅되는 모든 항목입니다.

## 사용자 지정 ACL 적용
<a name="cli-services-s3-apicommands-acls"></a>

고급 명령을 사용하면 `--acl` 옵션을 사용하여 Amazon S3 객체에 미리 정의된 액세스 제어 목록(ACL)을 적용할 수 있습니다. 그러나 이 명령을 사용해도 버킷 전체 ACL을 설정할 수는 없습니다. 그러나 ```[put-bucket-acl](https://docs.aws.amazon.com/cli/latest/reference/s3api/put-bucket-acl.html)` API 수준 명령을 사용하여 이 작업을 수행할 수 있습니다.

다음 예제에서는 두 명의 AWS 사용자(*user1@example.com* 및 *user2@example.com*)에게 전체 제어 권한을 부여하고 모든 사람에게 읽기 권한을 부여하는 방법을 보여줍니다. "모든 사람"의 식별자는 파라미터로 전달하는 특수 URI에서 가져옵니다.

```
$ aws s3api put-bucket-acl --bucket amzn-s3-demo-bucket --grant-full-control 'emailaddress="user1@example.com",emailaddress="user2@example.com"' --grant-read 'uri="http://acs.amazonaws.com/groups/global/AllUsers"'
```

ACL을 구성하는 방법에 대한 자세한 내용은 *Amazon Simple Storage Service API 참조*에서 [PUT Bucket acl](https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTacl.html)을 참조하세요. CLI에서 `s3api`와 같은 `put-bucket-acl` ACL 명령은 동일한 [간편 인수 표기법](https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-shorthand.html)을 사용합니다.

## 로깅 정책 구성
<a name="cli-services-s3-apicommands-logpol"></a>

API 명령인 `put-bucket-logging`은 버킷 로깅 정책을 구성합니다.

다음 예제에서 AWS 사용자 *user@example.com*에게는 로그 파일을 완전히 제어하는 권한이 부여되며, 모든 사용자는 읽기 액세스 권한을 갖게 됩니다. 로그를 읽고 버킷에 쓰는 데 필요한 권한을 Amazon S3 로그 전달 시스템(URI로 지정)에 부여하려는 경우에도 `put-bucket-acl` 명령이 필요합니다.

```
$ aws s3api put-bucket-acl --bucket amzn-s3-demo-bucket --grant-read-acp 'URI="http://acs.amazonaws.com/groups/s3/LogDelivery"' --grant-write 'URI="http://acs.amazonaws.com/groups/s3/LogDelivery"'
$ aws s3api put-bucket-logging --bucket amzn-s3-demo-bucket --bucket-logging-status file://logging.json
```

이전 명령의 `logging.json` 파일에도 다음 내용이 있습니다.

```
{
  "LoggingEnabled": {
    "TargetBucket": "amzn-s3-demo-bucket",
    "TargetPrefix": "amzn-s3-demo-bucketLogs/",
    "TargetGrants": [
      {
        "Grantee": {
          "Type": "AmazonCustomerByEmail",
          "EmailAddress": "user@example.com"
        },
        "Permission": "FULL_CONTROL"
      },
      {
        "Grantee": {
          "Type": "Group",
          "URI": "http://acs.amazonaws.com/groups/global/AllUsers"
        },
        "Permission": "READ"
      }
    ]
  }
}
```

## 리소스
<a name="cli-services-s3-apicommands-resources"></a>

**AWS CLI 참조:** 
+ [https://docs.aws.amazon.com/cli/latest/reference/s3api/index.html](https://docs.aws.amazon.com/cli/latest/reference/s3api/index.html)
+ [https://docs.aws.amazon.com/cli/latest/reference/s3api/put-bucket-acl.html](https://docs.aws.amazon.com/cli/latest/reference/s3api/put-bucket-acl.html)
+ [https://docs.aws.amazon.com/cli/latest/reference/s3api/put-bucket-logging.html](https://docs.aws.amazon.com/cli/latest/reference/s3api/put-bucket-logging.html)

**서비스 참조:**
+ **Amazon S3 사용 설명서의 [Amazon S3 버킷 작업](https://docs.aws.amazon.com//AmazonS3/latest/userguide/UsingBucket.html)
+ **Amazon S3 사용 설명서의 [Amazon S3 버킷 작업](https://docs.aws.amazon.com//AmazonS3/latest/userguide/UsingObjects.html)
+ **Amazon S3 사용 설명서의 [접두사 및 구분 기호를 사용하여 계층적 구조로 키 나열](https://docs.aws.amazon.com//AmazonS3/latest/userguide/ListingKeysHierarchy.html)
+ **Amazon S3 사용 설명서의 [AWS SDK for .NET(낮은 수준)를 사용하여 S3 버킷에 대한 멀티파트 업로드 중단](https://docs.aws.amazon.com//AmazonS3/latest/userguide/LLAbortMPUnet.html)

# AWS CLI의 Amazon S3 버킷 수명 주기에 대한 스크립팅 예제
<a name="cli-services-s3-lifecycle-example"></a>

이 주제에서는AWS Command Line Interface(AWS CLI)를 사용하는 Amazon S3 버킷 수명 주기 작업에 대한 bash 스크립팅 예제를 사용합니다. 이 스크립팅 예제에서는 [https://docs.aws.amazon.com/cli/latest/reference/s3api/index.html](https://docs.aws.amazon.com/cli/latest/reference/s3api/index.html) 명령 세트를 사용합니다. 셸 스크립트는 명령줄 인터페이스에서 실행되도록 설계된 프로그램입니다.

**Topics**
+ [시작하기 전에](#cli-services-s3-lifecycle-example-before)
+ [이 예제 정보](#cli-services-s3-lifecycle-example-about)
+ [파일](#cli-services-s3-lifecycle-example-files)
+ [참조](#cli-services-s3-lifecycle-example-references)

## 시작하기 전에
<a name="cli-services-s3-lifecycle-example-before"></a>

아래 예제 중 하나를 실행하려면 먼저 다음 작업을 완료해야 합니다.
+ AWS CLI를 설치하고 구성합니다. 자세한 내용은 [최신 버전의 AWS CLI 설치 또는 업데이트](getting-started-install.md) 및 [AWS CLI에 대한 인증 및 액세스 보안 인증](cli-chap-authentication.md) 섹션을 참조하세요.
+ 사용하는 프로파일에는 예제에서 수행하는 AWS 작업을 허용하는 권한이 있어야 합니다.
+ AWS 모범 사례로서 이 코드에 최소 권한을 부여하거나 태스크를 수행하는 데 필요한 권한만 부여하세요. 자세한 내용은 *IAM 사용 설명서*에서 [최소 권한 부여](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege)를 참조하세요.
+ 이 코드는 일부 AWS 리전에서 테스트되지 않았습니다. 일부 AWS 서비스는 특정 리전에서만 사용할 수 있습니다. 자세한 내용은 *AWS 일반 참조 안내서*에서 [서비스 엔드포인트 및 할당량](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html)을 참조하세요.
+ 이 코드를 실행하면 AWS 계정에 요금이 발생할 수 있습니다. 이 스크립트에 의해 생성된 모든 리소스를 사용한 후 제거하는 것은 사용자의 책임입니다.

Amazon S3 서비스에는 다음 용어가 사용됩니다.
+ 버킷 - 최상위 수준의 Amazon S3 폴더입니다.
+ 접두사 - 버킷의 Amazon S3 폴더입니다.
+ 객체 - Amazon S3 버킷에서 호스팅되는 모든 항목입니다.

## 이 예제 정보
<a name="cli-services-s3-lifecycle-example-about"></a>

이 예제는 셸 스크립트 파일의 함수 세트를 사용하여 일부 기본 Amazon S3 작업과 상호 작용하는 방법을 보여줍니다. 함수는 `bucket-operations.sh`라는 셸 스크립트 파일에 있습니다. 다른 파일에서 이러한 함수를 호출할 수 있습니다. 각 스크립트 파일에는 각 함수를 설명하는 주석이 들어 있습니다.

각 단계의 중간 결과를 보려면 `-i` 파라미터와 함께 스크립트를 실행합니다. Amazon S3 콘솔을 사용하여 버킷의 현재 상태 또는 버킷의 내용을 볼 수 있습니다. 스크립트는 프롬프트에서 **Enter** 키를 누르는 경우에만 다음 단계로 진행됩니다.

전체 예제 및 다운로드 가능한 스크립트 파일은 *GitHub*에서 *AWS 코드 예제 리포지토리*의 [Amazon S3 버킷 수명 주기 작업](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/s3/bucket-lifecycle-operations)을 참조하세요.

## 파일
<a name="cli-services-s3-lifecycle-example-files"></a>

에제에는 다음 파일이 들어 있습니다.

**bucket-operations.sh**  
이 기본 스크립트 파일은 다른 파일에서 가져올 수 있습니다. 여기에는 다음 작업을 수행하는 함수가 포함됩니다.  
+ 버킷 생성 및 버킷이 존재하는지 확인
+ 로컬 컴퓨터에서 버킷으로 파일 복사
+ 한 버킷 위치에서 다른 버킷 위치로 파일 복사
+ 버킷의 내용 나열
+ 버킷에서 파일 삭제
+ 버킷 삭제
*GitHub*에서 `[bucket-operations.sh](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/aws-cli/bash-linux/s3/bucket-lifecycle-operations/bucket_operations.sh)`에 대한 코드를 확인하세요.

**test-bucket-operations.sh**  
셸 스크립트 파일 `test-bucket-operations.sh`는 `bucket-operations.sh` 파일을 소싱하고 각 함수를 호출하여 함수를 호출하는 방법을 보여줍니다. 함수를 호출한 후 테스트 스크립트는 생성한 모든 리소스를 제거합니다.  
*GitHub*에서 `[test-bucket-operations.sh](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/aws-cli/bash-linux/s3/bucket-lifecycle-operations/test_bucket_operations.sh)`에 대한 코드를 확인하세요.

**awsdocs-general.sh**  
스크립트 파일 `awsdocs-general.sh`에는 AWS CLI에 대한 고급 코드 예제에서 사용되는 범용 함수가 들어 있습니다.  
*GitHub*에서 `[awsdocs-general.sh](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/aws-cli/bash-linux/s3/bucket-lifecycle-operations/awsdocs_general.sh)`에 대한 코드를 확인하세요.

## 참조
<a name="cli-services-s3-lifecycle-example-references"></a>

**AWS CLI 참조:** 
+ [https://docs.aws.amazon.com/cli/latest/reference/s3api/index.html](https://docs.aws.amazon.com/cli/latest/reference/s3api/index.html)
+ [https://docs.aws.amazon.com/cli/latest/reference/s3api/create-bucket.html](https://docs.aws.amazon.com/cli/latest/reference/s3api/create-bucket.html)
+ [https://docs.aws.amazon.com/cli/latest/reference/s3api/copy-object.html](https://docs.aws.amazon.com/cli/latest/reference/s3api/copy-object.html)
+ [https://docs.aws.amazon.com/cli/latest/reference/s3api/delete-bucket.html](https://docs.aws.amazon.com/cli/latest/reference/s3api/delete-bucket.html)
+ [https://docs.aws.amazon.com/cli/latest/reference/s3api/delete-object.html](https://docs.aws.amazon.com/cli/latest/reference/s3api/delete-object.html)
+ [https://docs.aws.amazon.com/cli/latest/reference/s3api/head-bucket.html](https://docs.aws.amazon.com/cli/latest/reference/s3api/head-bucket.html)
+ [https://docs.aws.amazon.com/cli/latest/reference/s3api/list-objects.html](https://docs.aws.amazon.com/cli/latest/reference/s3api/list-objects.html)
+ [https://docs.aws.amazon.com/cli/latest/reference/s3api/put-object.html](https://docs.aws.amazon.com/cli/latest/reference/s3api/put-object.html)

**기타 참조:**
+ **Amazon S3 사용 설명서의 [Amazon S3 버킷 작업](https://docs.aws.amazon.com//AmazonS3/latest/userguide/UsingBucket.html)
+ **Amazon S3 사용 설명서의 [Amazon S3 버킷 작업](https://docs.aws.amazon.com//AmazonS3/latest/userguide/UsingObjects.html)
+ AWS SDK 및 AWS CLI 코드 예제를 보고 기여하려면 *GitHub*에서 [AWS 코드 예제 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/)를 참조하세요.

# AWS CLI에서 Amazon SNS 액세스
<a name="cli-services-sns"></a>

AWS Command Line Interface(AWS CLI)를 사용하여 Amazon Simple Notification Service(Amazon SNS)의 기능에 액세스할 수 있습니다. Amazon SNS에 대한 AWS CLI 명령을 나열하려면 다음 명령을 사용합니다.

```
aws sns help
```

명령을 실행하기 전에 기본 자격 증명을 설정합니다. 자세한 내용은 [AWS CLI 설정 구성](cli-chap-configure.md) 단원을 참조하세요.

이 주제에서는 Amazon SNS에 대한 일반적인 태스크를 수행하는 AWS CLI 명령의 예제를 보여줍니다.

**Topics**
+ [주제 생성](#cli-create-sns-topic)
+ [주제 구독](#cli-subscribe-sns-topic)
+ [주제 게시](#cli-publish-sns-topic)
+ [주제에서 구독 취소](#cli-unsubscribe-sns-topic)
+ [주제 삭제](#cli-delete-sns-topic)

## 주제 생성
<a name="cli-create-sns-topic"></a>

주제를 만들려면 [https://docs.aws.amazon.com/cli/latest/reference/sns/create-topic.html](https://docs.aws.amazon.com/cli/latest/reference/sns/create-topic.html) 명령을 사용하고 주제에 할당할 이름을 지정합니다.

```
$ aws sns create-topic --name my-topic
{
    "TopicArn": "arn:aws:sns:us-west-2:123456789012:my-topic"
}
```

나중에 메시지를 게시할 때 사용할 응답의 `TopicArn`을 적어 둡니다.

## 주제 구독
<a name="cli-subscribe-sns-topic"></a>

주제를 구독하려면 [https://docs.aws.amazon.com/cli/latest/reference/sns/subscribe.html](https://docs.aws.amazon.com/cli/latest/reference/sns/subscribe.html) 명령을 사용합니다.

다음 예제는 `email`에 대한 이메일 주소와 `notification-endpoint` 프로토콜을 지정합니다.

```
$ aws sns subscribe --topic-arn arn:aws:sns:us-west-2:123456789012:my-topic --protocol email --notification-endpoint saanvi@example.com
{
    "SubscriptionArn": "pending confirmation"
}
```

AWS는 `subscribe` 명령으로 지정한 이메일 주소로 즉시 확인 메시지를 보냅니다. 이메일 메시지에는 다음 텍스트가 포함됩니다.

```
You have chosen to subscribe to the topic:
arn:aws:sns:us-west-2:123456789012:my-topic
To confirm this subscription, click or visit the following link (If this was in error no action is necessary):
Confirm subscription
```

수신자가 **구독 확인** 링크를 클릭하면 수신자의 브라우저에 다음과 유사한 정보가 포함된 알림 메시지가 표시됩니다.

```
Subscription confirmed!

You have subscribed saanvi@example.com to the topic:my-topic.

Your subscription's id is:
arn:aws:sns:us-west-2:123456789012:my-topic:1328f057-de93-4c15-512e-8bb22EXAMPLE

If it was not your intention to subscribe, click here to unsubscribe.
```

## 주제 게시
<a name="cli-publish-sns-topic"></a>

주제의 모든 구독자에게 메시지를 보내려면 [https://docs.aws.amazon.com/cli/latest/reference/sns/publish.html](https://docs.aws.amazon.com/cli/latest/reference/sns/publish.html) 명령을 사용합니다.

다음 예제에서는 지정된 주제의 모든 가입자에게 'Hello World\$1'라는 메시지를 보냅니다.

```
$ aws sns publish --topic-arn arn:aws:sns:us-west-2:123456789012:my-topic --message "Hello World!"
{
    "MessageId": "4e41661d-5eec-5ddf-8dab-2c867EXAMPLE"
}
```

이 예에서 AWS는 'Hello World\$1' 텍스트가 포함된 이메일 메시지를 `saanvi@example.com`으로 전송합니다.

## 주제에서 구독 취소
<a name="cli-unsubscribe-sns-topic"></a>

주제 구독을 해지하고 해당 주제로 게시된 메시지 수신을 중단하려면 [https://docs.aws.amazon.com/cli/latest/reference/sns/unsubscribe.html](https://docs.aws.amazon.com/cli/latest/reference/sns/unsubscribe.html) 명령을 사용하고 구독을 해지할 주제의 ARN을 지정합니다.

```
$ aws sns unsubscribe --subscription-arn arn:aws:sns:us-west-2:123456789012:my-topic:1328f057-de93-4c15-512e-8bb22EXAMPLE
```

구독이 성공적으로 해지되었는지 확인하려면 [https://docs.aws.amazon.com/cli/latest/reference/sns/list-subscriptions.html](https://docs.aws.amazon.com/cli/latest/reference/sns/list-subscriptions.html) 명령을 사용하여 해당 ARN이 목록에 더 이상 나타나지 않는지 확인합니다.

```
$ aws sns list-subscriptions
```

## 주제 삭제
<a name="cli-delete-sns-topic"></a>

주제를 삭제하려면 [https://docs.aws.amazon.com/cli/latest/reference/sns/delete-topic.html](https://docs.aws.amazon.com/cli/latest/reference/sns/delete-topic.html) 명령을 실행합니다.

```
$ aws sns delete-topic --topic-arn arn:aws:sns:us-west-2:123456789012:my-topic
```

AWS가 주제를 성공적으로 삭제했는지 확인하려면 [https://docs.aws.amazon.com/cli/latest/reference/sns/list-topics.html](https://docs.aws.amazon.com/cli/latest/reference/sns/list-topics.html) 명령을 사용하여 해당 주제가 목록에 더 이상 나타나지 않는지 확인합니다.

```
$ aws sns list-topics
```