

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

# AWS CLI 的引導式命令範例
<a name="cli-chap-services"></a>

AWS Command Line Interface (AWS CLI) 是開放原始碼工具，可讓您在命令列 Shell 中使用命令來與各種 AWS 服務 互動。本節提供引導式範例，示範如何利用 AWS CLI 來存取部分的 AWS 服務。這包括一些自訂 AWS CLI 命令，例如高階 `aws s3` 命令。這些命令範例示範用於某些 AWS 服務 的常見動作，並提供其他資源以取得詳細資訊。

無論您是經驗豐富的 AWS 使用者，還是 AWS CLI 的新手，這些引導式範例都可做為簡化 AWS 操作的資源。

如需各個 AWS 服務 所有可用命令的完整參考，請參閱 [AWS CLI 第 2 版參考指南](https://docs.aws.amazon.com/cli/latest/reference/index.html)。此外，您可以使用[內建命令列說明](cli-usage-help.md)來探索 AWS CLI 中的 AWS 服務、命令、選項和功能陣列。

如需更多本節中未提供的命令範例，請參閱 [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 指令碼範例，請參閱 [AWS CLI 搭配 Bash 指令碼程式碼範例](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) 提供對所有 AWS 資料庫服務 (包括 Amazon DynamoDB) 的支援。您可以將 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 檔案。例如，請試想下列 JSON 程式碼片段，其存放在名為 `expression-attributes.json` 的檔案中。

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

您可以使用該檔案來使用 AWS CLI 發出 `query` 請求。在下列範例中，`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 API 的應用程式，無須處理 DynamoDB Web 服務中的任何表格與資料。所有 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 開發人員指南》中的[搭配 DynamoDB Local 使用 AWS CLI](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**
+ [在 中建立、顯示和刪除 Amazon EC2 金鑰對 AWS CLI](cli-services-ec2-keypairs.md)
+ [在 中建立、設定和刪除 Amazon EC2 安全群組 AWS CLI](cli-services-ec2-sg.md)
+ [在 中啟動、列出和刪除 Amazon EC2 執行個體 AWS CLI](cli-services-ec2-instances.md)
+ [在 中使用 bash 指令碼變更 Amazon EC2 執行個體類型 AWS CLI](cli-services-ec2-instance-type-script.md)

# 在 中建立、顯示和刪除 Amazon EC2 金鑰對 AWS CLI
<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)。
+ 設定 IAM 許可，以允許 Amazon EC2 存取。如需有關 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>

若要刪除金鑰對，請執行 `[aws ec2 delete-key-pair](https://docs.aws.amazon.com/cli/latest/reference/ec2/delete-key-pair.html)` 命令，以您要刪除的金鑰對名稱來取代 *`MyKeyPair`*。

```
$ 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/)。

# 在 中建立、設定和刪除 Amazon EC2 安全群組 AWS CLI
<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)。
+ 設定 IAM 許可，以允許 Amazon EC2 存取。如需有關 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>

您可以建立與虛擬私有雲端 (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)` 命令。您只能依 `vpc-id` 參考 EC2-VPC 安全群組，不能使用其名稱。

```
$ 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 執行個體，則通常需新增規則以允許 TCP 連接埠 3389 上的對內流量來支援遠端桌面通訊協定 (RDP)。如果您正在啟動 Linux 執行個體，則通常必須新增規則以允許 TCP 連接埠 22 上的對內流量來支援 SSH 連線。

使用 `[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：//[https://checkip.global.api.aws/](https://checkip.global.api.aws/)。若要尋找可協助您識別 IP 地址的其他服務，請使用瀏覽器來搜尋「*我的 IP 地址是什麼*」。如果您透過 ISP 或從防火牆後方使用動態 IP 地址來連線 (透過私有網路的 NAT 閘道)，則您的地址可能會定期變更。在這種情況下，您必須找出用戶端電腦所用 IP 地址的範圍。

以下範例顯示如何新增 RDP 的規則 (TCP 連接埠 3389) 到使用您的 IP 地址、ID 為 `sg-903004f8` 的 EC2-VPC 安全群組。

若要開始，請找出 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/)。

# 在 中啟動、列出和刪除 Amazon EC2 執行個體 AWS CLI
<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)。
+ 設定 IAM 許可，以允許 Amazon EC2 存取。如需有關 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。如需詳細資訊，請參閱《Amazon EC2 使用者指南》**中的[尋找合適的 AMI](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/finding-an-ami.html)。

## 啟動您的執行個體
<a name="launching-instances"></a>

若要使用所選的 AMI 來啟動 Amazon EC2 執行個體，請使用 `[aws ec2 run-instances](https://docs.aws.amazon.com/cli/latest/reference/ec2/run-instances.html)` 命令。您可於虛擬私有雲端 (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) 磁碟區或執行個體存放磁碟區。

若要新增區塊型儲存設備至執行個體，請在使用 `run-instances` 時指定 `--block-device-mappings` 選項。

以下範例參數佈建 20 GB 大小的標準 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 使用者指南》**中的[連線至您的執行個體](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 啟動的執行個體：`ami-x0123456`、`ami-y0123456` 和 `ami-z0123456`。

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

## 刪除您的執行個體
<a name="terminating-instances"></a>

當您不再需要 Amazon EC2 執行個體時，您可以使用 AWS CLI 來終止 （刪除） 該執行個體。

**重要**  
**終止執行個體的操作為永久性且無法復原。**  
終止執行個體後，您將無法再連線至該執行個體，且無法復原該執行個體。所有設定為終止時刪除的已連接 Amazon EBS 磁碟區，也會被永久刪除且無法復原。儲存在執行個體儲存體磁碟區的所有資料將永久遺失。如需詳細資訊，請參閱[執行個體終止的運作方式](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/how-ec2-instance-termination-works.html)。  
在終止執行個體之前，確認您已將終止使用後需要保留的全部資料備份至持久性儲存體。

執行個體的狀態變更為 `shutting-down` 或 `terminated` 時刻起，該執行個體便停止收取費用。如果您希望稍後重新連接執行個體，請使用 [stop-instances](https://docs.aws.amazon.com/cli/v1/reference/ec2/stop-instances.html) 而不是 `terminate-instances`。如需詳細資訊，請參閱*《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/)。

# 在 中使用 bash 指令碼變更 Amazon EC2 執行個體類型 AWS CLI
<a name="cli-services-ec2-instance-type-script"></a>

此 Amazon EC2 的 bash 指令碼範例會使用 AWS Command Line Interface () 變更 Amazon EC2 執行個體的執行個體類型AWS CLI。如果執行個體正在執行，它會停止執行個體，變更執行個體類型，然後在要求時重新啟動執行個體。Shell 指令碼是專為在命令列界面中執行而設計的程式。

**注意**  
如需其他命令範例，請參閱[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)
+ [Parameters](#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>

這個範例被寫成 Shell 指令碼檔案 `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)。

## Parameters
<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/)。

# 在 中使用 Amazon Glacier AWS CLI
<a name="cli-services-glacier"></a>


| Amazon Glacier 簡介 | 
| --- | 
|    | 

本主題顯示執行 Amazon Glacier 常見任務的 AWS CLI 命令範例。這些範例示範如何使用 AWS CLI 將大型檔案分割成較小的部分，並從命令列上傳，以將大型檔案上傳至 Amazon Glacier。

您可以使用 AWS Command Line Interface () 存取 Amazon Glacier 功能AWS CLI。若要列出 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)
+ [Resources](#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)。
+ 本教學課程使用數個命令列工具，通常預先安裝在類 Unix 的操作系統上，包括 Linux 和 macOS。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>

為測試上載建立一個檔案。以下命令將建立名為 *largefile* 的檔案，其中包含 3 MiB 的隨機數據。

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

接下來，使用檔案分割器將檔案分成 1 MiB (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 需要以位元組為單位的每個部分大小 （此範例中為 1 MiB)、您的保存庫名稱，以及帳戶 ID 來設定分段上傳。操作完成時， 會 AWS CLI 輸出上傳 ID。將上傳 ID 儲存到 Shell 變數以供稍後使用。

**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` Shell 變數內容。在 Windows 命令列，請在變數名稱 (例如 `%UPLOADID%`) 任一側使用百分比符號 (%)。

您必須在上傳時指定每個部分的位元組範圍，以便 Amazon Glacier 可以正確順序重新組合。每一部分是 1048576 bytes，所以第一部分的位元組是 0-1048575，第二部分是 1048576-2097151，第三部分是 2097152-3145727。

## 完成上傳
<a name="cli-services-glacier-complete"></a>

Amazon Glacier 需要原始檔案的樹雜湊，以確認所有上傳的片段都完 AWS 好無損。

若要計算樹雜湊值，您必須將檔案拆分為 1 MiB 部分，並計算每個部分的二進位 SHA-256 雜湊值。然後，將雜湊值清單分為幾對，在每一對中合併兩個二進位雜湊值，並取結果的雜湊值。重複此過程，直到只剩下一個雜湊值。如果在任何階層都有奇數的雜湊值，則將其推進到下一階層而不進行修改。

使用命令列公用程式正確計算樹雜湊函數的關鍵是將每個雜湊值儲存為二進位格式，並且只在最後一步轉換為十六進位。組合或雜湊樹中任何雜湊的十六進位版本將導致錯誤的結果。

**注意**  
Windows 使用者可以使用 `type` 命令代替`cat`。位於 [OpenSSL.org](https://www.openssl.org/source/)的 OpenSSL 適用於 Windows。

**計算樹雜湊函數**

1. 如果尚未這麼做，請將原始檔案拆分為 1 MiB 部分。

   ```
   $ 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. 合併前兩個雜湊，並取結果的二進位雜湊值。

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

1. 以與區塊 `ac` 的雜湊值和雜湊結果將區塊 `aa` 和 `ab` 的父系雜湊值作結合，此時會輸出十六進位。將結果存放在 Shell 變數中。

   ```
   $ 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)` 命令完成上傳。此命令採用原始檔案的大小 (以位元組為單位)、最終的樹雜湊值 (十六進位) 以及您的帳戶 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](https://docs.aws.amazon.com/amazonglacier/latest/dev/checksum-calculations.html)

## Resources
<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 管理主控台 或以程式設計方式透過 AWS SDK、工具和 AWS CLI 加以存取和管理。

Amazon S3 包含基本儲存空間，也提供各種功能，包括生命週期管理、版本控制、可擴展性和安全性。這些功能與其他 AWS 服務 整合，讓您能夠建置雲端型解決方案來擴展您的需求。

AWS CLI 為存取 Amazon S3 提供了兩個層級的命令：
+ **s3** – 針對 AWS CLI 特別製作的自訂高階命令，可簡化執行常見任務，例如建立、操作、刪除和同步物件與儲存貯體。
+ **s3api**— 公開對所有 Amazon S3 API 操作的直接存取，使您能夠執行進階操作。

**Topics**
+ [在 中使用高階 (s3) 命令 AWS CLI](cli-services-s3-commands.md)
+ [在 中使用 API 層級 (s3api) 命令 AWS CLI](cli-services-s3-apicommands.md)
+ [中的 Amazon S3 儲存貯體生命週期指令碼範例 AWS CLI](cli-services-s3-lifecycle-example.md)

# 在 中使用高階 (s3) 命令 AWS CLI
<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)
+ [Resources](#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`命名空間中的第 2 `content-disposition` AWS CLI 版命令會將所有標籤和下列屬性集從來源傳輸到目的地複本：`content-type`、`content-language`、`content-encoding`、`cache-control`、`expires`、 和 `metadata`。

如果您使用第 1 AWS CLI 版，這可能會導致對 Amazon S3 端點進行額外的 AWS API 呼叫。這些可能包括：`HeadObject`、`GetObjectTagging`、和 `PutObjectTagging`。

如果您需要變更第 2 AWS CLI 版命令中的此預設行為，請使用 `--copy-props` 參數指定下列其中一個選項：
+ **預設** – 預設值。指定副本包括連接至來源物件的所有標籤，以及用於非多段副本的 `--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>

下列範例刪除來自 `s3://amzn-s3-demo-bucket/example` 的 `filename.txt`。

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

以下範例使用 `--recursive` 選項刪除所有來自 `s3://amzn-s3-demo-bucket/example` 的物件。

```
$ 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`)。

**警告**  
如果您使用的是 PowerShell，Shell 可能會改變 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` 會更新任何與目的地檔案具有相同名字，但是檔案大小或修改時間不同的檔案。輸出顯示在同步期間所執行的特定操作。請注意，操作會使用 `s3://amzn-s3-demo-bucket/path/MySubdirectory` 遞迴同步處理子目錄 `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
```

**排除**  
在使用 `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
```

**無覆寫**  
`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
```

## Resources
<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 使用者指南》中的 適用於 .NET 的 AWS SDK （低階） 中止分段上傳至 S3 儲存貯](https://docs.aws.amazon.com//AmazonS3/latest/userguide/LLAbortMPUnet.html)體 *Amazon S3 *

# 在 中使用 API 層級 (s3api) 命令 AWS CLI
<a name="cli-services-s3-apicommands"></a>

API 層級命令 (包含在 `s3api` 命令集中) 提供對 Amazon Simple Storage Service (Amazon S3) API 的直接存取，並啟用在高階 `s3` 命令中未公開的部分操作。這些命令等同於對服務功能提供 API 層級存取的其他 AWS 服務。如需這些 `s3` 命令的詳細資訊，請參閱 [在 中使用高階 (s3) 命令 AWS CLI](cli-services-s3-commands.md)

本主題提供範例，示範如何使用映射到 Amazon S3 API 的較低層級命令。此外，您可以在第 [AWS CLI 2 版參考指南](https://docs.aws.amazon.com/cli/latest/reference/s3api/index.html)的 `s3api`區段中找到每個 S3 API 命令的範例。

**Topics**
+ [先決條件](#cli-services-s3-apicommands-prereqs)
+ [套用自訂 ACL](#cli-services-s3-apicommands-acls)
+ [設定記錄政策](#cli-services-s3-apicommands-logpol)
+ [Resources](#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*)，以及授予每個人讀取許可。「everyone」的識別符來自您當做參數傳遞的特殊 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 儲存貯體 acl](https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTacl.html)。CLI 中的 `s3api` ACL 命令 (如 `put-bucket-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"
      }
    ]
  }
}
```

## Resources
<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 使用者指南》中的 適用於 .NET 的 AWS SDK （低階） 中止分段上傳至 S3 儲存貯](https://docs.aws.amazon.com//AmazonS3/latest/userguide/LLAbortMPUnet.html)體 *Amazon S3 *

# 中的 Amazon S3 儲存貯體生命週期指令碼範例 AWS CLI
<a name="cli-services-s3-lifecycle-example"></a>

本主題使用 Bash 指令碼範例來說明使用 AWS Command Line Interface (AWS CLI) 的 Amazon S3 儲存貯體生命週期操作。此指令碼範例會使用 [https://docs.aws.amazon.com/cli/latest/reference/s3api/index.html](https://docs.aws.amazon.com/cli/latest/reference/s3api/index.html) 命令組。Shell 指令碼是專為在命令列界面中執行而設計的程式。

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

此範例示範如何使用 Shell 指令碼檔案中的一組函數與某些基本 Amazon S3 操作互動。這些函數位於名為 `bucket-operations.sh` 的 Shell 指令碼檔案中。您可以在另一個檔案中呼叫這些函數。每個指令碼檔案包含描述每個函數的註釋。

若要查看每個步驟的中繼結果，請執行具有 `-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**  
Shell 指令碼檔案 `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
```

收件人按一下 **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
```