

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

# 使用 AWS CLI
<a name="cli-chap-using"></a>

本節提供 AWS Command Line Interface (AWS CLI) 中一般使用、常見功能和選項的完整概觀，但「組態 [在 中使用端點 AWS CLI](cli-configure-endpoints.md)」一節中涵蓋的詳細資訊除外。

本指南深入探討撰寫 AWS CLI 命令的基本層面，包括其基本結構、格式化和篩選功能。透過了解這些核心元素，您便能夠建構可精確鎖定所需資源和動作的命令，而不需要導覽複雜的 Web 型主控台。

此外，這會反白顯示 AWS CLI 可用的說明內容和文件。從內建的命令列說明，到完整的 [AWS CLI 第 2 版參考指南](https://docs.aws.amazon.com/cli/latest/reference/)，您可以存取資訊來協助您探索 AWS CLI 的功能。

如需 AWS 服務 特定的範例和使用案例，請參閱 [AWS CLI 的範例](cli-chap-code-examples.md) 或 [AWS CLI 第2 版參考指南](https://docs.aws.amazon.com/cli/latest/reference/)。這些指南會提供命令特定資訊，並示範如何將 AWS CLI 用於各種 AWS 服務 的範例。

**注意**  
預設情況下，AWS CLI 會透過在 TCP 連接埠 443 上使用 HTTPS，將請求傳送至 AWS 服務。若要確保成功使用 AWS CLI，您必須能夠在此連接埠上進行傳出連線。

**Topics**
+ [存取 的說明和資源 AWS CLI](cli-usage-help.md)
+ [AWS CLI 中的命令結構](cli-usage-commandstructure.md)
+ [在 AWS CLI 中指定參數值](cli-usage-parameters.md)
+ [在 中啟用和使用命令提示字元 AWS CLI](cli-usage-parameters-prompting.md)
+ [在 中控制命令輸出 AWS CLI](cli-usage-output.md)
+ [AWS CLI 中的命令列傳回碼](cli-usage-returncodes.md)
+ [使用自訂精靈在 中執行互動式命令 AWS CLI](cli-usage-wizard.md)
+ [在 中建立和使用別名 AWS CLI](cli-usage-alias.md)
+ [故障診斷 的錯誤 AWS CLI](cli-chap-troubleshooting.md)

# 存取 的說明和資源 AWS CLI
<a name="cli-usage-help"></a>

本主題說明如何存取 AWS Command Line Interface () 的說明內容AWS CLI。

**Topics**
+ [內建 AWS CLI 的 help 命令](#cli-usage-help-command)
+ [AWS CLI 參考指南](#cli-reference)
+ [API 文件](#api-reference)
+ [故障診斷錯誤](#help-tshoot)
+ [其他協助](#help-additional)

## 內建 AWS CLI 的 help 命令
<a name="cli-usage-help-command"></a>

使用 AWS Command Line Interface () 時，您可以取得任何命令的說明AWS CLI。若要這樣做，只需在命令名稱結尾輸入 `help`。

例如，下列命令會顯示一般 AWS CLI 選項和可用頂層命令的說明。

```
$ aws help
```

以下命令會顯示可用的 Amazon Elastic Compute Cloud (Amazon EC2) 特定命令。

```
$ aws ec2 help
```

以下範例會顯示 Amazon EC2 `DescribeInstances` 操作的詳細說明。說明包括輸入參數的描述、可用的篩選條件以及輸出包含的內容。此外也包含範例，顯示如何輸入命令的常見變化。

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

自版本 `2.31.0` 起，`help` 命令的顯示由 `cli_help_output` 設定來設定，並具有下列值：
+  **(預設)** `terminal` ‐ 在終端中開啟 man 頁面。
+ `browser` ‐ 在預設瀏覽器中將 man 頁面開啟為本機 HTML 檔案。開啟預設瀏覽器時，通知會列印到您的終端機，如果 AWS CLI 無法開啟您的瀏覽器，則會顯示錯誤訊息。
+ `url` ‐ 針對 AWS CLI 您已安裝的 版本，將 URL 列印至線上 AWS CLI 參考指南。遵守用戶端分頁的設定，例如`AWS_PAGER`環境變數。

各個命令的說明內容均分為六個區段：

名稱  
命令的名稱。  

```
NAME
       describe-instances -
```

Description  
命令叫用之 API 操作的描述。  

```
DESCRIPTION
       Describes one or more of your instances.

       If you specify one or more instance IDs, Amazon EC2 returns information
       for those instances. If you do not specify  instance  IDs,  Amazon  EC2
       returns  information  for  all  relevant  instances.  If you specify an
       instance ID that is not valid, an error is returned. If you specify  an
       instance  that  you  do  not  own,  it  is not included in the returned
       results.
...
```

概要  
使用命令和其選項的基本語法。如果有選項顯示在方括號內，代表為選用、具有預設值，或是具有可使用的替代選項。  

```
SYNOPSIS
            describe-instances
          [--dry-run | --no-dry-run]
          [--instance-ids <value>]
          [--filters <value>]
          [--cli-input-json <value>]
          [--starting-token <value>]
          [--page-size <value>]
          [--max-items <value>]
          [--generate-cli-skeleton]
```
例如， `describe-instances` 具有預設行為，可描述目前帳戶和 AWS 區域中***的所有***執行個體。您可選擇指定 `dry-run` 清單來描述一個或多個執行個體。`instance-ids` 是一個選用的布林值旗標，其不採用數值。若要使用布林值旗標，請指定顯示數值，在此範例中為 `--dry-run` 或 `--no-dry-run`。同樣地，`--generate-cli-skeleton` 不採用數值。如果選項的使用具有條件，則這些條件會在 `OPTIONS` 區段中說明，或顯示在範例中。

選項  
概要中顯示之各個選項的說明。  

```
OPTIONS
       --dry-run | --no-dry-run (boolean)
          Checks whether you have the required  permissions  for  the  action,
          without actually making the request, and provides an error response.
          If you have the required permissions, the error response is  DryRun-
          Operation . Otherwise, it is UnauthorizedOperation .

       --instance-ids (list)
          One or more instance IDs.

          Default: Describes all your instances.
...
```

範例  
命令使用及其選項的範例。如果沒有範例適用於您需要的命令或使用案例，請使用此頁面上的意見回饋連結請求，或在 AWS CLI 命令說明頁面上的命令參考中請求。  

```
    EXAMPLES
    To describe an Amazon EC2 instance

    Command:
    
    aws ec2 describe-instances --instance-ids i-5203422c
    
    To describe all instances with the instance type m1.small
    
    Command:
    
    aws ec2 describe-instances --filters "Name=instance-type,Values=m1.small"
    
    To describe all instances with an Owner tag
    
    Command:
    
    aws ec2 describe-instances --filters "Name=tag-key,Values=Owner"
...
```

Output  
來自 AWS的回應中所包含各個欄位與資料類型的說明。  
對於 `describe-instances`，輸出是保留物件的清單，每個清單都包含若干欄位和物件，而這些欄位和物件包含與其關聯之執行個體的資訊。此資訊來自 Amazon EC2 所使用的[保留資料類型的 API 文件](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_Reservation.html)。  

```
OUTPUT
       Reservations -> (list)
          One or more reservations.

          (structure)
              Describes a reservation.

              ReservationId -> (string)
                 The ID of the reservation.

              OwnerId -> (string)
                 The ID of the AWS account that owns the reservation.

              RequesterId -> (string)
                 The ID of the requester that launched the instances  on  your
                 behalf (for example, AWS Management Console or Auto Scaling).

              Groups -> (list)
                 One or more security groups.

                 (structure)
                     Describes a security group.

                     GroupName -> (string)
                        The name of the security group.

                     GroupId -> (string)
                        The ID of the security group.

              Instances -> (list)
                 One or more instances.

                 (structure)
                     Describes an instance.

                     InstanceId -> (string)
                        The ID of the instance.

                     ImageId -> (string)
                        The ID of the AMI used to launch the instance.

                     State -> (structure)
                        The current state of the instance.

                        Code -> (integer)
                            The  low  byte represents the state. The high byte
                            is an opaque internal value and should be ignored.
...
```
當 將輸出 AWS CLI 轉譯為 JSON 時，它會成為保留物件的陣列，類似於下列範例。  

```
{
    "Reservations": [
        {
            "OwnerId": "012345678901",
            "ReservationId": "r-4c58f8a0",
            "Groups": [],
            "RequesterId": "012345678901",
            "Instances": [
                {
                    "Monitoring": {
                        "State": "disabled"
                    },
                    "PublicDnsName": "ec2-52-74-16-12.us-west-2.compute.amazonaws.com",
                    "State": {
                        "Code": 16,
                        "Name": "running"
                    },
...
```
每個保留物件均包含說明該保留的欄位，以及執行個體物件列陣，每個執行個體物件都有提供說明的專屬欄位 (例如 `PublicDnsName`) 和物件 (例如 `State`)。  
**Windows 使用者**  
您可將說明命令的輸出輸送** (\$1) 到 `more` 命令，以便一次檢視一個說明檔案頁面。按下空格鍵或 **PgDn** 鍵檢視更多文件內容，按 **q** 鍵即可退出。  

```
C:\> aws ec2 describe-instances help | more
```

## AWS CLI 參考指南
<a name="cli-reference"></a>

說明檔案包含連結，無法從命令列檢視或瀏覽。您可以使用線上第 第 [AWS CLI 2 版參考指南](https://docs.aws.amazon.com/cli/latest/reference/index.html)，來檢視這些連結並與之互動。參考也包含所有 AWS CLI 命令的說明內容。提供的說明可在行動裝置、平板電腦或桌上型電腦螢幕上輕鬆導覽和檢視。

## API 文件
<a name="api-reference"></a>

中的所有命令 AWS CLI 都會對應至對 AWS 服務的公有 API 提出的請求。每個具備公有 API 的服務均有 API 參考，這些文件可以在 [AWS 文件網站](https://docs.aws.amazon.com/)上該服務的首頁中找到。API 參考的內容根據 API 的建構方式和所用協議而有所差異。一般來說，API 參考包含詳細資訊，說明 API 支援的操作、傳送到服務或從服務傳送的資料，以及服務可能報告的任何錯誤情況。

**API 文件區段**
+  **動作** – 關於每個操作及其參數 (包含長度限制或內容限制以及預設值) 的詳細資訊。它會列出此操作可能發生的錯誤。每個操作都會對應至 中的子命令 AWS CLI。
+  **資料類型** – 結構的詳細資訊，命令可能需要這些結構作為參數，或傳回以回應請求。
+  **常用參數** – 服務的所有動作共用之參數的詳細資訊。
+  **常見錯誤** – 服務的任何操作可能傳回之錯誤的詳細資訊。

每個區段的名稱或可用性，會依據服務而有所差異。

**服務特定的 CLI**  
某些服務具有單獨的 CLI，其日期從建立單一 AWS CLI 之前起算，以使用所有 服務。這些服務特定的 CLI 具有個別專屬的文件，可以從該服務的文件頁面中連結取得。服務特定 CLIs 的文件不適用於 AWS CLI。

## 故障診斷錯誤
<a name="help-tshoot"></a>

如需診斷和修正 AWS CLI 錯誤的說明，請參閱 [故障診斷 的錯誤 AWS CLI](cli-chap-troubleshooting.md)。

## 其他協助
<a name="help-additional"></a>

如需 AWS CLI 問題的其他協助，請造訪 *GitHub* 上的 [AWS CLI 社群](https://github.com/aws/aws-cli/issues)。

# AWS CLI 中的命令結構
<a name="cli-usage-commandstructure"></a>

本主題包括 AWS Command Line Interface (AWS CLI) 命令如何結構化，以及如何使用等待命令。

**Topics**
+ [命令結構](#cli-usage-commandstructure-structure.title)
+ [等候命令](#cli-usage-commandstructure-wait)

## 命令結構
<a name="cli-usage-commandstructure-structure.title"></a>

AWS CLI 在命令列上使用必須依以下順序指定的分段結構：

1. 對 `aws` 程式的基本呼叫。

1. 頂層*命令*，通常對應至 AWS CLI 支援的 AWS 服務。

1. 指定執行哪些操作的*子命令*。

1. 操作所需的一般 AWS CLI 選項或參數。只要位在前三個部分後面，您可以依任意順序指定這些項目。如果排他參數受到多次指定，只會套用*最終數值*。

```
$ aws <command> <subcommand> [options and parameters]
```

參數採用各種類型的輸入數值，例如數字、字串、清單、映射和 JSON 結構。支援哪些項目取決於您指定的命令和子命令。

### 範例
<a name="cli-usage-commandstructure-structure-example"></a>

**Amazon S3**

以下範例列出您的所有 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
```

如需 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 CloudFormation**

以下 [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/create-change-set.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/create-change-set.html) 命令範例會將 cloudformation 堆疊名稱變更為 *my-change-set*。

```
$ aws cloudformation create-change-set --stack-name my-stack --change-set-name my-change-set
```

如需 AWS CloudFormation 命令的詳細資訊，請參閱 *AWS CLI 命令參考*中的 [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/index.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/index.html)。

## 等候命令
<a name="cli-usage-commandstructure-wait"></a>

部分 AWS 服務可使用 `wait` 指令。任何使用 `aws wait` 的命令通常都會等到命令完成後，再進行下一個步驟。這對於分段命令或指令碼特別有用，因為如果等候命令失敗，您可以使用等候命令來避免進行後續步驟。

AWS CLI 會在命令列上使用必須依此順序指定的 `wait` 命令分段結構：

1. 對 `aws` 程式的基本呼叫。

1. 頂層*命令*，通常對應至 AWS CLI 支援的 AWS 服務。

1. `wait` 命令。

1. 指定執行哪些操作的*子命令*。

1. 操作所需的一般 CLI 選項或參數。只要位在前三個部分後面，您可以依任意順序指定這些項目。如果排他參數受到多次指定，只會套用*最終數值*。

```
$ aws <command> wait <subcommand> [options and parameters]
```

參數採用各種類型的輸入數值，例如數字、字串、清單、映射和 JSON 結構。支援哪些項目取決於您指定的命令和子命令。

**注意**  
並非所有 AWS 服務都支援 `wait` 命令。請參閱 [AWS CLI 第 2 版參考指南](https://docs.aws.amazon.com/cli/latest/reference/index.html)，了解您的服務是否支援 `wait` 命令。

### 範例
<a name="cli-usage-commandstructure-wait-example"></a>

**AWS CloudFormation**

以下 [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/wait/change-set-create-complete.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/wait/change-set-create-complete.html) 命令範例會暫停，且僅在可確認 *my-stack* 堆疊中的 *my-change-set* 變更集已準備好執行後，才會繼續執行。

```
$ aws cloudformation wait change-set-create-complete --stack-name my-stack --change-set-name my-change-set
```

如需 AWS CloudFormation `wait` 命令的詳細資訊，請參閱 *AWS CLI 命令參考*中的 [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/wait/index.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/wait/index.html)。

**AWS CodeDeploy**

以下 [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/wait/change-set-create-complete.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/wait/change-set-create-complete.html) 命令範例會暫停，直到 *d-A1B2C3111* 成功完成部署。

```
$ aws deploy wait deployment-successful --deployment-id d-A1B2C3111
```

如需 AWS CodeDeploy `wait` 命令的詳細資訊，請參閱 *AWS CLI 命令參考*中的 [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/wait/index.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/wait/index.html)。

# 在 AWS CLI 中指定參數值
<a name="cli-usage-parameters"></a>

AWS Command Line Interface (AWS CLI) 所用的許多參數都是簡單的字串或數字值，例如以下 `aws ec2 create-key-pair` 命令範例中的金鑰對名稱 `my-key-pair`。

```
$ aws ec2 create-key-pair --key-name my-key-pair
```

終端之間的命令格式可能有所不同。例如，大多數終端機是區分大小寫的，但 Powershell 不區分大小寫。這代表以下兩個命令範例會為區分大小寫的終端產生不同的結果，因為它們將 `MyFile*.txt` 和 `myfile*.txt` 視為**不同**的參數。

但是，PowerShell 會處理這些請求，因為它會將 `MyFile*.txt` 和 `myfile*.txt`視作**相同**的參數。下列命令範例使用 `aws s3 cp` 命令示範這些參數：

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

有關 PowerShell 不區分大小寫的詳細資訊，請參閱 *PowerShell 文件*中的[關於不區分大小寫](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_case-sensitivity)。

有時您需要在包含特殊或空格字元的字串周圍使用引號或文字。有關此格式的規則也可能在終端機之間有所不同。如需有關在複雜參數周圍使用引號的詳細資訊，請參閱 [在 中使用引號和常值搭配字串 AWS CLI](cli-usage-parameters-quoting-strings.md)。

這些主題涵蓋最常見的終端格式化規則。如果您的終端辨識參數值發生問題，請務必檢閱本節中的主題，並檢查終端的文件是否有其特定的語法規則。

**Topics**
+ [中的常見參數類型 AWS CLI](cli-usage-parameters-types.md)
+ [在 中使用引號和常值搭配字串 AWS CLI](cli-usage-parameters-quoting-strings.md)
+ [從 中的檔案載入參數 AWS CLI](cli-usage-parameters-file.md)
+ [AWS CLI 中的骨架和輸入檔案 AWS CLI](cli-usage-skeleton.md)
+ [在 中使用速記語法 AWS CLI](cli-usage-shorthand.md)

# 中的常見參數類型 AWS CLI
<a name="cli-usage-parameters-types"></a>

本節說明一些常見的參數類型和典型必要格式。

如果您對特定命令的參數格式有問題，請在命令名稱後輸入 **help** 來檢視說明。每個子命令的幫助包括選項的名稱和說明。該選項的參數類型在括弧中列出。如需檢視說明的詳細資訊，請參閱 [存取 的說明和資源 AWS CLI](cli-usage-help.md)。

**Topics**
+ [String](#parameter-type-string)
+ [時間戳記](#parameter-type-timestamp)
+ [清單](#parameter-type-list)
+ [Boolean](#parameter-type-boolean)
+ [Integer](#parameter-type-integer)
+ [Binary/Blob (二進位大型物件)和串流 Blob](#parameter-type-blobs)
+ [Map](#parameter-type-map)
+ [文件](#parameter-type-document)

## String
<a name="parameter-type-string"></a>

字串參數可以包含 [ASCII](https://wikipedia.org/wiki/ASCII) 字元集的英數字元、符號和空格。包含空格的字串必須用引號括起來。我們建議您不要使用標準空格字元以外的符號和空格，並觀察終端機的[引用規則](cli-usage-parameters-quoting-strings.md)以防止意外結果。

某些字串參數可以接受檔案中的二進位資料。如需範例，請參閱[二進位檔案](cli-usage-parameters-file.md#cli-usage-parameters-file-binary)。

## 時間戳記
<a name="parameter-type-timestamp"></a>

根據 [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) 標準對時間戳記進行格式化。這些通常稱為「`DateTime`」或「`Date`」參數。

```
$ aws ec2 describe-spot-price-history --start-time 2014-10-13T19:00:00Z
```

可接受的格式包括：
+ *YYYY*-*MM*-*DD*T*hh*:*mm*:*ss.sss**TZD (UTC)*，例如 2014-10-01T20:30:00.000Z
+ *YYYY*-*MM*-*DD*T*hh*:*mm*:*ss.sss**TZD (包含偏移)*，例如 2014-10-01T12:30:00.000-08:00
+ *YYYY*-*MM*-*DD*，例如 2014-10-01
+ Unix 時間 (以秒為單位)，例如 1412195400。這有時稱為 [Unix Epoch 時間](https://wikipedia.org/wiki/Unix_time)，表示為 1970 年 1 月 1 日午夜 (UTC 時間) 以來的秒數。

根據預設， AWS CLI 版本 2 會將所有***回應*** DateTime 值轉譯為 ISO 8601 格式。

您可以透過使用 `cli\$1timestamp\$1format` 檔案設定來設定時間戳記格式。

## 清單
<a name="parameter-type-list"></a>

由空格分隔的一個或多個字串。如果任何字串項目包含空格，就必須使用引號括住該項目。遵守您的終端機的[引號規則](cli-usage-parameters-quoting-strings.md)以防止意外結果。

```
$ aws ec2 describe-spot-price-history --instance-types m1.xlarge m1.medium
```

## Boolean
<a name="parameter-type-boolean"></a>

可開啟或關閉選項的二進位標記。例如，`ec2 describe-spot-price-history` 有一個布林值 `--dry-run` 參數，當指定時，可以在不實際執行查詢的情況下針對服務驗證查詢。

```
$ aws ec2 describe-spot-price-history --dry-run
```

輸出表明該命令的格式是否正確。此命令還包含一個 `--no-dry-run` 版本的參數，可用於明確指示該命令應該正常執行。包括它並不是必須的，因為這是預設行為。

## Integer
<a name="parameter-type-integer"></a>

一個不帶正負號的整數。

```
$ aws ec2 describe-spot-price-history --max-items 5
```

## Binary/Blob (二進位大型物件)和串流 Blob
<a name="parameter-type-blobs"></a>

在 中 AWS CLI，您可以直接在命令列上以字串形式傳遞二進位值。Blob 有兩種：
+ [Blob](#parameter-type-blob)
+ [串流 Blob](#parameter-type-streaming-blob)

### Blob
<a name="parameter-type-blob"></a>

若要將值傳遞至類型為 `blob` 的參數，您必須使用 `fileb://` 字首為包含二進位資料的本機檔案指定路徑。使用 `fileb://` 字首參考的檔案一律視為原始未編碼的二進位。指定的路徑會解譯為相對於目前的工作目錄。例如，`aws kms encrypt` 的 `--plaintext` 參數是一個 blob。

```
$ aws kms encrypt \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \
    --plaintext fileb://ExamplePlaintextFile \
    --output text \
    --query CiphertextBlob | base64 \
    --decode > ExampleEncryptedFile
```

**注意**  
為了向後相容性，您可以使用 `file://` 字首。根據檔案設定 `cli\$1binary\$1format` 或 `--cli-binary-format` 命令列選項，會使用兩種格式：  
第 2 AWS CLI 版的預設 。如果設定值為 `base64`，使用 `file://` 字首參考的檔案會視為 base64 編碼的文字。
第 1 AWS CLI 版的預設值。如果設定的值為 `raw-in-base64-out`，則會將使用 `file://` 字首參照的檔案讀取為文字，然後 AWS CLI 嘗試將其編碼為二進位。
如需詳細資訊，請參閱檔案設定 `cli\$1binary\$1format` 或 `--cli-binary-format` 命令列選項。

### 串流 Blob
<a name="parameter-type-streaming-blob"></a>

`aws cloudsearchdomain upload-documents` 等串流 blob 不使用字首。而是使用直接檔案路徑來格式化串流 Blob 參數。下列範例將直接檔案路徑 `document-batch.json` 用於 `aws cloudsearchdomain upload-documents` 命令：

```
$ aws cloudsearchdomain upload-documents \
    --endpoint-url https://doc-my-domain.us-west-1.cloudsearch.amazonaws.com \
    --content-type application/json \
    --documents document-batch.json
```

## Map
<a name="parameter-type-map"></a>

以 JSON 或使用 CLI [速記語法](cli-usage-shorthand.md)指定的鍵/值對組。以下 JSON 範例從名為 *my-table* 的 Amazon DynamoDB 表格中讀取一個項目，並附帶地圖參數 `--key`。該參數指定一個名為 *id* 的主金鑰，其在巢狀的 JSON 結構中具有數值 *1*。

若要在命令列中使用更進階的 JSON，請考慮使用 `jq` 之類的命令列 JSON 處理器來建立 JSON 字串。如需 `jq` 的詳細資訊，請參閱 *GitHub* 上的 [jq 儲存庫](http://stedolan.github.io/jq/)。

```
$ aws dynamodb get-item --table-name my-table --key '{"id": {"N":"1"}}'

{
    "Item": {
        "name": {
            "S": "John"
        },
        "id": {
            "N": "1"
        }
    }
}
```

## 文件
<a name="parameter-type-document"></a>

**注意**  
[速記語法](cli-usage-shorthand.md)與文件類型不相容。

文件類型用於傳送資料，無需將 JSON 嵌入字串中。文件類型使服務能夠提供任意架構，以便您使用更靈活的資料類型。

這允許在不需要轉義值的情況下傳送 JSON 資料。例如，不使用以下轉義的 JSON 輸入：

```
{"document": "{\"key\":true}"}
```

您可以使用以下文件類型：

```
{"document": {"key": true}}
```

### 文件類型的有效值
<a name="parameter-type-document-valid"></a>

由於文件類型的靈活性，有多種有效的值類型。有效值包括下列項目：

**String**  

```
--option '"value"'
```

**數字**  

```
--option 123
--option 123.456
```

**Boolean**  

```
--option true
```

**Null**  

```
--option null
```

**Array**  

```
--option '["value1", "value2", "value3"]'
--option '["value", 1, true, null, ["key1", 2.34], {"key2": "value2"}]'
```

**物件**  

```
--option '{"key": "value"}'
--option '{"key1": "value1", "key2": 123, "key3": true, "key4": null, "key5": ["value3", "value4"], "key6": {"value5": "value6"}'
```

# 在 中使用引號和常值搭配字串 AWS CLI
<a name="cli-usage-parameters-quoting-strings"></a>

在 AWS CLI中使用單引號和雙引號的方式主要有兩種。
+ [在包含空格的字串前後使用引號](#cli-usage-parameters-quoting-strings-around)
+ [在字串內使用引號](#cli-usage-parameters-quoting-strings-containing)

## 在包含空格的字串前後使用引號
<a name="cli-usage-parameters-quoting-strings-around"></a>

參數名稱及其值在命令列上以空格分隔。如果字串值包含內嵌空間，則必須以引號括住整個字串，以防止 AWS CLI 將空間誤判為值和下一個參數名稱之間的分隔符號。您使用的引號類型取決於您執行 AWS CLI 的作業系統。

------
#### [ Linux and macOS ]

使用單引號 `' '` 

```
$ aws ec2 create-key-pair --key-name 'my key pair'
```

如需使用引號的詳細資訊，請依據您偏好的 Shell 參閱相關使用者文件。

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

**單引號 (建議使用)**

單引號 `' '` 稱為 `verbatim` 字串。此字串將照您的輸入傳遞至命令，這表示不會傳遞 PowerShell 變數。

```
PS C:\> aws ec2 create-key-pair --key-name 'my key pair'
```

**雙引號**

雙引號 `" "` 稱為 `expandable` 字串。變數可在可擴充的字串中傳遞。

```
PS C:\> aws ec2 create-key-pair --key-name "my key pair"
```

如需使用引號的詳細資訊，請參閱 *Microsoft PowerShell 文件*中的[關於引號規則](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_quoting_rules?view=powershell-7)。

------
#### [ Windows command prompt ]

使用雙引號 `" "`。

```
C:\> aws ec2 create-key-pair --key-name "my key pair"
```

------

您也可以使用等號 `=` 而非空格來將參數名稱與數值分開。通常只有當參數值的開頭為連字號時，才需要這麼做。

```
$ aws ec2 delete-key-pair --key-name=-mykey
```

## 在字串內使用引號
<a name="cli-usage-parameters-quoting-strings-containing"></a>

字串可能包含引號，且您的 Shell 可能需要逸出引號才能使其正常運作。其中一個常見的參數值類型是 JSON 字串。這很複雜，因為其在 JSON 結構中的每個元素名稱和數值前後都包含空格和雙引號 `" "`。您在命令列輸入 JSON 格式參數的方式會因您的作業系統而異。

若要在命令列中使用更進階的 JSON，請考慮使用 `jq` 之類的命令列 JSON 處理器來建立 JSON 字串。如需 `jq` 的詳細資訊，請參閱 *GitHub* 上的 [jq 儲存庫](http://stedolan.github.io/jq/)。

------
#### [ Linux and macOS ]

為了讓 Linux 和 macOS 按字面含義解釋字串，請使用單引號 `' '` 將 JSON 資料結構括住，如以下範例所示。您不需要逸出 JSON 字串中內嵌的雙引號，因為它們會以字面含義處理。由於 JSON 會以單引號括住，因此字串中的任何單引號都需要逸出；為此，我們通常會在單引號前面使用反斜線 `\'`。

```
$ aws ec2 run-instances \
    --image-id ami-12345678 \
    --block-device-mappings '[{"DeviceName":"/dev/sdb","Ebs":{"VolumeSize":20,"DeleteOnTermination":false,"VolumeType":"standard"}}]'
```

如需使用引號的詳細資訊，請依據您偏好的 Shell 參閱相關使用者文件。

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

使用單引號 `' '` 或雙引號 `" "`。

**單引號 (建議使用)**

單引號 `' '` 稱為 `verbatim` 字串。此字串將照您的輸入傳遞至命令，這表示不會傳遞 PowerShell 變數。

由於 JSON 資料結構包含雙引號，我們建議使用**單**引號 `' '` 將其括住。如果您使用**單**引號，則不需要逸出內嵌在 JSON 字串中的**雙**引號。但在 JSON 結構中，您必須使用反引號 ``` 來逸出每個**單**引號。

```
PS C:\> aws ec2 run-instances `
    --image-id ami-12345678 `
    --block-device-mappings '[{"DeviceName":"/dev/sdb","Ebs":{"VolumeSize":20,"DeleteOnTermination":false,"VolumeType":"standard"}}]'
```

**雙引號**

雙引號 `" "` 稱為 `expandable` 字串。變數可在可擴充的字串中傳遞。

如果您使用**雙**引號，則不需要逸出內嵌在 JSON 字串中的**單**引號。但在 JSON 結構中，您必須使用反引號 ``` 來逸出每個**雙**引號，如以下範例所示。

```
PS C:\> aws ec2 run-instances `
    --image-id ami-12345678 `
    --block-device-mappings "[{`"DeviceName`":`"/dev/sdb`",`"Ebs`":{`"VolumeSize`":20,`"DeleteOnTermination`":false,`"VolumeType`":`"standard`"}}]"
```

如需使用引號的詳細資訊，請參閱 *Microsoft PowerShell 文件*中的[關於引號規則](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_quoting_rules?view=powershell-7)。

**警告**  
在 PowerShell 傳送命令至 之前 AWS CLI，它會判斷您的命令是使用一般 PowerShell `CommandLineToArgvW` 還是引號規則來解譯。在 PowerShell 使用 `CommandLineToArgvW` 進行處理時，您必須使用反斜線 `\` 逸出字元。  
如需 PowerShell 中 `CommandLineToArgvW` 的詳細資訊，請參閱 *Microsoft DevBlogs* 中的 [CommandLineToArgvW 對引號和反斜線的奇怪處理是怎麼回事](https://devblogs.microsoft.com/oldnewthing/20100917-00/?p=12833) (What's up with the strange treatment of quotation marks and backslashes by CommandLineToArgvW)、*Microsoft Docs Blog* 中的[大家都以錯誤方式引用命令列引數](https://docs.microsoft.com/en-us/archive/blogs/twistylittlepassagesallalike/everyone-quotes-command-line-arguments-the-wrong-way) (Everyone quotes command line arguments the wrong way)，以及 *Microsoft Docs* 中的 [CommandLineToArgvW 函數](https://docs.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-commandlinetoargvw#remarks)。  
**單引號**  
單引號 `' '` 稱為 `verbatim` 字串。此字串將照您的輸入傳遞至命令，這表示不會傳遞 PowerShell 變數。使用反斜線 `\` 逸出字元。  

```
PS C:\> aws ec2 run-instances `
    --image-id ami-12345678 `
    --block-device-mappings '[{\"DeviceName\":\"/dev/sdb\",\"Ebs\":{\"VolumeSize\":20,\"DeleteOnTermination\":false,\"VolumeType\":\"standard\"}}]'
```
**雙引號**  
雙引號 `" "` 稱為 `expandable` 字串。變數可在 `expandable` 字串中傳遞。對於雙引號字串，您必須在每個引號使用 *`\$1* 逸出兩次，而不是只用反引號。反引號會逸出反斜線，然後使用反斜線做為 `CommandLineToArgvW` 程序的逸出字元。  

```
PS C:\> aws ec2 run-instances `
    --image-id ami-12345678 `
    --block-device-mappings "[{`\"DeviceName`\":`\"/dev/sdb`\",`\"Ebs`\":{`\"VolumeSize`\":20,`\"DeleteOnTermination`\":false,`\"VolumeType`\":`\"standard`\"}}]"
```
**Blob (建議)**  
若要繞過 JSON 資料輸入的 PowerShell 引號規則，請使用 Blob 將 JSON 資料直接傳遞至 AWS CLI。如需 Blobs 的詳細資訊，請參閱 [Blob](cli-usage-parameters-types.md#parameter-type-blob)。

------
#### [ Windows command prompt ]

Windows 命令提示要求使用雙引號 `" "` 括住 JSON 資料結構。此外，若要防止命令處理器錯誤解譯 JSON 中內嵌的雙引號，您也必須在 JSON 資料結構本身中逸出 (前面加上反斜線 `\` 字元) 每個雙引號 `"`，如下列範例所示。

```
C:\> aws ec2 run-instances ^
    --image-id ami-12345678 ^
    --block-device-mappings "[{\"DeviceName\":\"/dev/sdb\",\"Ebs\":{\"VolumeSize\":20,\"DeleteOnTermination\":false,\"VolumeType\":\"standard\"}}]"
```

只有最外面的雙引號不用逸出。

------

# 從 中的檔案載入參數 AWS CLI
<a name="cli-usage-parameters-file"></a>

有些參數預期檔案名稱為引數， 會從中 AWS CLI 載入資料。其他參數可讓您以在命令列中輸入文字或從檔案讀取的形式指定參數值。無論檔案是必要或選用，您都必須正確編碼檔案， AWS CLI 才能了解該檔案。檔案的編碼必須符合讀取系統的預設地區設定。您可以透過使用 Python `locale.getpreferredencoding()` 方法判斷。

此方法用於載入單一參數的檔案。如需使用單一檔案載入多個參數的資訊，請參閱 [AWS CLI 中的骨架和輸入檔案 AWS CLI](cli-usage-skeleton.md)。

**注意**  
根據預設，Windows PowerShell 會將文字輸出為 UTF-16，這會與 JSON 檔案和許多 Linux 系統所使用的 UTF-8 編碼衝突。我們建議您`-Encoding ascii`搭配 PowerShell `Out-File`命令使用 ，以確保 AWS CLI 可以讀取產生的檔案。

**Topics**
+ [如何從檔案載入參數](#cli-usage-parameters-file-how)
+ [二進位檔案](#cli-usage-parameters-file-binary)
+ [將檔案載入為速記語法值](#cli-usage-parameters-file-shorthand)

## 如何從檔案載入參數
<a name="cli-usage-parameters-file-how"></a>

從檔案載入參數值有時很方便，而不要嘗試完全以命令列參數值輸入，例如當參數是複雜的 JSON 字串時。若要指定包含數值的檔案，請以下列格式指定檔案 URL。

```
file://complete/path/to/file
```
+ 前兩個斜線「/」字元是規格的一部分。如果所需的路徑以「/」開頭，則結果為三個斜線字元：`file:///folder/file`。
+ 此 URL 提供檔案的路徑，該檔案包含實際的參數內容。
+ 使用帶有空格或特殊字符的檔案時，請遵循您終端適用的[引用和逸出規則](cli-usage-parameters-quoting-strings.md)。

在下列範例中，檔案路徑是以相對於目前的工作目錄來解譯。

------
#### [ Linux or macOS ]

```
// Read from a file in the current directory
$ aws ec2 describe-instances --filters file://filter.json

// Read from a file in /tmp
$ aws ec2 describe-instances --filters file:///tmp/filter.json

// Read from a file with a filename with whitespaces
$ aws ec2 describe-instances --filters 'file://filter content.json'
```

------
#### [ Windows command prompt ]

```
// Read from a file in C:\temp
C:\> aws ec2 describe-instances --filters file://C:\temp\filter.json

// Read from a file with a filename with whitespaces
C:\> aws ec2 describe-instances --filters "file://C:\temp\filter content.json"
```

------

`file://` 前綴選項支援 Unix 風格的擴展，包括「`~/`」、「`./`」和「`../`」。在 Windows 上，「`~/`」表達式擴展到您的使用者目錄，儲存在 `%USERPROFILE%` 環境變數中。例如，在 Windows 10 中，通常在 `%USERPROFILE%` 下有一個使用者目錄。

您仍然必須逸出內嵌為其他 JSON 文件數值的 JSON 文件。

```
$ aws sqs create-queue --queue-name my-queue --attributes file://attributes.json
```

**attributes.json**

```
{
  "RedrivePolicy": "{\"deadLetterTargetArn\":\"arn:aws:sqs:us-west-2:0123456789012:deadletter\", \"maxReceiveCount\":\"5\"}"
}
```

## 二進位檔案
<a name="cli-usage-parameters-file-binary"></a>

對於以二進位資料作為參數的命令，使用 `fileb://` 前綴所指定的資料是二進位內容。接受二進位資料的命令包括：
+  **`aws ec2 run-instances:`** `--user-data` 參數。
+  **`aws s3api put-object:`** `--sse-customer-key` 參數。
+  **`aws kms decrypt:`** `--ciphertext-blob` 參數。

以下範例使用 Linux 命令列工具產生二進位 256 位元 AES 金鑰，然後將其提供給 Amazon S3 來加密上傳的檔案伺服器端。

```
$ dd if=/dev/urandom bs=1 count=32 > sse.key
32+0 records in
32+0 records out
32 bytes (32 B) copied, 0.000164441 s, 195 kB/s
$ aws s3api put-object \
    --bucket amzn-s3-demo-bucket \
    --key test.txt \
    --body test.txt \
    --sse-customer-key fileb://sse.key \
    --sse-customer-algorithm AES256
{
    "SSECustomerKeyMD5": "iVg8oWa8sy714+FjtesrJg==",
    "SSECustomerAlgorithm": "AES256",
    "ETag": "\"a6118e84b76cf98bf04bbe14b6045c6c\""
}
```

關於參考包含 JSON 格式參數的檔案的另一個範例，請參閱 [將 IAM 受管政策連接至使用者](cli-services-iam.md#cli-services-iam-policy)。

## 將檔案載入為速記語法值
<a name="cli-usage-parameters-file-shorthand"></a>

使用值較大或複雜的速記語法時，通常更容易將檔案載入為值。若要將檔案載入為速記語法值，格式會稍微變更。不是 `key=value`，您將使用 `@=` 運算子，而非 `=` 運算子。`@=` 表示 AWS CLI 應將該值讀為檔案路徑，而不是字串。下列範例會示範金鑰-值對如何為其值載入檔案。

------
#### [ Linux or macOS ]

```
--option key@=file://template.txt
```

------
#### [ Windows ]

```
--option "key1@=file://template.txt"
```

------

下列範例會示範為 `aws rolesanywhere create-trust-anchor` 命令載入憑證檔案。

```
$ aws rolesanywhere create-trust-anchor --name TrustAnchor \
    --source sourceData={x509CertificateData@=file://root-ca.crt},sourceType="CERTIFICATE_BUNDLE"  \ 
    --enabled
```

如需速記語法的詳細資訊，請參閱 [在 中使用速記語法 AWS CLI](cli-usage-shorthand.md)。

# AWS CLI 中的骨架和輸入檔案 AWS CLI
<a name="cli-usage-skeleton"></a>

大多數 AWS CLI 命令都接受從檔案匯入參數輸入。這些範本可以使用 `generate-cli-skeleton` 選項產生，然後使用 `--cli-input-json`和 `--cli-input-yaml` 參數匯入。

**Topics**
+ [關於骨 AWS CLI 架和輸入檔案](#cli-usage-skeleton-about)
+ [產生和匯入命令骨架](#cli-usage-skeleton-generate)
+ [結合輸入檔案和命令列參數](#cli-usage-skeleton-combine)

## 關於骨 AWS CLI 架和輸入檔案
<a name="cli-usage-skeleton-about"></a>

大多數 AWS Command Line Interface (AWS CLI) 命令都支援使用 `--cli-input-json`和 `--cli-input-yaml` 參數接受來自檔案的參數輸入。

這些相同命令使用 `--generate-cli-skeleton` 參數，以您能夠編輯和填入的所有參數來產生 JSON 或 YAML  格式的檔案。然後，您可以執行命令搭配 `--cli-input-json` 或 `--cli-input-yaml` 參數，以指向要填入的檔案。

**重要**  
自訂 AWS CLI 命令，例如[`aws s3`命令](https://docs.aws.amazon.com/cli/latest/reference/s3/index.html)不支援本主題中所述的 `--generate-cli-skeleton`或 `--cli-input-json`和 `--cli-input-yaml` 參數。若要檢查特定命令是否支援這些參數，請針對您要使用的命令執行 [`help` 命令](cli-usage-help.md#cli-usage-help-command)，或參閱[AWS CLI 版本 2 參考指南](https://docs.aws.amazon.com/cli/latest/reference/index.html)。

`--generate-cli-skeleton` 會產生並顯示參數範本，您可以在命令上自訂該範本並用作輸入。產生的範本包含命令支援的所有參數。

`--generate-cli-skeleton` 參數接受下列其中一個數值：
+ `input` – 產生的範本包括所有格式化為 JSON 的輸入參數。這是預設值。
+ `yaml-input` – 產生的範本包括所有格式化為 YAML 的輸入參數。
+ `output` – 產生的範本包括所有 JSON 格式的輸出參數。您目前無法請求輸出參數為 YAML。

由於 基本上 AWS CLI 是圍繞服務 API 的「包裝函式」，因此骨架檔案會要求您依其基礎 API 參數名稱來參考所有參數。這可能與 AWS CLI 參數名稱不同。例如，名為 的 AWS CLI 參數`user-name`可能會對應到名為 AWS 的服務 API 參數 `UserName`（請注意已變更的大寫和遺失破折號）。建議您使用 `--generate-cli-skeleton` 選項，以「正確」參數名稱產生範本，以免發生錯誤。您可以參考該服務的《API 參考指南》，以查看預期的參數名稱。您可以從範本刪除任何非必要且不想為其提供數值的參數。

例如，如果您執行以下命令，其會為 Amazon Elastic Compute Cloud (Amazon EC2) 命令 **run-instances** 產生參數範本。

------
#### [ JSON ]

下列範例顯示如何使用 `--generate-cli-skeleton` 參數的預設值 (`input`) 生產格式化的 JSON 範本。

```
$ aws ec2 run-instances --generate-cli-skeleton
```

```
{
    "DryRun": true,
    "ImageId": "",
    "MinCount": 0,
    "MaxCount": 0,
    "KeyName": "",
    "SecurityGroups": [
        ""
    ],
    "SecurityGroupIds": [
        ""
    ],
    "UserData": "",
    "InstanceType": "",
    "Placement": {
        "AvailabilityZone": "",
        "GroupName": "",
        "Tenancy": ""
    },
    "KernelId": "",
    "RamdiskId": "",
    "BlockDeviceMappings": [
        {
            "VirtualName": "",
            "DeviceName": "",
            "Ebs": {
                "SnapshotId": "",
                "VolumeSize": 0,
                "DeleteOnTermination": true,
                "VolumeType": "",
                "Iops": 0,
                "Encrypted": true
            },
            "NoDevice": ""
        }
    ],
    "Monitoring": {
        "Enabled": true
    },
    "SubnetId": "",
    "DisableApiTermination": true,
    "InstanceInitiatedShutdownBehavior": "",
    "PrivateIpAddress": "",
    "ClientToken": "",
    "AdditionalInfo": "",
    "NetworkInterfaces": [
        {
            "NetworkInterfaceId": "",
            "DeviceIndex": 0,
            "SubnetId": "",
            "Description": "",
            "PrivateIpAddress": "",
            "Groups": [
                ""
            ],
            "DeleteOnTermination": true,
            "PrivateIpAddresses": [
                {
                    "PrivateIpAddress": "",
                    "Primary": true
                }
            ],
            "SecondaryPrivateIpAddressCount": 0,
            "AssociatePublicIpAddress": true
        }
    ],
    "IamInstanceProfile": {
        "Arn": "",
        "Name": ""
    },
    "EbsOptimized": true
}
```

------
#### [ YAML ]

下列範例顯示如何使用 `yaml-input` 參數的 `--generate-cli-skeleton` 數值產生格式化的 YAML 範本。

```
$ aws ec2 run-instances --generate-cli-skeleton yaml-input
```

```
BlockDeviceMappings:  # The block device mapping entries.
- DeviceName: ''  # The device name (for example, /dev/sdh or xvdh).
  VirtualName: '' # The virtual device name (ephemeralN).
  Ebs: # Parameters used to automatically set up Amazon EBS volumes when the instance is launched.
    DeleteOnTermination: true  # Indicates whether the EBS volume is deleted on instance termination.
    Iops: 0 # The number of I/O operations per second (IOPS) that the volume supports.
    SnapshotId: '' # The ID of the snapshot.
    VolumeSize: 0 # The size of the volume, in GiB.
    VolumeType: st1 # The volume type. Valid values are: standard, io1, gp2, sc1, st1.
    Encrypted: true # Indicates whether the encryption state of an EBS volume is changed while being restored from a backing snapshot.
    KmsKeyId: '' # Identifier (key ID, key alias, ID ARN, or alias ARN) for a customer managed KMS key under which the EBS volume is encrypted.
  NoDevice: '' # Suppresses the specified device included in the block device mapping of the AMI.
ImageId: '' # The ID of the AMI.
InstanceType: c4.4xlarge # The instance type. Valid values are: t1.micro, t2.nano, t2.micro, t2.small, t2.medium, t2.large, t2.xlarge, t2.2xlarge, t3.nano, t3.micro, t3.small, t3.medium, t3.large, t3.xlarge, t3.2xlarge, t3a.nano, t3a.micro, t3a.small, t3a.medium, t3a.large, t3a.xlarge, t3a.2xlarge, m1.small, m1.medium, m1.large, m1.xlarge, m3.medium, m3.large, m3.xlarge, m3.2xlarge, m4.large, m4.xlarge, m4.2xlarge, m4.4xlarge, m4.10xlarge, m4.16xlarge, m2.xlarge, m2.2xlarge, m2.4xlarge, cr1.8xlarge, r3.large, r3.xlarge, r3.2xlarge, r3.4xlarge, r3.8xlarge, r4.large, r4.xlarge, r4.2xlarge, r4.4xlarge, r4.8xlarge, r4.16xlarge, r5.large, r5.xlarge, r5.2xlarge, r5.4xlarge, r5.8xlarge, r5.12xlarge, r5.16xlarge, r5.24xlarge, r5.metal, r5a.large, r5a.xlarge, r5a.2xlarge, r5a.4xlarge, r5a.8xlarge, r5a.12xlarge, r5a.16xlarge, r5a.24xlarge, r5d.large, r5d.xlarge, r5d.2xlarge, r5d.4xlarge, r5d.8xlarge, r5d.12xlarge, r5d.16xlarge, r5d.24xlarge, r5d.metal, r5ad.large, r5ad.xlarge, r5ad.2xlarge, r5ad.4xlarge, r5ad.8xlarge, r5ad.12xlarge, r5ad.16xlarge, r5ad.24xlarge, x1.16xlarge, x1.32xlarge, x1e.xlarge, x1e.2xlarge, x1e.4xlarge, x1e.8xlarge, x1e.16xlarge, x1e.32xlarge, i2.xlarge, i2.2xlarge, i2.4xlarge, i2.8xlarge, i3.large, i3.xlarge, i3.2xlarge, i3.4xlarge, i3.8xlarge, i3.16xlarge, i3.metal, i3en.large, i3en.xlarge, i3en.2xlarge, i3en.3xlarge, i3en.6xlarge, i3en.12xlarge, i3en.24xlarge, i3en.metal, hi1.4xlarge, hs1.8xlarge, c1.medium, c1.xlarge, c3.large, c3.xlarge, c3.2xlarge, c3.4xlarge, c3.8xlarge, c4.large, c4.xlarge, c4.2xlarge, c4.4xlarge, c4.8xlarge, c5.large, c5.xlarge, c5.2xlarge, c5.4xlarge, c5.9xlarge, c5.12xlarge, c5.18xlarge, c5.24xlarge, c5.metal, c5d.large, c5d.xlarge, c5d.2xlarge, c5d.4xlarge, c5d.9xlarge, c5d.18xlarge, c5n.large, c5n.xlarge, c5n.2xlarge, c5n.4xlarge, c5n.9xlarge, c5n.18xlarge, cc1.4xlarge, cc2.8xlarge, g2.2xlarge, g2.8xlarge, g3.4xlarge, g3.8xlarge, g3.16xlarge, g3s.xlarge, g4dn.xlarge, g4dn.2xlarge, g4dn.4xlarge, g4dn.8xlarge, g4dn.12xlarge, g4dn.16xlarge, cg1.4xlarge, p2.xlarge, p2.8xlarge, p2.16xlarge, p3.2xlarge, p3.8xlarge, p3.16xlarge, p3dn.24xlarge, d2.xlarge, d2.2xlarge, d2.4xlarge, d2.8xlarge, f1.2xlarge, f1.4xlarge, f1.16xlarge, m5.large, m5.xlarge, m5.2xlarge, m5.4xlarge, m5.8xlarge, m5.12xlarge, m5.16xlarge, m5.24xlarge, m5.metal, m5a.large, m5a.xlarge, m5a.2xlarge, m5a.4xlarge, m5a.8xlarge, m5a.12xlarge, m5a.16xlarge, m5a.24xlarge, m5d.large, m5d.xlarge, m5d.2xlarge, m5d.4xlarge, m5d.8xlarge, m5d.12xlarge, m5d.16xlarge, m5d.24xlarge, m5d.metal, m5ad.large, m5ad.xlarge, m5ad.2xlarge, m5ad.4xlarge, m5ad.8xlarge, m5ad.12xlarge, m5ad.16xlarge, m5ad.24xlarge, h1.2xlarge, h1.4xlarge, h1.8xlarge, h1.16xlarge, z1d.large, z1d.xlarge, z1d.2xlarge, z1d.3xlarge, z1d.6xlarge, z1d.12xlarge, z1d.metal, u-6tb1.metal, u-9tb1.metal, u-12tb1.metal, u-18tb1.metal, u-24tb1.metal, a1.medium, a1.large, a1.xlarge, a1.2xlarge, a1.4xlarge, a1.metal, m5dn.large, m5dn.xlarge, m5dn.2xlarge, m5dn.4xlarge, m5dn.8xlarge, m5dn.12xlarge, m5dn.16xlarge, m5dn.24xlarge, m5n.large, m5n.xlarge, m5n.2xlarge, m5n.4xlarge, m5n.8xlarge, m5n.12xlarge, m5n.16xlarge, m5n.24xlarge, r5dn.large, r5dn.xlarge, r5dn.2xlarge, r5dn.4xlarge, r5dn.8xlarge, r5dn.12xlarge, r5dn.16xlarge, r5dn.24xlarge, r5n.large, r5n.xlarge, r5n.2xlarge, r5n.4xlarge, r5n.8xlarge, r5n.12xlarge, r5n.16xlarge, r5n.24xlarge.
Ipv6AddressCount: 0 # [EC2-VPC] The number of IPv6 addresses to associate with the primary network interface.
Ipv6Addresses: # [EC2-VPC] The IPv6 addresses from the range of the subnet to associate with the primary network interface.
- Ipv6Address: ''  # The IPv6 address.
KernelId: '' # The ID of the kernel.
KeyName: '' # The name of the key pair.
MaxCount: 0 # [REQUIRED] The maximum number of instances to launch.
MinCount: 0 # [REQUIRED] The minimum number of instances to launch.
Monitoring: # Specifies whether detailed monitoring is enabled for the instance.
  Enabled: true  # [REQUIRED] Indicates whether detailed monitoring is enabled.
Placement: # The placement for the instance.
  AvailabilityZone: ''  # The Availability Zone of the instance.
  Affinity: '' # The affinity setting for the instance on the Dedicated Host.
  GroupName: '' # The name of the placement group the instance is in.
  PartitionNumber: 0 # The number of the partition the instance is in.
  HostId: '' # The ID of the Dedicated Host on which the instance resides.
  Tenancy: dedicated # The tenancy of the instance (if the instance is running in a VPC). Valid values are: default, dedicated, host.
  SpreadDomain: '' # Reserved for future use.
RamdiskId: '' # The ID of the RAM disk to select.
SecurityGroupIds: # The IDs of the security groups.
- ''
SecurityGroups: # [default VPC] The names of the security groups.
- ''
SubnetId: '' # [EC2-VPC] The ID of the subnet to launch the instance into.
UserData: '' # The user data to make available to the instance.
AdditionalInfo: '' # Reserved.
ClientToken: '' # Unique, case-sensitive identifier you provide to ensure the idempotency of the request.
DisableApiTermination: true # If you set this parameter to true, you can't terminate the instance using the Amazon EC2 console, CLI, or API; otherwise, you can.
DryRun: true # Checks whether you have the required permissions for the action, without actually making the request, and provides an error response.
EbsOptimized: true # Indicates whether the instance is optimized for Amazon EBS I/O.
IamInstanceProfile: # The IAM instance profile.
  Arn: ''  # The Amazon Resource Name (ARN) of the instance profile.
  Name: '' # The name of the instance profile.
InstanceInitiatedShutdownBehavior: stop # Indicates whether an instance stops or terminates when you initiate shutdown from the instance (using the operating system command for system shutdown). Valid values are: stop, terminate.
NetworkInterfaces: # The network interfaces to associate with the instance.
- AssociatePublicIpAddress: true  # Indicates whether to assign a public IPv4 address to an instance you launch in a VPC.
  DeleteOnTermination: true # If set to true, the interface is deleted when the instance is terminated.
  Description: '' # The description of the network interface.
  DeviceIndex: 0 # The position of the network interface in the attachment order.
  Groups: # The IDs of the security groups for the network interface.
  - ''
  Ipv6AddressCount: 0 # A number of IPv6 addresses to assign to the network interface.
  Ipv6Addresses: # One or more IPv6 addresses to assign to the network interface.
  - Ipv6Address: ''  # The IPv6 address.
  NetworkInterfaceId: '' # The ID of the network interface.
  PrivateIpAddress: '' # The private IPv4 address of the network interface.
  PrivateIpAddresses: # One or more private IPv4 addresses to assign to the network interface.
  - Primary: true  # Indicates whether the private IPv4 address is the primary private IPv4 address.
    PrivateIpAddress: '' # The private IPv4 addresses.
  SecondaryPrivateIpAddressCount: 0 # The number of secondary private IPv4 addresses.
  SubnetId: '' # The ID of the subnet associated with the network interface.
  InterfaceType: '' # The type of network interface.
PrivateIpAddress: '' # [EC2-VPC] The primary IPv4 address.
ElasticGpuSpecification: # An elastic GPU to associate with the instance.
- Type: ''  # [REQUIRED] The type of Elastic Graphics accelerator.
ElasticInferenceAccelerators: # An elastic inference accelerator to associate with the instance.
- Type: ''  # [REQUIRED]  The type of elastic inference accelerator.
TagSpecifications: # The tags to apply to the resources during launch.
- ResourceType: network-interface  # The type of resource to tag. Valid values are: client-vpn-endpoint, customer-gateway, dedicated-host, dhcp-options, elastic-ip, fleet, fpga-image, host-reservation, image, instance, internet-gateway, launch-template, natgateway, network-acl, network-interface, reserved-instances, route-table, security-group, snapshot, spot-instances-request, subnet, traffic-mirror-filter, traffic-mirror-session, traffic-mirror-target, transit-gateway, transit-gateway-attachment, transit-gateway-route-table, volume, vpc, vpc-peering-connection, vpn-connection, vpn-gateway.
  Tags: # The tags to apply to the resource.
  - Key: ''  # The key of the tag.
    Value: '' # The value of the tag.
LaunchTemplate: # The launch template to use to launch the instances.
  LaunchTemplateId: ''  # The ID of the launch template.
  LaunchTemplateName: '' # The name of the launch template.
  Version: '' # The version number of the launch template.
InstanceMarketOptions: # The market (purchasing) option for the instances.
  MarketType: spot  # The market type. Valid values are: spot.
  SpotOptions: # The options for Spot Instances.
    MaxPrice: ''  # The maximum hourly price you're willing to pay for the Spot Instances.
    SpotInstanceType: one-time # The Spot Instance request type. Valid values are: one-time, persistent.
    BlockDurationMinutes: 0 # The required duration for the Spot Instances (also known as Spot blocks), in minutes.
    ValidUntil: 1970-01-01 00:00:00 # The end date of the request.
    InstanceInterruptionBehavior: terminate # The behavior when a Spot Instance is interrupted. Valid values are: hibernate, stop, terminate.
CreditSpecification: # The credit option for CPU usage of the T2 or T3 instance.
  CpuCredits: ''  # [REQUIRED] The credit option for CPU usage of a T2 or T3 instance.
CpuOptions: # The CPU options for the instance.
  CoreCount: 0  # The number of CPU cores for the instance.
  ThreadsPerCore: 0 # The number of threads per CPU core.
CapacityReservationSpecification: # Information about the Capacity Reservation targeting option.
  CapacityReservationPreference: none  # Indicates the instance's Capacity Reservation preferences. Valid values are: open, none.
  CapacityReservationTarget: # Information about the target Capacity Reservation.
    CapacityReservationId: ''  # The ID of the Capacity Reservation.
HibernationOptions: # Indicates whether an instance is enabled for hibernation.
  Configured: true  # If you set this parameter to true, your instance is enabled for hibernation.
LicenseSpecifications: # The license configurations.
- LicenseConfigurationArn: ''  # The Amazon Resource Name (ARN) of the license configuration.
```

------

## 產生和匯入命令骨架
<a name="cli-usage-skeleton-generate"></a>

**若要產生和使用參數骨架檔案**

1. 執行命令搭配 `--generate-cli-skeleton` 參數，產生   JSON 或 YAML，並將輸出導向至檔案以便儲存。

------
#### [ JSON ]

   ```
   $ aws ec2 run-instances --generate-cli-skeleton input > ec2runinst.json
   ```

------
#### [ YAML ]

   ```
   $ aws ec2 run-instances --generate-cli-skeleton yaml-input > ec2runinst.yaml
   ```

------

1. 在文字編輯器中開啟參數骨架檔案，移除您不需要的任何參數。例如，您可以將範本剔除為下列內容。移除不需要的元素之後，請確認檔案仍是有效的 JSON  或 YAML。

------
#### [ JSON ]

   ```
   {
       "DryRun": true,
       "ImageId": "",
       "KeyName": "",
       "SecurityGroups": [
           ""
       ],
       "InstanceType": "",
       "Monitoring": {
           "Enabled": true
       }
   }
   ```

------
#### [ YAML ]

   ```
   DryRun: true
   ImageId: ''
   KeyName: ''
   SecurityGroups:
   - ''
   InstanceType:
   Monitoring: 
     Enabled: true
   ```

------

   在此範例中，我們會保留設定為 `true` 的 `DryRun` 參數，以便使用 Amazon EC2 試轉功能。此功能可讓您安全地測試命令，而不必實際建立或修改任何資源。

1. 使用適合您方案的數值，填入其餘數值。在這個範例中，我們提供 Amazon Machine Image (AMI) 的執行個體類型、金鑰名稱、安全群組和識別符以供使用。此範例假設預設值 AWS 區域。AMI `ami-dfc39aef` 是託管於 `us-west-2` 區域中的 64 位元 Amazon Linux 映像。如果使用不同的區域，您必須 [找到要使用的正確 AMI ID](https://aws.amazon.com/amazon-linux-ami/)。

------
#### [ JSON ]

   ```
   {
       "DryRun": true,
       "ImageId": "ami-dfc39aef",
       "KeyName": "mykey",
       "SecurityGroups": [
           "my-sg"
       ],
       "InstanceType": "t2.micro",
       "Monitoring": {
           "Enabled": true
       }
   }
   ```

------
#### [ YAML ]

   ```
   DryRun: true
   ImageId: 'ami-dfc39aef'
   KeyName: 'mykey'
   SecurityGroups:
   - 'my-sg'
   InstanceType: 't2.micro'
   Monitoring: 
     Enabled: true
   ```

------

1. 使用 `file://` 前綴將完整的範本檔案傳遞到 `--cli-input-json` 或 -- `cli-input-yaml`參數，以使用完成的參數執行命令。會 AWS CLI 解譯相對於您目前工作目錄的路徑。下列範例會在目前的工作目錄中 AWS CLI 尋找 檔案。

------
#### [ JSON ]

   ```
   $ aws ec2 run-instances --cli-input-json file://ec2runinst.json
   ```

   ```
   A client error (DryRunOperation) occurred when calling the RunInstances operation: Request would have succeeded, but DryRun flag is set.
   ```

------
#### [ YAML ]

   ```
   $ aws ec2 run-instances --cli-input-yaml file://ec2runinst.yaml
   ```

   ```
   A client error (DryRunOperation) occurred when calling the RunInstances operation: Request would have succeeded, but DryRun flag is set.
   ```

------

   試轉錯誤表示 JSON 或 YAML 正確產生且參數值有效。如果在輸出中報告其他問題，請修復它們並重複先前步驟，直到顯示「`Request would have succeeded`」訊息為止。

1. 現在您可以將 `DryRun` 參數設定為 `false`，以停用試轉。

------
#### [ JSON ]

   ```
   {
       "DryRun": false,
       "ImageId": "ami-dfc39aef",
       "KeyName": "mykey",
       "SecurityGroups": [
           "my-sg"
       ],
       "InstanceType": "t2.micro",
       "Monitoring": {
           "Enabled": true
       }
   }
   ```

------
#### [ YAML ]

   ```
   DryRun: false
   ImageId: 'ami-dfc39aef'
   KeyName: 'mykey'
   SecurityGroups:
   - 'my-sg'
   InstanceType: 't2.micro'
   Monitoring: 
     Enabled: true
   ```

------

1. 執行命令，`run-instances` 會實際啟動 Amazon EC2 執行個體並顯示成功啟動產生的詳細資訊。輸出的格式是由 `--output` 參數控制，與輸入參數範本的格式分開。

------
#### [ JSON ]

   ```
   $ aws ec2 run-instances --cli-input-json file://ec2runinst.json --output json
   ```

   ```
   {
       "OwnerId": "123456789012",
       "ReservationId": "r-d94a2b1",
       "Groups": [],
       "Instances": [
   ...
   ```

------
#### [ YAML ]

   ```
   $ aws ec2 run-instances --cli-input-yaml file://ec2runinst.yaml --output yaml
   ```

   ```
   OwnerId: '123456789012'
   ReservationId: 'r-d94a2b1',
   Groups":
   - ''
   Instances:
   ...
   ```

------

## 結合輸入檔案和命令列參數
<a name="cli-usage-skeleton-combine"></a>

輸入檔案可用於所有參數，也可以與 AWS CLI中指定的參數結合。您可以將此功能用於在輸入檔案中經常重複使用的設定，同時將個別設定保留在命令本身。

下列 `aws ec2 run-instances` 範例會結合使用輸入檔案和參數。我們提供執行個體類型、金鑰名稱、安全群組、Amazon Machine Image (AMI) 的識別符，以供使用並擔任預設值 AWS 區域。AMI `ami-dfc39aef` 是託管於 `us-west-2` 區域中的 64 位元 Amazon Linux 映像。如果使用不同的區域，您必須 [找到要使用的正確 AMI ID](https://aws.amazon.com/amazon-linux-ami/)。

------
#### [ JSON ]

JSON 檔案的內容：

```
{
    "ImageId": "ami-dfc39aef",
    "KeyName": "mykey",
    "SecurityGroups": [
        "my-sg"
    ],
    "InstanceType": "t2.micro",
    "Monitoring": {
        "Enabled": true
    }
}
```

------
#### [ YAML ]

YAML 檔案的內容：

```
ImageId: 'ami-dfc39aef'
KeyName: 'mykey'
SecurityGroups:
- 'my-sg'
InstanceType: 't2.micro'
Monitoring: 
  Enabled: true
```

------

下列範例使用輸入檔案並搭配 `--dry-run` 參數，來執行命令的停用試轉，以確認您是否具有所需的許可，並已使用有效的值填入檔案。

------
#### [ JSON ]

```
$ aws ec2 run-instances --cli-input-json file://ec2runinst.json --dry-run
```

```
A client error (DryRunOperation) occurred when calling the RunInstances operation: Request would have succeeded, but DryRun flag is set.
```

------
#### [ YAML ]

```
$ aws ec2 run-instances --cli-input-yaml file://ec2runinst.yaml --dry-run
```

```
A client error (DryRunOperation) occurred when calling the RunInstances operation: Request would have succeeded, but DryRun flag is set.
```

------

以下範例接著會使用相同的輸入檔案，但使用 `--no-dry-run` 參數完整執行命令。

------
#### [ JSON ]

```
$ aws ec2 run-instances --cli-input-json file://ec2runinst.json --no-dry-run --output json
```

```
{
    "OwnerId": "123456789012",
    "ReservationId": "r-d94a2b1",
    "Groups": [],
    "Instances": [
...
```

------
#### [ YAML ]

```
$ aws ec2 run-instances --cli-input-yaml file://ec2runinst.yaml --no-dry-run --output yaml
```

```
OwnerId: '123456789012'
ReservationId: 'r-d94a2b1',
Groups":
- ''
Instances:
...
```

------

# 在 中使用速記語法 AWS CLI
<a name="cli-usage-shorthand"></a>

 AWS Command Line Interface (AWS CLI) 可以接受 JSON 格式的許多選項參數。不過，在命令列輸入大型 JSON 清單或結構可能會變得很冗長。為了簡化此作業， AWS CLI 也支援速記語法，相較於使用完整的 JSON 格式，可讓您更輕鬆地呈現選項參數。

**Topics**
+ [具有金鑰-值對的結構參數](#shorthand-structure-parameters)
+ [將檔案載入為速記語法值](#shorthand-files)
+ [搭配 使用速記語法 AWS CLI](#shorthand-list-parameters)

## 具有金鑰-值對的結構參數
<a name="shorthand-structure-parameters"></a>

中的速記語法 AWS CLI 可讓使用者更輕鬆地輸入平坦的參數 （非巢狀結構）。格式為以逗號分隔的鍵值對清單。請務必使用您的終端機適用的[引用](cli-usage-parameters-quoting-strings.md)和轉義規則，因為速記語法是字串。

------
#### [ Linux or macOS ]

```
--option key1=value1,key2=value2,key3=value3
```

等同於下列 JSON 格式的範例。

```
--option '{"key1":"value1","key2":"value2","key3":"value3"}'
```

------
#### [ Windows ]

```
--option "key1=value1,key2=value2,key3=value3"
```

等同於下列 JSON 格式的範例。

```
--option '{"key1":"value1","key2":"value2","key3":"value3"}'
```

------

每個逗號分隔的金鑰/數值對之間不能有空白字元。以下範例為 Amazon DynamoDB `update-table` 命令，其包含以速記語法指定的 `--provisioned-throughput` 選項。

```
$ aws dynamodb update-table \
    --provisioned-throughput ReadCapacityUnits=15,WriteCapacityUnits=10 \
    --table-name MyDDBTable
```

這等同於下列 JSON 格式的範例。

```
$ aws dynamodb update-table \
    --provisioned-throughput '{"ReadCapacityUnits":15,"WriteCapacityUnits":10}' \
    --table-name MyDDBTable
```

## 將檔案載入為速記語法值
<a name="shorthand-files"></a>

當值較大或複雜時，通常更容易載入做為值。若要將檔案載入為速記語法值，格式會稍微變更。不是 `key=value`，您將使用 `@=` 運算子，而非 `=` 運算子。`@=` 表示 AWS CLI 值應該讀取為檔案路徑，而不是字串。以速記語法載入檔案時，一般的 [AWS CLI 檔案格式規則適用](cli-usage-parameters-file.md)。下列範例會示範金鑰-值對如何為其值載入檔案。

------
#### [ Linux or macOS ]

```
--option key@=file://template.txt
```

------
#### [ Windows ]

```
--option "key1@=file://template.txt"
```

------

下列範例會示範為 `aws rolesanywhere create-trust-anchor` 命令載入憑證檔案。

```
$ aws rolesanywhere create-trust-anchor --name TrustAnchor \
    --source sourceData={x509CertificateData@=file://root-ca.crt},sourceType="CERTIFICATE_BUNDLE"  \ 
    --enabled
```

## 搭配 使用速記語法 AWS CLI
<a name="shorthand-list-parameters"></a>

您可以用兩種方式指定清單形式中的輸入參數：JSON 或速記。 AWS CLI 的速記語法易於傳入具有數字、字串或非巢狀結構的清單中。

基本格式如下所示，清單中的數值以單一空格分隔。

```
--option value1 value2 value3
```

這等同於下列 JSON 格式的範例。

```
--option '[value1,value2,value3]'
```

如同先前所述，您可以使用速記語法來指定數字清單、字串清單或非巢狀結構的清單。以下是 Amazon Elastic Compute Cloud (Amazon EC2) `stop-instances` 命令的範例，其中 `--instance-ids` 選項的輸入參數 (字串清單) 以速記語法指定。

```
$ aws ec2 stop-instances \
    --instance-ids i-1486157a i-1286157c i-ec3a7e87
```

這等同於下列 JSON 格式的範例。

```
$ aws ec2 stop-instances \
    --instance-ids '["i-1486157a","i-1286157c","i-ec3a7e87"]'
```

下列範例顯示 Amazon EC2 `create-tags` 命令，其中 `--tags` 選項採用非巢狀結構的清單。`--resources` 選項指定要標記之執行個體的 ID。

```
$ aws ec2 create-tags \
    --resources i-1286157c \
    --tags Key=My1stTag,Value=Value1 Key=My2ndTag,Value=Value2 Key=My3rdTag,Value=Value3
```

這等同於下列 JSON 格式的範例。為確保易讀性，JSON 參數以多行文字編寫。

```
$ aws ec2 create-tags \
    --resources i-1286157c \
    --tags '[
        {"Key": "My1stTag", "Value": "Value1"},
        {"Key": "My2ndTag", "Value": "Value2"},
        {"Key": "My3rdTag", "Value": "Value3"}
    ]'
```

# 在 中啟用和使用命令提示字元 AWS CLI
<a name="cli-usage-parameters-prompting"></a>

您可以在執行 命令時，讓 第 2 AWS CLI 版提示您命令、參數和資源`aws`。

**Topics**
+ [運作方式](#cli-usage-auto-prompt-about)
+ [自動提示功能](#cli-usage-auto-prompt-features)
+ [自動提示模式](#cli-usage-auto-prompt-modes)
+ [設定自動提示](#cli-usage-auto-prompt-configure)

## 運作方式
<a name="cli-usage-auto-prompt-about"></a>

啟用自動提示後，您可使用 **ENTER** 鍵來完成部分輸入的命令。按下 **ENTER** 鍵後，系統會根據您繼續輸入的內容來建議命令、參數和資源。建議會在左側列出命令、參數或資源的名稱，並在右側列出相關描述。若要選取並使用建議，請使用方向鍵來反白顯示該列，然後按下 **SPACE** 鍵。完成輸入命令後，按下 **ENTER** 來使用命令。以下範例呈現自動提示的建議清單。

```
$ aws
> aws a
       accessanalyzer                Access Analyzer
       acm                           AWS Certificate Manager
       acm-pca                       AWS Certificate Manager Private Certificate Authority
       alexaforbusiness              Alexa For Business
       amplify                       AWS Amplify
```

## 自動提示功能
<a name="cli-usage-auto-prompt-features"></a>

自動提示包含以下實用功能：

**文件面板**  
提供有關目前命令的說明文件。若要開啟文件，請按 **F3** 鍵。

**命令完成**  
建議可使用的 `aws` 命令。若要查看清單，請輸入命令的部分內容。以下範例是搜尋以字母 `a` 為開頭的服務。  

```
$ aws
> aws a
       accessanalyzer                Access Analyzer
       acm                           AWS Certificate Manager
       acm-pca                       AWS Certificate Manager Private Certificate Authority
       alexaforbusiness              Alexa For Business
       amplify                       AWS Amplify
```

**參數完成**  
您輸入命令後，自動提示功能會開始建議參數。參數的描述包括數值類型，以及有關參數內容的描述。首先會列出必要的參數，再按要求進行標記。以下範例顯示 `aws dynamodb describe-table` 的參數自動提示清單。  

```
$ aws dynamodb describe-table
> aws dynamodb describe-table 
                              --table-name (required)  [string] The name of the table to describe.
                               --cli-input-json         [string] Reads arguments from the JSON string provided. The JSON string follows the format provide...
                               --cli-input-yaml         [string] Reads arguments from the YAML string provided. The YAML string follows the format provide...
                               --generate-cli-skeleton  [string] Prints a JSON skeleton to standard output without sending an API request. If provided wit...
```

**資源完成**  
自動提示會使用可用的 AWS 資源屬性呼叫 AWS API 以建議資源數值。此會允許在輸入參數時，自動提示建議您擁有的潛在資源。在以下範例中，自動提示在您填入 `aws dynamodb describe-table` 命令的 `--table-name` 參數時列出表格名稱。  

```
$ aws dynamodb describe-table
> aws dynamodb describe-table --table-name 
                                            Table1
                                            Table2
                                            Table3
```

**速記完成**  
若為使用速記語法的參數，自動提示會建議要使用的數值。在下列範例中，自動提示會列出 `aws ec2 run-instances` 命令中 `--placement` 參數的速記語法數值。  

```
$ aws ec2 run-instances
> aws ec2 run-instances --placement 
 AvailabilityZone=      [string] The Availability Zone of the instance. If not specified, an Availability Zone wil...
 Affinity=              [string] The affinity setting for the instance on the Dedicated Host. This parameter is no...
 GroupName=             [string] The name of the placement group the instance is in.
 PartitionNumber=       [integer] The number of the partition the instance is in. Valid only if the placement grou...
```

**檔案完成**  
在 `aws` 命令中填入參數時，自動完成會在使用前綴 `file://` 或 `fileb://` 後建議本機檔案名稱。在以下範例中，在為 `aws ec2 run-instances` 命令輸入 `--item file://` 後，自動提示建議本機檔案。  

```
$ aws ec2 run-instances
> aws ec2 run-instances --item file:// 
                         item1.txt
                         file1.json
                         file2.json
```

**區域完成**  
在使用全域參數 `--region` 時，自動提示會列出可供選取的區域。下列範例示範為 `aws dynamodb list-tables` 命令輸入 `--region` 後，自動提示會建議以字母排序的區域。  

```
$ aws dynamodb list-tables
> aws dynamodb list-tables --region 
                                     af-south-1
                                     ap-east-1
                                     ap-northeast-1
                                     ap-northeast-2
```

**設定檔完成**  
在使用全域參數 `--profile` 時，自動提示會列出您的設定檔。下列範例示範為 `aws dynamodb list-tables` 命令輸入 `--profile` 後，自動提示會建議您的設定檔。  

```
$ aws dynamodb list-tables
> aws dynamodb list-tables --profile 
                                     profile1
                                     profile2
                                     profile3
```

**模糊搜尋**  
完成包含特定字元集的完整命令和數值。下列範例示範為 `eu` 命令輸入 `--region eu` 後，自動提示會建議包含 `aws dynamodb list-tables` 的區域。  

```
$ aws dynamodb list-tables
> aws dynamodb list-tables --region west
                                         eu-west-1
                                         eu-west-2
                                         eu-west-3
                                         us-west-1
```

**歷程記錄**  
若要在自動提示模式中檢視並執行先前使用的命令，請按 **CTRL \$1 R**。歷史記錄會列出先前用過的命令，您可以使用方向鍵進行選取。以下範例顯示自動提示模式中的歷史記錄。  

```
$ aws
> aws 
        dynamodb list-tables
        s3 ls
```

## 自動提示模式
<a name="cli-usage-auto-prompt-modes"></a>

第 2 AWS CLI 版的自動提示有 2 種可設定的模式：
+ **完整模式**：無論您使用 `--cli-auto-prompt` 參數手動呼叫或永久啟用命令，每次嘗試執行 `aws` 命令時都會使用自動提示。這包括在完整的命令或不完整的命令之後按下 **ENTER**。
+ **部分模式：**如果命令不完整或因用戶端驗證錯誤而無法執行時，使用自動提示。如果您有預先存在的指令碼、Runbook，或是您只希望系統自動提示您不熟悉的命令 (而非針對每個命令發出提示)，這個模式就特別有用。

## 設定自動提示
<a name="cli-usage-auto-prompt-configure"></a>

若要設定自動提示，您可以依優先順序使用下列方法：
+ **命令列選項**可用於啟用或停用單一命令的自動提示。使用 `--cli-auto-prompt` 可呼叫自動提示，使用 `--no-cli-auto-prompt` 則能停用自動提示。
+ **環境變數**使用 `aws\$1cli\$1auto\$1prompt` 變數。
+ **共享組態檔**使用 `cli\$1auto\$1prompt` 設定。

# 在 中控制命令輸出 AWS CLI
<a name="cli-usage-output"></a>

本節介紹控制 AWS Command Line Interface (AWS CLI) 輸出的不同方法。自訂終端機中的 AWS CLI 輸出可改善可讀性、簡化指令碼處理自動化，以及更輕鬆地導覽較大的資料集。

 AWS CLI 支援多種[輸出格式](cli-usage-output-format.md)，包括 [`json`](cli-usage-output-format.md#json-output)、[`text`](cli-usage-output-format.md#text-output)、[`off`](cli-usage-output-format.md#off-output)、 [`yaml`](cli-usage-output-format.md#yaml-output)和 [`table`](cli-usage-output-format.md#table-output)。有些服務的資料具有伺服器端[分頁](cli-usage-pagination.md)，而 為其他分頁選項 AWS CLI 提供自己的用戶端功能。

最後， AWS CLI 具有[伺服器端和用戶端篩選](cli-usage-filter.md)，您可以個別或一起使用來篩選 AWS CLI 輸出。

**Topics**
+ [敏感輸出](#cli-usage-output-sensitive)
+ [伺服器端與用戶端輸出選項](#cli-usage-output-server-client)
+ [在 中設定輸出格式 AWS CLI](cli-usage-output-format.md)
+ [中的結構化錯誤輸出 AWS CLI](cli-usage-error-format.md)
+ [使用 中的分頁選項 AWS CLI](cli-usage-pagination.md)
+ [在 中篩選輸出 AWS CLI](cli-usage-filter.md)

## 敏感輸出
<a name="cli-usage-output-sensitive"></a>

的某些操作 AWS CLI 可能會傳回可能被視為敏感的資訊，包括來自環境變數的資訊。此資訊的暴露在某些情況下可能代表安全風險；例如，資訊可能包含在持續整合和持續部署 (CI/CD) 日誌中。因此，當您將此類輸出作為日誌的一部分時，請務必進行審查，並在不需要時抑制輸出。

如需保護敏感資料的其他資訊，請參閱[中的資料保護 AWS CLI](data-protection.md)。

請考慮下列最佳實務：
+ 考慮以程式設計方式從秘密存放區擷取秘密，例如 AWS Secrets Manager。
+ 檢閱建置日誌的內容，確保其中未包含敏感資訊。考慮輸送到 `/dev/null` 或擷取輸出做為 bash 或 PowerShell 變數等方法來抑制命令輸出。

  以下是將輸出 (而非錯誤) 重新導向至 `/dev/null` 的 bash 範例：

  ```
  $ aws s3 ls > /dev/null
  ```

  如需抑制終端輸出的特定資訊，請參閱您所使用終端的使用者文件。
+ 考慮存取日誌，並根據使用案例適當調整存取範圍。

## 伺服器端與用戶端輸出選項
<a name="cli-usage-output-server-client"></a>

 AWS CLI 具有[伺服器端和用戶端篩選](cli-usage-filter.md)，您可以個別或一起使用來篩選 AWS CLI 輸出。系統會先處理伺服器端篩選，並傳回用戶端篩選的輸出。服務 API 支援伺服器端篩選。用戶端使用 `--query` 參數支援 AWS CLI 用戶端篩選。

**伺服器端**輸出選項是 AWS 服務 API 直接支援的功能。篩選或分頁的任何資料不會傳送至用戶端，這會加速 HTTP 回應時間，並改善較大資料集的頻寬。

**用戶端**輸出選項是由 AWS CLI建立的功能。所有資料都會傳送到用戶端，然後 AWS CLI 篩選或分頁顯示的內容。對於較大的資料集，用戶端操作不會節省速度或頻寬。

當伺服器端和用戶端選項一起使用時，會先完成伺服器端操作，然後傳送至用戶端以進行用戶端操作。這會使用伺服器端選項的潛在速度和省下的頻寬，同時使用其他 AWS CLI 功能來取得所需的輸出。

# 在 中設定輸出格式 AWS CLI
<a name="cli-usage-output-format"></a>

本主題說明 AWS Command Line Interface () 的不同輸出格式AWS CLI。 AWS CLI 支援以下輸出格式：
+ **[`json`](#json-output)** – 輸出的格式為 [JSON](https://json.org/) 字串。
+  **[`yaml`](#yaml-output)** – 輸出的格式為 [YAML](https://yaml.org/) 字串。
+ **[`yaml-stream`](#yaml-stream-output)** – 輸出採用串流方式且格式為 [YAML](https://yaml.org/) 字串。串流可加速處理大型資料類型。
+ **[`text`](#text-output)** – 輸出的格式是多行以 Tab 分隔的字串值。這對於將輸出傳遞給文字處理器 (如 `grep`、`sed` 或 `awk`) 非常有用。
+ **[`table`](#table-output)** – 輸出的格式為使用字元 \$1\$1- 形成儲存格框線的表格。它通常以「方便人類使用」的格式來呈現資訊，這種格式比其他格式更容易閱讀，但在編寫程式方面較不有用。
+ **[`off`](#off-output)** – 輸出會隱藏 stdout 的所有命令輸出。這在自動化指令碼和 CI/CD 管道中非常有用，您只需檢查命令的結束程式碼，而無需處理輸出。

## 如何選擇輸出格式
<a name="cli-usage-output-format-how"></a>

如同[組態](cli-chap-configure.md)主題所說明，您可以用三種方式來指定輸出格式：
+ **使用 `config` 檔案具名設定檔中的 `output` 選項** – 下列範例將預設輸出格式設定為 `text`。

  ```
  [default]
  output=text
  ```
+ **使用 `AWS_DEFAULT_OUTPUT` 環境變數** – 以下輸出會將此命令列工作階段中的命令格式設定為 `table`，直到變數變更或工作階段結束為止。使用此環境變數覆寫 `config` 檔案中設定的任何數值。

  ```
  $ export AWS_DEFAULT_OUTPUT="table"
  ```
+ **在命令列使用 `--output` 選項** – 以下範例僅將這個命令的輸出設定為 `json`。在命令列上使用此選項會覆寫任何目前設定的環境變數或 `config` 檔案中的數值。

  ```
  $ aws swf list-domains --registration-status REGISTERED --output json
  ```

**重要**  
您指定的輸出類型會影響 `--query` 選項的運作方式：  
如果您指定 `--output text`，輸出會在套用`--query`篩選條件*之前*進行分頁，而 會在輸出*的每個頁面上* AWS CLI 執行一次查詢。因此，查詢會包含每個頁面上第一個相符的要素，即會導致意外額外輸出的要素。若要額外篩選輸出，您可以使用其他命令列工具，例如 `head` 或 `tail`。
如果您指定 `--output json`、 `--output yaml` 或 `--output yaml-stream`，系統就會將輸出完全處理為單一原生結構後，才套用 `--query` 篩選條件。只會針對整個結構 AWS CLI 執行一次查詢，產生篩選結果，然後輸出。

## JSON 輸出格式
<a name="json-output"></a>

[JSON](https://json.org) 為 AWS CLI的預設輸出格式。大部分程式設計語言可以使用內建功能或開放使用的資料庫，來輕易解碼 JSON 字串。您可以使用強大的方法來結合 JSON 輸出與 [--query 選項](cli-usage-filter.md)，以篩選和格式化 AWS CLI JSON 格式的輸出。

您可能無法使用 `--query` 進行更進階的篩選，您可以考慮 `jq`，JSON 處理器的命令列。您可以前往下列網址下載並取得官方教學課程 [http://stedolan.github.io/jq/](http://stedolan.github.io/jq/)。

以下為 JSON 輸出的範例。

```
$ aws iam list-users --output json
```

```
{
    "Users": [
        {
            "Path": "/",
            "UserName": "Admin",
            "UserId": "AIDA1111111111EXAMPLE",
            "Arn": "arn:aws:iam::123456789012:user/Admin",
            "CreateDate": "2014-10-16T16:03:09+00:00",
            "PasswordLastUsed": "2016-06-03T18:37:29+00:00"
        },
        {
            "Path": "/backup/",
            "UserName": "backup-user",
            "UserId": "AIDA2222222222EXAMPLE",
            "Arn": "arn:aws:iam::123456789012:user/backup/backup-user",
            "CreateDate": "2019-09-17T19:30:40+00:00"
        },
        {
            "Path": "/",
            "UserName": "cli-user",
            "UserId": "AIDA3333333333EXAMPLE",
            "Arn": "arn:aws:iam::123456789012:user/cli-user",
            "CreateDate": "2019-09-17T19:11:39+00:00"
        }
    ]
}
```

## YAML 輸出格式
<a name="yaml-output"></a>

[YAML](https://yaml.org) 是使用發出或消耗 [YAML](https://yaml.org) 格式字串的服務和工具以程式設計方式處理輸出的好選擇，例如 CloudFormation 支援 [YAML 格式的範本](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-formats.html)。

您可能無法使用 `--query` 進行更進階的篩選，您可以考慮 `yq`，YAML 處理器的命令列。您可以在 *GitHub* 上的 [yq 存儲庫](https://github.com/mikefarah/yq)中下載 `yq`。

以下為 YAML 輸出的範例。

```
$ aws iam list-users --output yaml
```

```
Users:
- Arn: arn:aws:iam::123456789012:user/Admin
  CreateDate: '2014-10-16T16:03:09+00:00'
  PasswordLastUsed: '2016-06-03T18:37:29+00:00'
  Path: /
  UserId: AIDA1111111111EXAMPLE
  UserName: Admin
- Arn: arn:aws:iam::123456789012:user/backup/backup-user
  CreateDate: '2019-09-17T19:30:40+00:00'
  Path: /backup/
  UserId: AIDA2222222222EXAMPLE
  UserName: arq-45EFD6D1-CE56-459B-B39F-F9C1F78FBE19
- Arn: arn:aws:iam::123456789012:user/cli-user
  CreateDate: '2019-09-17T19:30:40+00:00'
  Path: /
  UserId: AIDA3333333333EXAMPLE
  UserName: cli-user
```

## YAML 串流輸出格式
<a name="yaml-stream-output"></a>

`yaml-stream` 格式會利用 [YAML](https://yaml.org) 格式，並同時透過將資料串流傳輸給您，提供更能回應/更快的大型資料集檢視功能。您可以先開始檢視和使用 YAML 資料，再下載整體查詢。

您可能無法使用 `--query` 進行更進階的篩選，您可以考慮 `yq`，YAML 處理器的命令列。您可以在 *GitHub* 上的 [yq 存儲庫](https://github.com/mikefarah/yq)中下載 `yq`。

以下為 `yaml-stream` 輸出範例。

```
$ aws iam list-users --output yaml-stream
```

```
- IsTruncated: false
  Users:
  - Arn: arn:aws:iam::123456789012:user/Admin
    CreateDate: '2014-10-16T16:03:09+00:00'
    PasswordLastUsed: '2016-06-03T18:37:29+00:00'
    Path: /
    UserId: AIDA1111111111EXAMPLE
    UserName: Admin
  - Arn: arn:aws:iam::123456789012:user/backup/backup-user
    CreateDate: '2019-09-17T19:30:40+00:00'
    Path: /backup/
    UserId: AIDA2222222222EXAMPLE
    UserName: arq-45EFD6D1-CE56-459B-B39F-F9C1F78FBE19
  - Arn: arn:aws:iam::123456789012:user/cli-user
    CreateDate: '2019-09-17T19:30:40+00:00'
    Path: /
    UserId: AIDA3333333333EXAMPLE
    UserName: cli-user
```

以下是 `yaml-stream` 輸出搭配使用 `--page-size` 參數對串流的 YAML 內容進行分頁的範例。

```
$ aws iam list-users --output yaml-stream --page-size 2
```

```
- IsTruncated: true
  Marker: ab1234cdef5ghi67jk8lmo9p/q012rs3t445uv6789w0x1y2z/345a6b78c9d00/1efgh234ij56klmno78pqrstu90vwxyx  
  Users:
  - Arn: arn:aws:iam::123456789012:user/Admin
    CreateDate: '2014-10-16T16:03:09+00:00'
    PasswordLastUsed: '2016-06-03T18:37:29+00:00'
    Path: /
    UserId: AIDA1111111111EXAMPLE
    UserName: Admin
  - Arn: arn:aws:iam::123456789012:user/backup/backup-user
    CreateDate: '2019-09-17T19:30:40+00:00'
    Path: /backup/
    UserId: AIDA2222222222EXAMPLE
    UserName: arq-45EFD6D1-CE56-459B-B39F-F9C1F78FBE19
- IsTruncated: false
  Users:
  - Arn: arn:aws:iam::123456789012:user/cli-user
    CreateDate: '2019-09-17T19:30:40+00:00'
    Path: /
    UserId: AIDA3333333333EXAMPLE
    UserName: cli-user
```

## 文字輸出格式
<a name="text-output"></a>

`text` 格式會將 AWS CLI 輸出組織成以標籤分隔的行。這很適合用於傳統 Unix 文字工具 (例如 `grep`、`sed` 和 `awk`)，和 PowerShell 執行的文字處理。

`text` 輸出格式依據基本結構，如下所示。欄位依據底層 JSON 物件之對應金鑰名稱的字母排序。

```
IDENTIFIER  sorted-column1 sorted-column2
IDENTIFIER2 sorted-column1 sorted-column2
```

以下為 `text` 輸出範例。每個的標籤都與其他欄位獨立，空的欄位則會有額外的標籤。

```
$ aws iam list-users --output text
```

```
USERS   arn:aws:iam::123456789012:user/Admin                2014-10-16T16:03:09+00:00   2016-06-03T18:37:29+00:00   /          AIDA1111111111EXAMPLE   Admin
USERS   arn:aws:iam::123456789012:user/backup/backup-user   2019-09-17T19:30:40+00:00                               /backup/   AIDA2222222222EXAMPLE   backup-user
USERS   arn:aws:iam::123456789012:user/cli-user             2019-09-17T19:11:39+00:00                               /          AIDA3333333333EXAMPLE   cli-user
```

第四欄位為 `PasswordLastUsed` 欄位，且最後兩個項目是空的，因為該使用者永遠不會登入 AWS 管理主控台。

**重要**  
*我們強烈建議指定 `text` 輸出時，一律使用 [`--query`](cli-usage-filter.md) 選項以確保一致的行為*。  
這是因為文字格式會依 AWS 服務傳回的基礎 JSON 物件金鑰名稱，依字母順序排序輸出資料欄，而類似的資源可能沒有相同的金鑰名稱。例如，Linux 型 Amazon EC2 執行個體的 JSON 表示法，可能具有 Windows 型執行個體之 JSON 表示法中不存在的元素，反之亦然。此外，資源在未來更新中可能會新增或移除鍵值元素，並改變欄位順序。`--query` 在此處擴大 `text` 輸出的功能，以讓您完全控制輸出格式。  
在下列範例中，命令指定了要顯示的元素，並使用清單表示法 `[key1, key2, ...]` 來*定義欄位順序*。如此可讓您充分信賴預期的欄位永遠都會顯示正確的鍵值。最後，請注意 AWS CLI 輸出如何`None`作為不存在金鑰的值。  

```
$ aws iam list-users --output text --query 'Users[*].[UserName,Arn,CreateDate,PasswordLastUsed,UserId]'
```

```
Admin         arn:aws:iam::123456789012:user/Admin         2014-10-16T16:03:09+00:00   2016-06-03T18:37:29+00:00   AIDA1111111111EXAMPLE
backup-user   arn:aws:iam::123456789012:user/backup-user   2019-09-17T19:30:40+00:00   None                        AIDA2222222222EXAMPLE
cli-user      arn:aws:iam::123456789012:user/cli-backup    2019-09-17T19:11:39+00:00   None                        AIDA3333333333EXAMPLE
```

以下範例顯示如何使用 `grep` 和 `awk` 搭配來自 `aws ec2 describe-instances` 命令的 `text` 輸出。第一個命令顯示可用區域、目前狀態，以及 `text` 輸出中每個執行個體的執行個體 ID。第二個命令處理該輸出以僅顯示 `us-west-2a` 可用區域內所有執行中執行個體的執行個體 ID。

```
$ aws ec2 describe-instances --query 'Reservations[*].Instances[*].[Placement.AvailabilityZone, State.Name, InstanceId]' --output text
```

```
us-west-2a      running i-4b41a37c
us-west-2a      stopped i-a071c394
us-west-2b      stopped i-97a217a0
us-west-2a      running i-3045b007
us-west-2a      running i-6fc67758
```

```
$ aws ec2 describe-instances --query 'Reservations[*].Instances[*].[Placement.AvailabilityZone, State.Name, InstanceId]' --output text | grep us-west-2a | grep running | awk '{print $3}'
```

```
i-4b41a37c
i-3045b007
i-6fc67758
```

以下範例更進一步，不僅顯示如何篩選輸出，也顯示如何使用該輸出來自動變更每個已停止執行個體的執行個體類型。

```
$ aws ec2 describe-instances --query 'Reservations[*].Instances[*].[State.Name, InstanceId]' --output text |
> grep stopped |
> awk '{print $2}' |
> while read line;
> do aws ec2 modify-instance-attribute --instance-id $line --instance-type '{"Value": "m1.medium"}';
> done
```

`text` 輸出在 PowerShell 也相當實用。由於 `text` 輸出中的欄以 Tab 鍵分隔，因此您可以使用 PowerShell 的 ``t` 分隔符號輕鬆將輸出分割為陣列。下列命令可在第一欄位 (`InstanceId`) 符合字串 `AvailabilityZone` 的情況下，顯示第三欄位中的數值 (`us-west-2a`)。

```
PS C:\>aws ec2 describe-instances --query 'Reservations[*].Instances[*].[Placement.AvailabilityZone, State.Name, InstanceId]' --output text |
%{if ($_.split("`t")[0] -match "us-west-2a") { $_.split("`t")[2]; } }
```

```
-4b41a37c
i-a071c394
i-3045b007
i-6fc67758
```

請注意，雖然先前的範例已示範如何使用 `--query` 參數來剖析基礎 JSON 物件並提取所需的欄，但 PowerShell 有自己處理 JSON 的能力，當您無須擔心跨平台相容性時，即可使用。PowerShell 可讓您使用 `ConvertFrom-JSON` cmdlet 產生階層結構化物件，而非以文字形式處理輸出。然後，您可以直接從該物件存取您想要的成員。

```
(aws ec2 describe-instances --output json | ConvertFrom-Json).Reservations.Instances.InstanceId
```

**提示**  
如果您輸出文字並使用 `--query` 參數將輸出篩選為單一欄位，則輸出會是單行標籤分隔值。若要將每個數值放在單獨的行上，您可以用括弧括住輸出欄位，如下列範例所示。  
Tab 分隔的單行輸出：  

```
$ aws iam list-groups-for-user --user-name susan  --output text --query "Groups[].GroupName"
```

```
HRDepartment    Developers      SpreadsheetUsers  LocalAdmins
```
將 `[GroupName]` 放在括弧中，每個數值都在單獨一行上：  

```
$ aws iam list-groups-for-user --user-name susan  --output text --query "Groups[].[GroupName]"
```

```
HRDepartment
Developers
SpreadsheetUsers
LocalAdmins
```

## 表格輸出格式
<a name="table-output"></a>

`table` 格式能對複雜的 AWS CLI 輸出以表格形式產生易讀形式。

```
$ aws iam list-users --output table
```

```
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
|                                                                                 ListUsers                                                                     |
+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
||                                                                                  Users                                                                      ||
|+----------------------------------------------------+---------------------------+---------------------------+----------+-----------------------+-------------+|
||                         Arn                        |       CreateDate          |    PasswordLastUsed       |   Path   |        UserId         |   UserName  ||
|+----------------------------------------------------+---------------------------+---------------------------+----------+-----------------------+-------------+|
||  arn:aws:iam::123456789012:user/Admin              | 2014-10-16T16:03:09+00:00 | 2016-06-03T18:37:29+00:00 | /        | AIDA1111111111EXAMPLE | Admin       ||
||  arn:aws:iam::123456789012:user/backup/backup-user | 2019-09-17T19:30:40+00:00 |                           | /backup/ | AIDA2222222222EXAMPLE | backup-user ||
||  arn:aws:iam::123456789012:user/cli-user           | 2019-09-17T19:11:39+00:00 |                           | /        | AIDA3333333333EXAMPLE | cli-user    ||
+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
```

您可將 `--query` 選項與 `table` 格式結合使用，以顯示從列輸出中預選的元素組。請留意字典表示法和清單表示法之間的輸出差異：在第一個範例中，欄位名稱以字母順序排序；在第二個範例中，未命名欄位則根據使用者定義來排序。如需有關 `--query` 選項的詳細資訊，請參閱 [在 中篩選輸出 AWS CLI](cli-usage-filter.md)。

```
$ aws ec2 describe-volumes --query 'Volumes[*].{ID:VolumeId,InstanceId:Attachments[0].InstanceId,AZ:AvailabilityZone,Size:Size}' --output table
```

```
------------------------------------------------------
|                   DescribeVolumes                  | 
+------------+----------------+--------------+-------+
|     AZ     |      ID        | InstanceId   | Size  |
+------------+----------------+--------------+-------+
|  us-west-2a|  vol-e11a5288  |  i-a071c394  |  30   |
|  us-west-2a|  vol-2e410a47  |  i-4b41a37c  |  8    |
+------------+----------------+--------------+-------+
```

```
$ aws ec2 describe-volumes --query 'Volumes[*].[VolumeId,Attachments[0].InstanceId,AvailabilityZone,Size]' --output table
```

```
----------------------------------------------------
|                  DescribeVolumes                 |
+--------------+--------------+--------------+-----+
|  vol-e11a5288|  i-a071c394  |  us-west-2a  |  30 |
|  vol-2e410a47|  i-4b41a37c  |  us-west-2a  |  8  |
+--------------+--------------+--------------+-----+
```

## 關閉輸出格式
<a name="off-output"></a>

`off` 格式會隱藏 stdout 的所有命令輸出。這在自動化指令碼和 CI/CD 管道中非常有用，您只需檢查命令的結束程式碼，而無需處理輸出。錯誤訊息仍會顯示在 stderr 上。

下列範例顯示 `off` 格式如何抑制成功輸出。您可以檢查結束程式碼以判斷成功：

```
$ aws s3api list-buckets --output off
$ echo $?
0
```

這在您要驗證資源是否存在而不擷取輸出的 shell 指令碼中特別有用：

```
#!/bin/bash
if aws s3api head-bucket --bucket my-bucket --output off 2>/dev/null; then
    echo "Bucket exists"
else
    echo "Bucket does not exist"
fi
```

**注意**  
`off` 格式只會抑制 stdout。錯誤仍會寫入 stderr。

# 中的結構化錯誤輸出 AWS CLI
<a name="cli-usage-error-format"></a>

本主題說明 AWS Command Line Interface () 的結構化錯誤輸出格式AWS CLI。CLI 會將錯誤寫入 stderr，並支援下列格式：
+ **[`enhanced`](#cli-error-format-enhanced)** （預設） – 顯示內嵌其他詳細資訊的錯誤訊息。用於人類可讀取偵錯。
+ **[`json`](#cli-error-format-json)** – 輸出格式為包含所有錯誤欄位的 [JSON](https://json.org/) 字串。使用 進行自動化和指令碼編寫。
+ **[`yaml`](#cli-error-format-yaml)** – 輸出會格式化為包含所有錯誤欄位的 [YAML](https://yaml.org/) 字串。使用 進行自動化和指令碼編寫。
+ **[`text`](#cli-error-format-text)** – 使用文字格式化器格式化錯誤。使用 進行快速視覺化掃描。
+ **[`table`](#cli-error-format-table)** – 使用資料表格式化器格式化錯誤。使用 進行快速視覺化掃描。
+ **[`legacy`](#cli-error-format-legacy)** – 沒有結構化詳細資訊的原始錯誤格式。使用 實現回溯相容性。

## 設定錯誤格式
<a name="cli-error-format-configuring"></a>

您可以使用下列任一方法設定錯誤格式：

命令列旗標  

```
$ aws <command> --cli-error-format json
```

組態檔案 (`~/.aws/config`)  

```
[default]
cli_error_format = json
```

環境變數  

```
$ export AWS_CLI_ERROR_FORMAT=yaml
```

## 錯誤輸出格式
<a name="cli-error-output-formats"></a>

下列各節說明每種格式：

### 增強型格式 （預設）
<a name="cli-error-format-enhanced"></a>

增強型格式會顯示錯誤訊息，其中包含簡單值的其他詳細資訊內嵌。對於複雜的結構， 格式會提供使用 JSON 或 YAML 的提示。

**範例：缺少區域組態**

```
aws: [ERROR]: An error occurred (NoRegion): You must specify a region. You can also configure your region by running "aws configure".
```

**範例：不存在的 Lambda 函數與其他欄位**

```
aws: [ERROR]: An error occurred (ResourceNotFoundException) when calling the GetFunction operation: Function not found: arn:aws:lambda:us-west-2:123456789012:function:nonexistent-function-12345

Additional error details:
Type: User
```

「其他錯誤詳細資訊」區段只會顯示服務錯誤形狀模型中定義的欄位。不會顯示來自錯誤回應的未建模欄位。

**範例：複雜錯誤欄位**

```
An error occurred (TransactionCanceledException) when calling the TransactWriteItems operation: Transaction cancelled, please refer cancellation reasons for specific reasons [ConditionalCheckFailed, None]

Additional error details:
CancellationReasons: <complex value>
Use "--cli-error-format json" or another error format to see the full details.
```

### JSON format (JSON 格式)
<a name="cli-error-format-json"></a>

JSON 格式提供包含所有錯誤欄位的結構化表示。

**範例：缺少區域組態**

```
{
    "Code": "NoRegion",
    "Message": "You must specify a region. You can also configure your region by running \"aws configure\"."
}
```

**範例：不存在的 Lambda 函數**

```
{
    "Code": "ResourceNotFoundException",
    "Message": "Function not found: arn:aws:lambda:us-west-2:123456789012:function:nonexistent-function-12345",
    "Type": "User"
}
```

### YAML 格式
<a name="cli-error-format-yaml"></a>

YAML 格式提供包含所有錯誤欄位的結構化表示。

**範例：缺少區域組態**

```
Code: NoRegion
Message: You must specify a region. You can also configure your region by running "aws configure".
```

**範例：不存在的 Lambda 函數**

```
Code: ResourceNotFoundException
Message: "Function not found: arn:aws:lambda:us-west-2:123456789012:function:nonexistent-function-12345"
Type: User
```

### 文字格式
<a name="cli-error-format-text"></a>

文字格式使用與成功命令輸出相同的格式器。

**範例：不存在的 Lambda 函數**

```
ResourceNotFoundException    Function not found: arn:aws:lambda:us-west-2:123456789012:function:nonexistent-function-12345    User
```

### 資料表格式
<a name="cli-error-format-table"></a>

資料表格式使用與成功命令輸出相同的格式器。

**範例：不存在的 Lambda 函數**

```
------------------------------------------------------------------------------------------------------------------------------------|
|                                                              error                                                                 |
+----------------------------+--------------------------------------------------------------------------------------------------+------+
|            Code            |                              Message                                                             | Type |
+----------------------------+--------------------------------------------------------------------------------------------------+------+
|  ResourceNotFoundException |  Function not found: arn:aws:lambda:us-west-2:123456789012:function:nonexistent-function-12345   | User |
+----------------------------+--------------------------------------------------------------------------------------------------+------+
```

### 舊版格式
<a name="cli-error-format-legacy"></a>

舊版格式提供不含結構化詳細資訊的原始錯誤格式。此格式不包含 CLI 例外狀況的「發生錯誤 (ErrorCode)：」字首。

**範例：缺少區域組態**

```
aws: [ERROR]: You must specify a region. You can also configure your region by running "aws configure".
```

**範例：不存在的 Lambda 函數**

```
An error occurred (ResourceNotFoundException) when calling the GetFunction operation: Function not found: arn:aws:lambda:us-west-2:123456789012:function:nonexistent-function-12345
```

**注意**  
錯誤現在會持續包含 CLI 例外狀況的`aws: [ERROR]:`字首。舊版不一定包含此字首。  
無論設定的錯誤格式為何，下列例外一律使用舊版格式：  
`UnknownArgumentError` – 顯示用量資訊
鍵盤中斷 (`KeyboardInterrupt`)

## 完成範例
<a name="cli-error-format-example"></a>

下列範例顯示具有 JSON 錯誤格式的命令：

```
$ aws lambda get-function \
    --function-name nonexistent-function-12345 \
    --cli-error-format json
```

輸出 (stderr)：

```
{
    "Code": "ResourceNotFoundException",
    "Message": "Function not found: arn:aws:lambda:us-west-2:123456789012:function:nonexistent-function-12345",
    "Type": "User"
}
```

`Type` 欄位是 Lambda 服務錯誤形狀中定義的模型化錯誤成員。只有服務錯誤模型中定義的欄位才會包含在結構化錯誤輸出中。

# 使用 中的分頁選項 AWS CLI
<a name="cli-usage-pagination"></a>

本主題說明從 AWS Command Line Interface () 分頁輸出的不同方式AWS CLI。

主要有兩種方法來控制 AWS CLI輸出的分頁。
+ [使用伺服器端的分頁參數。](#cli-usage-pagination-serverside)
+ [使用您的預設輸出用戶端分頁程式](#cli-usage-pagination-clientside)。

伺服器端分頁參數先處理，然後所有輸出都傳送到用戶端分頁。

## 伺服器端分頁
<a name="cli-usage-pagination-serverside"></a>

對於傳回大量項目清單的大多數命令， AWS CLI 具有多個伺服器端選項，可在 AWS CLI 呼叫服務的 API 填入清單時控制輸出中包含的項目數量。中的伺服器端分頁由 AWS 服務 API AWS CLI 啟用，因此這些選項只有在服務 API 啟用時才有效。

**Topics**
+ [--no-paginate](#cli-usage-pagination-nopaginate)
+ [--page-size](#cli-usage-pagination-pagesize)
+ [--max-items](#cli-usage-pagination-maxitems)
+ [--starting-token](#cli-usage-pagination-startingtoken)

根據預設， AWS CLI 會使用由個別服務決定的頁面大小，並擷取所有可用的項目。例如，Amazon S3 的預設頁面大小為 1000。例如，如果您在包含 3,500 個物件的 Amazon S3 儲存貯體上執行 `aws s3api list-objects`， AWS CLI 會自動對 Amazon S3 進行 4 次呼叫、在背景為您處理服務特定的分頁邏輯，並在最終輸出中傳回全部 3,500 個物件。

如需有關特定命令是否具有伺服器端分頁的資訊，請參閱第 [AWS CLI 2 版參考指南](https://docs.aws.amazon.com/cli/latest/reference/index.html)。

### 如何使用 --no-paginate 參數
<a name="cli-usage-pagination-nopaginate"></a>

`--no-paginate` 選項在客户端停用以下分頁標記。使用命令時， 預設 AWS CLI 會自動進行多次呼叫，以傳回所有可能的結果來建立分頁。每個頁面一個呼叫。停用分頁對於命令結果的第一頁 AWS CLI 只有一次呼叫。

例如，如果您在包含 3，500 個物件的 Amazon S3 儲存貯體`aws s3api list-objects`上執行 ，則 AWS CLI 只會對 Amazon S3 進行第一次呼叫，並在最終輸出中僅傳回前 1，000 個物件。

```
$ aws s3api list-objects \
    --bucket amzn-s3-demo-bucket \
    --no-paginate
{
    "Contents": [
...
```

### 如何使用 --page-size 參數
<a name="cli-usage-pagination-pagesize"></a>

如果您在針對大量資源執行清單命令時發生問題，可能是預設頁面大小太高。這可能會導致對 AWS 服務的呼叫超過允許的時間上限，並產生「逾時」錯誤。您可以使用 `--page-size`選項來指定從每次呼叫服務 AWS CLI 請求較少數量的項目 AWS 。 AWS CLI 仍會擷取完整清單，但在背景執行更多數量的服務 API 呼叫，並在每次呼叫時擷取較少數量的項目。這可讓每次呼叫不逾時的成功機會更高。變更頁面大小不會影響輸出；它只會影響產生輸出所需進行的 API 呼叫數量。

```
$ aws s3api list-objects \
    --bucket amzn-s3-demo-bucket \
    --page-size 100
{
    "Contents": [
...
```

### 如何使用 --max-items 參數
<a name="cli-usage-pagination-maxitems"></a>

若要一次在 AWS CLI 輸出中包含較少的項目，請使用 `--max-items`選項。 AWS CLI 仍會如先前所述使用 服務處理分頁，但一次只會列印您指定的項目數量。

```
$ aws s3api list-objects \
    --bucket amzn-s3-demo-bucket \
    --max-items 100
{
    "NextToken": "eyJNYXJrZXIiOiBudWxsLCAiYm90b190cnVuY2F0ZV9hbW91bnQiOiAxfQ==",
    "Contents": [
...
```

### 如何使用 --starting-token 參數
<a name="cli-usage-pagination-startingtoken"></a>

如果項目輸出數量 (`--max-items`) 少於基礎 API 呼叫傳回的項目總數，則輸出會包含一個 `NextToken`，提供您在後續命令中傳送以擷取下一組項目。以下範例說明如何使用前一範例傳回的 `NextToken` 值，並讓您擷取第二批的 100 個項目。

**注意**  
參數 `--starting-token` 不能為 null 或空白。如果先前的命令未傳回 `NextToken` 值，表示已沒有更多項目可傳回，您也不需要再次呼叫命令。

```
$ aws s3api list-objects \
    --bucket amzn-s3-demo-bucket \
    --max-items 100 \
    --starting-token eyJNYXJrZXIiOiBudWxsLCAiYm90b190cnVuY2F0ZV9hbW91bnQiOiAxfQ==
{
    "Contents": [
...
```

每次呼叫 時，指定的 AWS 服務可能不會以相同的順序傳回項目。如果您為 `--page-size` 和 `--max-items` 指定不同的數值，您可能會取得意外的結果，並發生遺漏或重複的項目。欲避免此情況，請對 `--page-size` 和 `--max-items` 使用相同數字，以同步 AWS CLI 和基礎服務的分頁。您亦可擷取整個清單，並於本機執行所需的分頁操作。

## 用戶端分頁程式
<a name="cli-usage-pagination-clientside"></a>

AWS CLI 第 2 版提供使用用戶端分頁程式進行輸出。根據預設，此功能會透過作業系統的預設分頁程式傳回所有輸出。

依據優先順序，您可以使用以下方式指定輸出分頁程式：
+ 使用 `default` 或具名設定檔內 `config` 檔案中的 `cli_pager` 設定。
+ 使用 `AWS_PAGER` 環境變數。
+ 使用 `PAGER` 環境變數。

依優先順序，您可以透過下列方式停用所有對外部分頁程式的使用：
+ 使用 `--no-cli-pager` 命令列選項停用單一命令使用的分頁程式。
+ 將 `cli_pager` 設定或 `AWS_PAGER` 變數設為空白字串。

**Topics**
+ [cli\$1pager](#cli-usage-pagination-clipager)
+ [AWS\$1PAGER](#cli-usage-pagination-awspager)
+ [--no-cli-pager](#cli-usage-pagination-noclipager)
+ [分頁程式標記](#cli-usage-pagination-flags)

### 如何使用 cli\$1pager 設定
<a name="cli-usage-pagination-clipager"></a>

您可以將常用的組態設定和憑證儲存在 AWS CLI維護的檔案中。具名設定檔內的設定優先於 `default` 設定檔內的設定。如需組態設定的詳細資訊，請參閱 [中的組態和登入資料檔案設定 AWS CLI](cli-configure-files.md)。

以下範例設定預設的輸出分頁程式至 `less` 程式。

```
[default]
cli_pager=less
```

下列範例會將預設值設定為停用分頁程式。

```
[default]
cli_pager=
```



### 如何設定 AWS\$1PAGER 環境變數
<a name="cli-usage-pagination-awspager"></a>

以下範例設定預設的輸出分頁程式至 `less` 程式。如需有關環境變數的詳細資訊，請參閱 [設定 的環境變數 AWS CLI](cli-configure-envvars.md)。

------
#### [ Linux and macOS ]

```
$ export AWS_PAGER="less"
```

------
#### [ Windows ]

```
C:\> setx AWS_PAGER "less"
```

------

### 如何使用 --no-cli-pager 選項
<a name="cli-usage-pagination-noclipager"></a>

若要停用單一命令對呼叫程式的使用，請使用 `--no-cli-pager` 選項。如需命令列選項的詳細資訊，請參閱 [中的命令列選項 AWS CLI](cli-configure-options.md)。

```
$ aws s3api list-objects \
    --bucket amzn-s3-demo-bucket \
    --no-cli-pager
{
    "Contents": [
...
```

### 如何使用分頁程式標記
<a name="cli-usage-pagination-flags"></a>

您可以指定要自動與分頁程式搭配使用的標記。標記是依您使用的分頁程式而定。以下範例是 `less` 和 `more` 的典型預設內容。

------
#### [ Linux and macOS ]

如果您未另外指定，分頁器第 2 AWS CLI 版預設使用 `less`。如果您沒有設定`LESS`環境變數，第 2 AWS CLI 版會使用 `FRX`旗標。您可以在設定 AWS CLI 分頁器時指定旗標，以結合旗標。

下列範例使用 `S` 標記。然後，此標誌會與預設的 `FRX` 標誌合併，以建立最終 `FRXS` 標記。

```
$ export AWS_PAGER="less -S"
```

如果您不希望有任何 `FRX` 標記，可將其否定。以下範例會否定 `F` 標記以建立最終 `RX` 標記。

```
$ export AWS_PAGER="less -+F"
```

如需 `less` 的詳細資訊，請參閱 *manpages.org* 上的 [less](http://manpages.org/less/1#options)。

------
#### [ Windows ]

如果您未另外指定，分頁器 AWS CLI 版本 2 預設會使用 `more`，沒有額外的旗標。

下列範例會使用 `/c` 參數。

```
C:\> setx AWS_PAGER "more /c"
```

如需 `more` 旗標的詳細資訊，請參閱 *Microsoft Docs* 的 `[more](https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/more)`。

------

# 在 中篩選輸出 AWS CLI
<a name="cli-usage-filter"></a>

 AWS Command Line Interface (AWS CLI) 具有伺服器端和用戶端篩選，您可以個別或一起使用來篩選 AWS CLI 輸出。系統會先處理伺服器端篩選，並傳回用戶端篩選的輸出。
+ 伺服器端篩選受 API 支援，且您通常會搭配 `--filter` 參數執行該篩選。服務僅會傳回符合的結果，即可加速大型資料集的 HTTP 回應時間之結果。
+ 用戶端使用 `--query` 參數支援 AWS CLI 用戶端篩選。此參數具有伺服器端篩選可能沒有的功能。

**Topics**
+ [伺服器端篩選](#cli-usage-filter-server-side)
+ [用戶端篩選](#cli-usage-filter-client-side)
+ [結合伺服器端和用戶端篩選](#cli-usage-filter-combining)
+ [其他資源](#cli-usage-filter-resources)

## 伺服器端篩選
<a name="cli-usage-filter-server-side"></a>

中的伺服器端篩選由 AWS 服務 API AWS CLI 提供。 AWS 服務僅會傳回符合您篩選條件 HTTP 回應中的記錄，其可加速大型資料集的 HTTP 回應時間。由於伺服器端篩選是由服務 API 定義，參數名稱和函數會因服務而異。部分用於篩選的常見參數名稱有：
+ `--filter` 例如 [ses](https://docs.aws.amazon.com/cli/latest/reference/ses/create-receipt-filter.html) 和 [ce](https://docs.aws.amazon.com/cli/latest/reference/ce/get-cost-and-usage.html)。
+ `--filters` 例如 [ec2](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-volumes.html)、[autoscaling](https://docs.aws.amazon.com/cli/latest/reference/autoscaling/describe-tags.html) 和 [rds](https://docs.aws.amazon.com/cli/latest/reference/rds/describe-db-instances.html)。
+ 以單字 `filter` 開頭來命名，例如對 [https://docs.aws.amazon.com/cli/latest/reference/dynamodb/scan.html](https://docs.aws.amazon.com/cli/latest/reference/dynamodb/scan.html) 命令而言為 `--filter-expression`。

如需特定命令是否具有伺服器端篩選和篩選規則的資訊，請參閱第 [AWS CLI 2 版參考指南](https://docs.aws.amazon.com/cli/latest/reference/index.html)。

## 用戶端篩選
<a name="cli-usage-filter-client-side"></a>

使用 `--query` 參數 AWS CLI 提供內建的 JSON 型用戶端篩選功能。`--query` 參數是功能強大的工具，可供您用來自訂輸出的內容與樣式。`--query` 參數會取得從伺服器傳回的 HTTP 回應，並在顯示結果之前先行篩選。因為整個 HTTP 回應會在篩選之前傳送至用戶端，所以在大型資料集速度方面，用戶端篩選可能會比伺服器端篩選來得慢。

查詢會使用 [JMESPath 語法 語法](https://jmespath.org/)來建立表達式，以便篩選輸出。若要學習 JMESPath 語法，請參閱 *JMESPath 網站*上的[教學課程](https://jmespath.org/tutorial.html)。

**重要**  
您指定的輸出類型會影響 `--query` 選項的運作方式：  
如果您指定 `--output text`，輸出會在套用`--query`篩選條件*之前*進行分頁，而 會在輸出*的每個頁面上* AWS CLI 執行一次查詢。因此，查詢會包含每個頁面上第一個相符的要素，即會導致意外額外輸出的要素。若要額外篩選輸出，您可以使用其他命令列工具，例如 `head` 或 `tail`。
如果您指定 `--output json`、 `--output yaml` 或 `--output yaml-stream`，系統就會將輸出完全處理為單一原生結構後，才套用 `--query` 篩選條件。只會針對整個結構 AWS CLI 執行一次查詢，產生篩選結果，然後輸出。

**Topics**
+ [開始之前](#cli-usage-filter-client-side-output)
+ [識別碼](#cli-usage-filter-client-side-identifiers)
+ [從清單中選取](#cli-usage-filter-client-side-select-list)
+ [篩選巢狀資料](#cli-usage-filter-client-side-nested)
+ [扁平化結果](#cli-usage-filter-client-side-specific-flattening)
+ [篩選特定值](#cli-usage-filter-client-side-specific-values)
+ [輸送表達式](#cli-usage-filter-client-side-pipe)
+ [篩選多個識別碼值](#cli-usage-filter-client-side-miltiselect-list)
+ [將標籤新增至識別碼值](#cli-usage-filter-client-side-multiselect-hash)
+ [函數](#cli-usage-filter-client-side-functions)
+ [進階 `--query` 範例](#cli-usage-filter-client-side-advanced)

### 開始之前
<a name="cli-usage-filter-client-side-output"></a>

**注意**  
這些篩選條件表達式範例是針對基本類似 Linux 的 shell 撰寫的。使用這些範例時，請務必為終端 Shell 使用正確引號規則。終端解譯輸入的方式可能會大幅變更傳送至 AWS CLI的內容。終端讀取單引號 `'`、雙引號 `"` 或反引號 ``` 的方式會改變讀取內容的方式。  
如需詳細資訊，請參閱[在 中使用引號和常值搭配字串 AWS CLI](cli-usage-parameters-quoting-strings.md)。

以下 JSON 輸出會顯示如何產生 `--query` 參數之範例。輸出會描述連接到不同 Amazon EC2 執行個體的三個 Amazon EBS 磁碟區。

#### 範例輸出
<a name="cli-usage-filter-client-side-output-example"></a>

```
$ aws ec2 describe-volumes
{
  "Volumes": [
    {
      "AvailabilityZone": "us-west-2a",
      "Attachments": [
        {
          "AttachTime": "2013-09-17T00:55:03.000Z",
          "InstanceId": "i-a071c394",
          "VolumeId": "vol-e11a5288",
          "State": "attached",
          "DeleteOnTermination": true,
          "Device": "/dev/sda1"
        }
      ],
      "VolumeType": "standard",
      "VolumeId": "vol-e11a5288",
      "State": "in-use",
      "SnapshotId": "snap-f23ec1c8",
      "CreateTime": "2013-09-17T00:55:03.000Z",
      "Size": 30
    },
    {
      "AvailabilityZone": "us-west-2a",
      "Attachments": [
        {
          "AttachTime": "2013-09-18T20:26:16.000Z",
          "InstanceId": "i-4b41a37c",
          "VolumeId": "vol-2e410a47",
          "State": "attached",
          "DeleteOnTermination": true,
          "Device": "/dev/sda1"
        }
      ],
      "VolumeType": "standard",
      "VolumeId": "vol-2e410a47",
      "State": "in-use",
      "SnapshotId": "snap-708e8348",
      "CreateTime": "2013-09-18T20:26:15.000Z",
      "Size": 8
    },
    {
      "AvailabilityZone": "us-west-2a",
      "Attachments": [
        {
          "AttachTime": "2020-11-20T19:54:06.000Z",
          "InstanceId": "i-1jd73kv8",
          "VolumeId": "vol-a1b3c7nd",
          "State": "attached",
          "DeleteOnTermination": true,
          "Device": "/dev/sda1"
        }
      ],
      "VolumeType": "standard",
      "VolumeId": "vol-a1b3c7nd",
      "State": "in-use",
      "SnapshotId": "snap-234087fb",
      "CreateTime": "2020-11-20T19:54:05.000Z",
      "Size": 15
    }
  ]
}
```

### 識別碼
<a name="cli-usage-filter-client-side-identifiers"></a>

識別碼是輸出值的標籤。在建立篩選條件時，您可以使用識別碼來縮小查詢結果範圍。在下列輸出範例中，所有識別碼 (例如 `Volumes`、`AvailabilityZone` 以及 `AttachTime`) 皆會反白顯示。

```
$ aws ec2 describe-volumes
{
  "Volumes": [
    {
      "AvailabilityZone": "us-west-2a",
      "Attachments": [
        {
          "AttachTime": "2013-09-17T00:55:03.000Z",
          "InstanceId": "i-a071c394",
          "VolumeId": "vol-e11a5288",
          "State": "attached",
          "DeleteOnTermination": true,
          "Device": "/dev/sda1"
        }
      ],
      "VolumeType": "standard",
      "VolumeId": "vol-e11a5288",
      "State": "in-use",
      "SnapshotId": "snap-f23ec1c8",
      "CreateTime": "2013-09-17T00:55:03.000Z",
      "Size": 30
    },
    {
      "AvailabilityZone": "us-west-2a",
      "Attachments": [
        {
          "AttachTime": "2013-09-18T20:26:16.000Z",
          "InstanceId": "i-4b41a37c",
          "VolumeId": "vol-2e410a47",
          "State": "attached",
          "DeleteOnTermination": true,
          "Device": "/dev/sda1"
        }
      ],
      "VolumeType": "standard",
      "VolumeId": "vol-2e410a47",
      "State": "in-use",
      "SnapshotId": "snap-708e8348",
      "CreateTime": "2013-09-18T20:26:15.000Z",
      "Size": 8
    },
    {
      "AvailabilityZone": "us-west-2a",
      "Attachments": [
        {
          "AttachTime": "2020-11-20T19:54:06.000Z",
          "InstanceId": "i-1jd73kv8",
          "VolumeId": "vol-a1b3c7nd",
          "State": "attached",
          "DeleteOnTermination": true,
          "Device": "/dev/sda1"
        }
      ],
      "VolumeType": "standard",
      "VolumeId": "vol-a1b3c7nd",
      "State": "in-use",
      "SnapshotId": "snap-234087fb",
      "CreateTime": "2020-11-20T19:54:05.000Z",
      "Size": 15
    }
  ]
}
```

如需詳細資訊，請參閱 *JMESPath 網站*上的[識別碼](https://jmespath.org/specification.html#identifiers )。

### 從清單中選取
<a name="cli-usage-filter-client-side-select-list"></a>

輕單或陣列為後接方括號 `[` 的識別碼，例如 [開始之前](#cli-usage-filter-client-side-output) 中的 `Volumes` 和 `Attachments`。

**語法**

```
<listName>[ ]
```

若要從陣列中篩選所有輸出，您可以使用萬用表示法。[萬用字元](http://jmespath.org/specification.html#wildcard-expressions)表達式為使用 `*` 符號來傳回要素的表達式。

以下範例會查詢所有 `Volumes` 內容。

```
$ aws ec2 describe-volumes \
    --query 'Volumes[*]'
[
  {
    "AvailabilityZone": "us-west-2a",
    "Attachments": [
      {
        "AttachTime": "2013-09-17T00:55:03.000Z",
        "InstanceId": "i-a071c394",
        "VolumeId": "vol-e11a5288",
        "State": "attached",
        "DeleteOnTermination": true,
        "Device": "/dev/sda1"
      }
    ],
    "VolumeType": "standard",
    "VolumeId": "vol-e11a5288",
    "State": "in-use",
    "SnapshotId": "snap-f23ec1c8",
    "CreateTime": "2013-09-17T00:55:03.000Z",
    "Size": 30
  },
  {
    "AvailabilityZone": "us-west-2a",
    "Attachments": [
      {
        "AttachTime": "2020-11-20T19:54:06.000Z",
        "InstanceId": "i-1jd73kv8",
        "VolumeId": "vol-a1b3c7nd",
        "State": "attached",
        "DeleteOnTermination": true,
        "Device": "/dev/sda1"
      }
    ],
    "VolumeType": "standard",
    "VolumeId": "vol-a1b3c7nd",
    "State": "in-use",
    "SnapshotId": "snap-234087fb",
    "CreateTime": "2020-11-20T19:54:05.000Z",
    "Size": 15
  }
]
```

若要依索引檢視陣列中的特定磁碟區，您可以呼叫陣列索引。例如，`Volumes` 陣列中首個項目的索引為 0，會導致 `Volumes[0]` 查詢。如需有關陣列索引的詳細資訊，請參閱 *JMESPath 網站*上的[索引表達式](http://jmespath.org/specification.html#index-expressions)。

```
$ aws ec2 describe-volumes \
    --query 'Volumes[0]'
{
  "AvailabilityZone": "us-west-2a",
  "Attachments": [
    {
      "AttachTime": "2013-09-17T00:55:03.000Z",
      "InstanceId": "i-a071c394",
      "VolumeId": "vol-e11a5288",
      "State": "attached",
      "DeleteOnTermination": true,
      "Device": "/dev/sda1"
    }
  ],
  "VolumeType": "standard",
  "VolumeId": "vol-e11a5288",
  "State": "in-use",
  "SnapshotId": "snap-f23ec1c8",
  "CreateTime": "2013-09-17T00:55:03.000Z",
  "Size": 30
}
```

若要依索引檢視特定範圍的磁碟區，請搭配 `slice` 使用以下語法，其中 **start** 為開始陣列索引，**stop** 為篩選條件停止處理的索引，**step** 則是略過間隔。

**語法**

```
<arrayName>[<start>:<stop>:<step>]
```

如果從配量表達式中省略了其中任何一個，則會使用下列預設值：
+ Start – 清單中的第一個索引，值為 0。
+ Stop – 清單中的最後一個索引。
+ Step – 未略過步驟，其數值為 1。

若只要傳回前兩個磁碟區，您可以使用 start 數值 0、stop 數值 2，以及 step 數值 1，如下列範例所示。

```
$ aws ec2 describe-volumes \
    --query 'Volumes[0:2:1]'
[
  {
    "AvailabilityZone": "us-west-2a",
    "Attachments": [
      {
        "AttachTime": "2013-09-17T00:55:03.000Z",
        "InstanceId": "i-a071c394",
        "VolumeId": "vol-e11a5288",
        "State": "attached",
        "DeleteOnTermination": true,
        "Device": "/dev/sda1"
      }
    ],
    "VolumeType": "standard",
    "VolumeId": "vol-e11a5288",
    "State": "in-use",
    "SnapshotId": "snap-f23ec1c8",
    "CreateTime": "2013-09-17T00:55:03.000Z",
    "Size": 30
  },
  {
    "AvailabilityZone": "us-west-2a",
    "Attachments": [
      {
        "AttachTime": "2013-09-18T20:26:16.000Z",
        "InstanceId": "i-4b41a37c",
        "VolumeId": "vol-2e410a47",
        "State": "attached",
        "DeleteOnTermination": true,
        "Device": "/dev/sda1"
      }
    ],
    "VolumeType": "standard",
    "VolumeId": "vol-2e410a47",
    "State": "in-use",
    "SnapshotId": "snap-708e8348",
    "CreateTime": "2013-09-18T20:26:15.000Z",
    "Size": 8
  }
]
```

由於此範例中包含預設值，您可以將配量從 `Volumes[0:2:1]` 縮短至 `Volumes[:2]`。

下列範例會省略預設值，並傳回整個陣列中的每兩個磁碟區。

```
$ aws ec2 describe-volumes \
    --query 'Volumes[::2]'
[
  {
    "AvailabilityZone": "us-west-2a",
    "Attachments": [
      {
        "AttachTime": "2013-09-17T00:55:03.000Z",
        "InstanceId": "i-a071c394",
        "VolumeId": "vol-e11a5288",
        "State": "attached",
        "DeleteOnTermination": true,
        "Device": "/dev/sda1"
      }
    ],
    "VolumeType": "standard",
    "VolumeId": "vol-e11a5288",
    "State": "in-use",
    "SnapshotId": "snap-f23ec1c8",
    "CreateTime": "2013-09-17T00:55:03.000Z",
    "Size": 30
  },
  {
    "AvailabilityZone": "us-west-2a",
    "Attachments": [
      {
        "AttachTime": "2020-11-20T19:54:06.000Z",
        "InstanceId": "i-1jd73kv8",
        "VolumeId": "vol-a1b3c7nd",
        "State": "attached",
        "DeleteOnTermination": true,
        "Device": "/dev/sda1"
      }
    ],
    "VolumeType": "standard",
    "VolumeId": "vol-a1b3c7nd",
    "State": "in-use",
    "SnapshotId": "snap-234087fb",
    "CreateTime": "2020-11-20T19:54:05.000Z",
    "Size": 15
  }
]
```

Step 也可以使用負數並以與陣列相反的順序來篩選，如下列範例所示。

```
$ aws ec2 describe-volumes \
    --query 'Volumes[::-2]'
[
  {
    "AvailabilityZone": "us-west-2a",
    "Attachments": [
      {
        "AttachTime": "2020-11-20T19:54:06.000Z",
        "InstanceId": "i-1jd73kv8",
        "VolumeId": "vol-a1b3c7nd",
        "State": "attached",
        "DeleteOnTermination": true,
        "Device": "/dev/sda1"
      }
    ],
    "VolumeType": "standard",
    "VolumeId": "vol-a1b3c7nd",
    "State": "in-use",
    "SnapshotId": "snap-234087fb",
    "CreateTime": "2020-11-20T19:54:05.000Z",
    "Size": 15
  },
  {
    "AvailabilityZone": "us-west-2a",
    "Attachments": [
      {
        "AttachTime": "2013-09-17T00:55:03.000Z",
        "InstanceId": "i-a071c394",
        "VolumeId": "vol-e11a5288",
        "State": "attached",
        "DeleteOnTermination": true,
        "Device": "/dev/sda1"
      }
    ],
    "VolumeType": "standard",
    "VolumeId": "vol-e11a5288",
    "State": "in-use",
    "SnapshotId": "snap-f23ec1c8",
    "CreateTime": "2013-09-17T00:55:03.000Z",
    "Size": 30
  }
]
```

如需詳細資訊，請參閱 *JMESPath 網站*上的[配量](https://jmespath.org/specification.html#slices)。

### 篩選巢狀資料
<a name="cli-usage-filter-client-side-nested"></a>

若要縮小對巢狀值 `Volumes[*]` 的篩選範圍，您可以附加句點以及您的篩選條件標準來使用子運算式。

**語法**

```
<expression>.<expression>
```

以下範例顯示所有磁碟區的所以 `Attachments` 資訊。

```
$ aws ec2 describe-volumes \
    --query 'Volumes[*].Attachments'
[
  [
    {
      "AttachTime": "2013-09-17T00:55:03.000Z",
      "InstanceId": "i-a071c394",
      "VolumeId": "vol-e11a5288",
      "State": "attached",
      "DeleteOnTermination": true,
      "Device": "/dev/sda1"
    }
  ],
  [
    {
      "AttachTime": "2013-09-18T20:26:16.000Z",
      "InstanceId": "i-4b41a37c",
      "VolumeId": "vol-2e410a47",
      "State": "attached",
      "DeleteOnTermination": true,
      "Device": "/dev/sda1"
    }
  ],
  [
    {
      "AttachTime": "2020-11-20T19:54:06.000Z",
      "InstanceId": "i-1jd73kv8",
      "VolumeId": "vol-a1b3c7nd",
      "State": "attached",
      "DeleteOnTermination": true,
      "Device": "/dev/sda1"
    }
  ]
]
```

若要進一步篩選巢狀值，請附加每個巢狀識別碼的表達式。以下範例會列出所有 `Volumes` 的 `State`。

```
$ aws ec2 describe-volumes \
    --query 'Volumes[*].Attachments[*].State'
[
  [
    "attached"
  ],
  [
    "attached"
  ],
  [
    "attached"
  ]
]
```

### 扁平化結果
<a name="cli-usage-filter-client-side-specific-flattening"></a>

如需詳細資訊，請參閱 *JMESPath 網站*上的[子運算式](https://jmespath.org/specification.html#subexpressions)。

您可以移除導致 `Volumes[*].Attachments[].State` 查詢的萬用表示法，以展平 `Volumes[*].Attachments[*].State` 結果。展平化通常有助於改善結果的可讀性。

```
$ aws ec2 describe-volumes \
    --query 'Volumes[*].Attachments[].State'
[
  "attached",
  "attached",
  "attached"
]
```

如需詳細資訊，請參閱 *JMESPath 網站*上的[展平化](https://jmespath.org/specification.html#flatten)。

### 篩選特定值
<a name="cli-usage-filter-client-side-specific-values"></a>

若要篩選清單中的特定值，您可以使用篩選條件表達式，如下列語法所示。

**語法**

```
? <expression> <comparator> <expression>]
```

表達式比較子包括 `==`、`!=`、`<`、`<=`、`>` 和 `>=`。下列範例會篩選 `Attached``State` 中所有 `Volumes` 的 `VolumeIds`。

```
$ aws ec2 describe-volumes \
    --query 'Volumes[*].Attachments[?State==`attached`].VolumeId'
[
  [
    "vol-e11a5288"
  ],
  [
    "vol-2e410a47"
  ],
  [
    "vol-a1b3c7nd"
  ]
]
```

然後可將其展平化，形成以下範例。

```
$ aws ec2 describe-volumes \
    --query 'Volumes[*].Attachments[?State==`attached`].VolumeId[]'
[
  "vol-e11a5288",
  "vol-2e410a47",
  "vol-a1b3c7nd"
]
```

下列範例會篩選所有 `Volumes` 中規模小於 20 的 `VolumeIds`。

```
$ aws ec2 describe-volumes \
    --query 'Volumes[?Size < `20`].VolumeId'
[
  "vol-2e410a47",
  "vol-a1b3c7nd"
]
```

如需詳細資訊，請參閱 *JMESPath 網站*上的[篩選條件表達式](https://jmespath.org/specification.html#filterexpressions)。

### 輸送表達式
<a name="cli-usage-filter-client-side-pipe"></a>

您可以將篩選結果輸送至新清單，然後透過下列語法利用另一個表達式來篩選結果：

**語法**

```
<expression> | <expression>] 
```

下列範例會採用 `Volumes[*].Attachments[].InstanceId` 表達式的篩選結果，並輸出陣列中的第一個結果。

```
$ aws ec2 describe-volumes \
    --query 'Volumes[*].Attachments[].InstanceId | [0]'
"i-a071c394"
```

此範例會先從以下表達式中建立陣列，以達成上述目標。

```
$ aws ec2 describe-volumes \
    --query 'Volumes[*].Attachments[].InstanceId'
"i-a071c394",
  "i-4b41a37c",
  "i-1jd73kv8"
```

接著，傳回該陣列中的第一個要素。

```
"i-a071c394"
```

如需詳細資訊，請參閱 *JMESPath 網站*上的[輸送表達式](https://jmespath.org/specification.html#pipe-expressions)。

### 篩選多個識別碼值
<a name="cli-usage-filter-client-side-miltiselect-list"></a>

若要篩選多個識別碼，您可以透過下列語法來使用複選清單：

**語法**

```
<listName>[].[<expression>, <expression>]
```

在以下範例中，`VolumeId` 和 `VolumeType` 會在 `Volumes` 清單受到篩選，以產生下列表達式。

```
$ aws ec2 describe-volumes \
    --query 'Volumes[].[VolumeId, VolumeType]'
[
  [
    "vol-e11a5288",
    "standard"
  ],
  [
    "vol-2e410a47",
    "standard"
  ],
  [
    "vol-a1b3c7nd",
    "standard"
  ]
]
```

若要將巢狀資料新增至清單，請新增另一個複選清單。以下範例會透過在巢狀 `Attachments` 清單中篩選 `InstanceId` 和 `State` 來擴展上述範例。成果如以下表達式。

```
$ aws ec2 describe-volumes \
    --query 'Volumes[].[VolumeId, VolumeType, Attachments[].[InstanceId, State]]'
[
  [
    "vol-e11a5288",
    "standard",
    [
      [
        "i-a071c394",
        "attached"
      ]
    ]
  ],
  [
    "vol-2e410a47",
    "standard",
    [
      [
        "i-4b41a37c",
        "attached"
      ]
    ]
  ],
  [
    "vol-a1b3c7nd",
    "standard",
    [
      [
        "i-1jd73kv8",
        "attached"
      ]
    ]
  ]
]
```

為了更具可讀性，會如下列範例所示展平表達式。

```
$ aws ec2 describe-volumes \
    --query 'Volumes[].[VolumeId, VolumeType, Attachments[].[InstanceId, State][]][]'
[
  "vol-e11a5288",
  "standard",
  [
    "i-a071c394",
    "attached"
  ],
  "vol-2e410a47",
  "standard",
  [
    "i-4b41a37c",
    "attached"
  ],
  "vol-a1b3c7nd",
  "standard",
  [
    "i-1jd73kv8",
    "attached"
  ]
]
```

如需詳細資訊，請參閱 *JMESPath 網站*上的[複選清單](https://jmespath.org/specification.html#multiselectlist)。

### 將標籤新增至識別碼值
<a name="cli-usage-filter-client-side-multiselect-hash"></a>

為了使此輸出更容易閱讀，請使用具有以下語法的複選雜湊。

**語法**

```
<listName>[].{<label>: <expression>, <label>: <expression>}
```

您的識別碼標籤不需與識別碼的名稱相同。以下範例會將 `VolumeType` 標籤用於 `VolumeType` 值。

```
$ aws ec2 describe-volumes \
    --query 'Volumes[].{VolumeType: VolumeType}'
[
  {
    "VolumeType": "standard",
  },
  {
    "VolumeType": "standard",
  },
  {
    "VolumeType": "standard",
  }
]
```

為了簡單起見，下列範例會保留每個標籤的識別碼名稱，並顯示所有磁碟區的 `VolumeId`、`VolumeType`、`InstanceId` 以及 `State`：

```
$ aws ec2 describe-volumes \
    --query 'Volumes[].{VolumeId: VolumeId, VolumeType: VolumeType, InstanceId: Attachments[0].InstanceId, State: Attachments[0].State}'
[
  {
    "VolumeId": "vol-e11a5288",
    "VolumeType": "standard",
    "InstanceId": "i-a071c394",
    "State": "attached"
  },
  {
    "VolumeId": "vol-2e410a47",
    "VolumeType": "standard",
    "InstanceId": "i-4b41a37c",
    "State": "attached"
  },
  {
    "VolumeId": "vol-a1b3c7nd",
    "VolumeType": "standard",
    "InstanceId": "i-1jd73kv8",
    "State": "attached"
  }
]
```

如需詳細資訊，請參閱 *JMESPath 網站*上的[複選雜湊](https://jmespath.org/specification.html#multiselecthash)。

### 函數
<a name="cli-usage-filter-client-side-functions"></a>

JMESPath 語法包含許多可用於查詢的功能。如需 JMESPath 函數的相關資訊，請參閱 *JMESPath 網站*上的[內建函數](https://jmespath.org/specification.html#built-in-functions)。

為了示範如何將函數合併至您的查詢中，下列範例會使用 `sort_by` 函數。`sort_by` 函數會使用以下語法，利用表達式作為排序索引鍵來排序陣列：

**語法**

```
sort_by(<listName>, <sort expression>)[].<expression>
```

下列範例會使用先前的[複選雜湊範例](#cli-usage-filter-client-side-multiselect-hash)，並藉由 `VolumeId` 來排序輸出。

```
$ aws ec2 describe-volumes \
    --query 'sort_by(Volumes, &VolumeId)[].{VolumeId: VolumeId, VolumeType: VolumeType, InstanceId: Attachments[0].InstanceId, State: Attachments[0].State}'
[
  {
    "VolumeId": "vol-2e410a47",
    "VolumeType": "standard",
    "InstanceId": "i-4b41a37c",
    "State": "attached"
  },
  {
    "VolumeId": "vol-a1b3c7nd",
    "VolumeType": "standard",
    "InstanceId": "i-1jd73kv8",
    "State": "attached"
  },
  {
    "VolumeId": "vol-e11a5288",
    "VolumeType": "standard",
    "InstanceId": "i-a071c394",
    "State": "attached"
  }
]
```

如需詳細資訊，請參閱 *JMESPath 網站*上的 [sort\$1by](https://jmespath.org/specification.html#sort-by)。

### 進階 `--query` 範例
<a name="cli-usage-filter-client-side-advanced"></a>

**從特定項目中擷取資訊**

以下範例使用 `--query` 參數來尋找清單中的特定項目，然後從該項目中擷取資訊。該範例會列出與指定服務端點相關的所有 `AvailabilityZones`。它從具有指定 `ServiceName` 的 `ServiceDetails` 清單擷取項目，然後從該選取項目輸出 `AvailabilityZones` 欄位。

```
$ aws --region us-east-1 ec2 describe-vpc-endpoint-services \
    --query 'ServiceDetails[?ServiceName==`com.amazonaws.us-east-1.ecs`].AvailabilityZones'
[
    [
        "us-east-1a",
        "us-east-1b",
        "us-east-1c",
        "us-east-1d",
        "us-east-1e",
        "us-east-1f"
    ]
]
```

**顯示指定建立日期之後的快照**

以下範例說明如何列出在指定日期之後建立的所有快照，並只包括輸出中的幾個可用欄位。

```
$ aws ec2 describe-snapshots --owner self \
    --output json \
    --query 'Snapshots[?StartTime>=`2018-02-07`].{Id:SnapshotId,VId:VolumeId,Size:VolumeSize}'
[
    {
        "id": "snap-0effb42b7a1b2c3d4",
        "vid": "vol-0be9bb0bf12345678",
        "Size": 8
    }
]
```

**顯示最近的 AMI**

以下範例會列出您建立的 5 個最新 Amazon Machine Image (AMI)，依最新到最舊排列。

```
$ aws ec2 describe-images \
    --owners self \
    --query 'reverse(sort_by(Images,&CreationDate))[:5].{id:ImageId,date:CreationDate}'
[
    {
        "id": "ami-0a1b2c3d4e5f60001",
        "date": "2018-11-28T17:16:38.000Z"
    },
    {
        "id": "ami-0a1b2c3d4e5f60002",
        "date": "2018-09-15T13:51:22.000Z"
    },
    {
        "id": "ami-0a1b2c3d4e5f60003",
        "date": "2018-08-19T10:22:45.000Z"
    },
    {
        "id": "ami-0a1b2c3d4e5f60004",
        "date": "2018-05-03T12:04:02.000Z"
    },
    {
        "id": "ami-0a1b2c3d4e5f60005",
        "date": "2017-12-13T17:16:38.000Z"
    }
]
```

**顯示狀況不良的 Auto Scaling 執行個體**

以下範例僅會顯示指定 Auto Scaling 群組中任何狀況不良的執行個體的 `InstanceId`。

```
$ aws autoscaling describe-auto-scaling-groups \
    --auto-scaling-group-name My-AutoScaling-Group-Name \
    --output text \
    --query 'AutoScalingGroups[*].Instances[?HealthStatus==`Unhealthy`].InstanceId'
```

**包含有指定標籤的磁碟區**

以下範例描述所有具備 `test` 標籤的執行個體。只要 `test` 旁邊有另一個附加至磁碟區的標籤，則磁碟區仍會傳回結果中。

下列表達式傳回陣列中具有 `test` 標籤的所有標籤。任何不是 `test` 標籤的標籤都包含 `null` 值。

```
$ aws ec2 describe-volumes \
    --query 'Volumes[*].Tags[?Value == `test`]'
```

**排除有指定標籤的磁碟區**

以下範例描述所有沒有 `test` 標籤的執行個體。使用簡易 `?Value != `test`` 表達式之方式，不適用於排除磁碟區，原因是磁碟區可擁有多個標籤。只要 `test` 旁邊有另一個附加至磁碟區的標籤，則磁碟區仍會傳回結果中。

若要排除所有具有 `test` 標籤的磁碟區，請從以下表達式開始傳回陣列中所有具有 `test` 標籤的標籤。任何不是 `test` 標籤的標籤都包含 `null` 值。

```
$ aws ec2 describe-volumes \
    --query 'Volumes[*].Tags[?Value == `test`]'
```

接著，請使用 `not_null` 函數篩選掉所有正向 `test` 結果。

```
$ aws ec2 describe-volumes \
    --query 'Volumes[?!not_null(Tags[?Value == `test`].Value)]'
```

輸送結果，以展平會導致以下查詢的結果。

```
$ aws ec2 describe-volumes \
    --query 'Volumes[?!not_null(Tags[?Value == `test`].Value)] | []'
```

## 結合伺服器端和用戶端篩選
<a name="cli-usage-filter-combining"></a>

您可以將伺服器端和用戶端篩選搭配著使用。先完成伺服器端篩選，再將資料傳送至 `--query` 參數稍後要篩選的用戶端。如果您使用的是大型資料集，則先使用伺服器端篩選可以降低每次 AWS CLI 呼叫傳送至用戶端的資料量，同時仍保留用戶端篩選提供的強大自訂功能。

以下範例會列出同時使用伺服器端和用戶端篩選的 Amazon EC2 磁碟區。此服務會篩選 `us-west-2a` 可用區域內所有附加磁碟區。`--query` 參數會將輸出進一步限制為 `Size` 數值大於 50 的那些磁碟區，並只顯示具有使用者定義名稱的指定欄位。

```
$ aws ec2 describe-volumes \
    --filters "Name=availability-zone,Values=us-west-2a" "Name=status,Values=attached" \
    --query 'Volumes[?Size > `50`].{Id:VolumeId,Size:Size,Type:VolumeType}'
[
    {
        "Id": "vol-0be9bb0bf12345678",
        "Size": 80,
        "VolumeType": "gp2"
    }
]
```

以下範例擷取符合幾個條件的影像清單。接著使用 `--query` 參數來依照 `CreationDate` 排序輸出，只選擇最新的項目。最後，顯示該映像的 `ImageId`。

```
$ aws ec2 describe-images \
    --owners amazon \
    --filters "Name=name,Values=amzn*gp2" "Name=virtualization-type,Values=hvm" "Name=root-device-type,Values=ebs" \
    --query "sort_by(Images, &CreationDate)[-1].ImageId" \
    --output text
ami-00ced3122871a4921
```

以下範例透過使用 `length` 計算清單中有多少項目數，顯示超過 1000 IOPS 的可用磁碟區數。

```
$ aws ec2 describe-volumes \
    --filters "Name=status,Values=available" \
    --query 'length(Volumes[?Iops > `1000`])'
3
```

下列範例會擷取在使用 CloudFormation 堆疊的指定 中使用啟動組態 AWS 區域 的 Auto Scaling 群組名稱。

```
$ aws autoscaling describe-auto-scaling-groups --region us-west-2 \
  --filters Name=tag-key,Values=aws:cloudformation:stack-name \
  --query 'AutoScalingGroups[?LaunchConfigurationName!=`null`].AutoScalingGroupName'
[
    "group-1",
    "group-2",
    "group-3"
]
```

## 其他資源
<a name="cli-usage-filter-resources"></a>

**AWS CLI 自動提示**  
開始使用篩選條件表達式時，您可以使用第 2 AWS CLI 版中的自動提示功能。自動提示功能可在您按下 **F5** 鍵時提供預覽。如需詳細資訊，請參閱 [在 中啟用和使用命令提示字元 AWS CLI](cli-usage-parameters-prompting.md)。

**JMESPath 終端機**  
JMESPath 終端機為交互式終端命令，與用於用戶端篩選的 JMESPath 表達式一起進行實驗。使用 `jpterm` 命令時，終端機會在您輸入時立即顯示查詢結果。您可以直接將 AWS CLI 輸出輸送至終端機，啟用進階查詢實驗。  
下列範例會直接輸送 `aws ec2 describe-volumes` 輸出至 JMESPath 終端機。  

```
$ aws ec2 describe-volumes | jpterm
```
如需 JMESPath 終端機和安裝說明的詳細資訊，請參閱 *GitHub* 上的 [JMESPath 終端機](https://github.com/jmespath/jmespath.terminal)。

**jq 公用程式**  
`jq` 公用程式會提供一個方法，讓您能將用戶端的輸出轉換為您要的輸出格式。如需 `jq` 和安裝說明的詳細資訊，請參閱 *GitHub* 上的 [jq](https://stedolan.github.io/jq/)。

# AWS CLI 中的命令列傳回碼
<a name="cli-usage-returncodes"></a>

傳回碼通常是在執行 AWS Command Line Interface (AWS CLI) 命令後傳送的隱藏代碼，其會描述命令狀態。您可以使用 `echo` 命令來顯示從上個 AWS CLI 命令傳送的代碼，並使用這些代碼來判斷命令成功與否，以及命令可能發生錯誤的原因。除了傳回碼之外，您還可以使用 `--debug` 交換器來檢視有關執行命令失敗的更多詳細資訊。此交換器會產生 AWS CLI 用於處理命令的步驟的詳細報告，以及每個步驟的結果。

若要判斷 AWS CLI 命令的傳回碼，請在執行 CLI 命令後立即執行以下其中一個命令。

------
#### [ Linux and macOS ]

```
$ echo $?
0
```

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

```
PS> echo $lastexitcode
0
```

------
#### [ Windows Command Prompt ]

```
C:\> echo %errorlevel%
0
```

------

以下是執行 AWS Command Line Interface (AWS CLI) 命令最後可能傳回的傳回碼值。


| 代碼 | 意義 | 
| --- | --- | 
| 0 |  該服務以 HTTP 回應狀態代碼 200 進行回應，表示請求所傳送的 AWS CLI 和 AWS 服務並未產生錯誤。  | 
| 1 |  一或多個 Amazon S3 傳輸操作失敗。*限於 S3 命令。*  | 
| 2 |  此傳回碼的意義取決於命令： [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/cli/latest/userguide/cli-usage-returncodes.html)  | 
| 130 |  命令被 SIGINT 中斷。這便是您傳送的以 `Ctrl`\$1`C` 取消命令的訊號。  | 
| 252 |  命令語法無效、提供了未知參數，或參數值不正確，導致命令無法執行。  | 
| 253 |  系統環境或組態無效。雖然提供的命令在語法上可能有效，但缺少組態或憑證會導致命令無法執行。  | 
| 254 |  已成功剖析命令，並向指定的服務發出請求，但服務傳回錯誤。這通常表示 API 使用不正確，或發生其他服務特定問題。  | 
| 255 |  命令失敗。請求送往 AWS CLI 或 AWS 的服務產生錯誤。  | 

# 使用自訂精靈在 中執行互動式命令 AWS CLI
<a name="cli-usage-wizard"></a>

 AWS Command Line Interface (AWS CLI) 提供對某些命令使用精靈的功能。若要貢獻或檢視可用 AWS CLI 精靈的完整清單，請參閱 GitHub 上的[AWS CLI 精靈資料夾](https://github.com/aws/aws-cli/tree/v2/awscli/customizations/wizard/wizards)。

## 運作方式
<a name="cli-usage-wizard-how"></a>

與 AWS 主控台類似， AWS CLI 具有 UI 精靈，可引導您管理 AWS 資源。若要使用精靈，您可以呼叫 `wizard` 子命令，以及命令中服務名稱後的精靈名稱。命令結構如下所示：

**語法:**

```
$ aws <command> wizard <wizardName>
```

下列範例為呼叫精靈建立新的 `dynamodb` 資料表。

```
$ aws dynamodb wizard new-table
```

`aws configure` 是唯一沒有精靈名稱的精靈。在執行精靈時，請依照下面範例示範的方式來執行 `aws configure wizard` 命令：

```
$ aws configure wizard
```

在呼叫精靈之後，系統會顯示 Shell 中的表單。對於各個參數，系統會提供一個選項清單供您選取，或提示您輸入字串。若要從清單中選取，請使用向上鍵和向下鍵，然後按 **ENTER**。若要檢視某個選項的詳細資訊，請按向右鍵。在您完成填寫參數後，請按 **ENTER**。

```
$ aws configure wizard
What would you like to configure
> Static Credentials
  Assume Role
  Process Provider
  Additional CLI configuration
Enter the name of the profile: 
Enter your Access Key Id: 
Enter your Secret Access Key:
```

若要編輯先前的提示，請使用 **SHIFT** \$1 **TAB**。對於某些精靈，在填入所有提示之後，您可以預覽 AWS CloudFormation 範本或填入您資訊的 AWS CLI 命令。此預覽模式有助於了解 AWS CLI、 服務 APIs，以及建立指令碼的範本。

請在檢視或最後提示結束後，按 **ENTER** 來執行最終命令。

```
$ aws configure wizard
What would you like to configure
Enter the name of the profile: testWizard
Enter your Access Key Id: AB1C2D3EF4GH5I678J90K
Enter your Secret Access Key: ab1c2def34gh5i67j8k90l1mnop2qr3s45tu678v90
<ENTER>
```

# 在 中建立和使用別名 AWS CLI
<a name="cli-usage-alias"></a>

別名是您可以在 AWS Command Line Interface (AWS CLI) 中建立的捷徑，以縮短您經常使用的命令或指令碼。您可以在位於組態資料夾的 `alias` 檔案中建立別名。

**Topics**
+ [先決條件](#cli-usage-alias-prepreqs)
+ [步驟 1：建立別名檔案](#cli-usage-alias-create-file)
+ [步驟 2：建立別名](#cli-usage-alias-create-alias)
+ [步驟 3：呼叫別名](#cli-usage-alias-call-alias)
+ [別名儲存庫範例](#cli-usage-alias-examples)
+ [Resources](#cli-usage-alias-references)

## 先決條件
<a name="cli-usage-alias-prepreqs"></a>

若要使用別名命令，您需要完成以下事項：
+ 安裝及設定 AWS CLI。如需詳細資訊，請參閱[安裝或更新至最新版本的 AWS CLI](getting-started-install.md)及[的身分驗證和存取憑證 AWS CLI](cli-chap-authentication.md)。
+ 使用最低 AWS CLI 版本 1.11.24 或 2.0.0。
+ （選用） 若要使用別名 bash AWS CLI 指令碼，您必須使用與 bash 相容的終端機。

## 步驟 1：建立別名檔案
<a name="cli-usage-alias-create-file"></a>

若要建立 `alias` 檔案，您可以使用檔案導覽和文字編輯器，或使用您偏好的終端機並按照逐步程序來建立。若要快速建立別名檔案，請使用以下命令區塊。

------
#### [ Linux and macOS ]

```
$ mkdir -p ~/.aws/cli
$ echo '[toplevel]' > ~/.aws/cli/alias
```

------
#### [ Windows ]

```
C:\> md %USERPROFILE%\.aws\cli
C:\> echo [toplevel] > %USERPROFILE%/.aws/cli/alias
```

------

**建立別名檔案**

1. 在 AWS CLI 組態資料夾中建立名為 `cli`的資料夾。預設情況下，組態資料夾是 `~/.aws/` (Linux 或 macOS) 或 `%USERPROFILE%\.aws\` (Windows)。您可以透過檔案導覽或使用以下命令來建立此資料夾。

------
#### [ Linux and macOS ]

   ```
   $ mkdir -p ~/.aws/cli
   ```

------
#### [ Windows ]

   ```
   C:\> md %USERPROFILE%\.aws\cli
   ```

------

   產生的 `cli` 資料夾預設路徑為 `~/.aws/cli/` (Linux 或 macOS) 或 `%USERPROFILE%\.aws\cli` (Windows)。

1. 在 `cli` 資料夾中，建立沒有副檔名且名為 `alias` 的文字檔案，並將 `[toplevel]` 新增至第一行。您可以透過偏好的文字編輯器或使用下列命令來建立此檔案。

------
#### [ Linux and macOS ]

   ```
   $ echo '[toplevel]' > ~/.aws/cli/alias
   ```

------
#### [ Windows ]

   ```
   C:\> echo [toplevel] > %USERPROFILE%/.aws/cli/alias
   ```

------

## 步驟 2：建立別名
<a name="cli-usage-alias-create-alias"></a>

您可以使用基本命令或 Bash 指令碼來建立別名。

### 建立基本命令別名
<a name="cli-usage-alias-create-alias-basic"></a>

您可以在上一步建立的 `alias` 檔案中，使用下列語法新增命令以建立別名。

**語法**

```
aliasname = command [--options]
```

*aliasname* 是您所命名的別名。*command* 為您要呼叫的命令，此命令可包含其他別名。您可以在別名中加入選項或參數，或在呼叫別名時新增選項或參數。

以下範例使用 [https://docs.aws.amazon.com/cli/latest/reference/sts/get-caller-identity.html](https://docs.aws.amazon.com/cli/latest/reference/sts/get-caller-identity.html) 命令來建立名為 `aws whoami` 的別名。由於此別名會呼叫現有的 AWS CLI 命令，因此您編寫的命令無需添加 `aws` 前綴。

```
whoami = sts get-caller-identity
```

下列範例採用之前的 `whoami` 範例，並新增 `Account` 篩選條件和文字 `output` 選項。

```
whoami2 = sts get-caller-identity --query Account --output text
```

### 建立子命令別名
<a name="cli-usage-alias-create-alias-sub-command"></a>

**注意**  
子命令別名功能需要 1.11.24 或 2.0.0 的最低 AWS CLI 版本

您可以在上一步建立的 `alias` 檔案中，使用下列語法新增命令以建立子命令的別名。

**語法**

```
[command commandGroup]
aliasname = command [--options]
```

*commandGroup* 是命令名稱空間，例如，命令 `aws ec2 describe-regions` 在 `ec2` 命令群組下。*aliasname* 是您所命名的別名。*command* 為您要呼叫的命令，此命令可包含其他別名。您可以在別名中加入選項或參數，或在呼叫別名時新增選項或參數。

以下範例使用 [https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-regions.html](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-regions.html) 命令來建立名為 `aws ec2 regions` 的別名。由於此別名會呼叫 `ec2` 命令命名空間下現有的 AWS CLI 命令，因此您編寫的命令無需添加 `aws ec2` 字首。

```
[command ec2]
regions = describe-regions --query Regions[].RegionName
```

若要從命令名稱空間之外的命令建立別名，請在完整命令前加上驚嘆號。以下範例使用 [https://docs.aws.amazon.com/cli/latest/reference/iam/list-instance-profiles.html](https://docs.aws.amazon.com/cli/latest/reference/iam/list-instance-profiles.html) 命令來建立名為 `aws ec2 instance-profiles` 的別名。

```
[command ec2]
instance-profiles = !aws iam list-instance-profiles
```

**注意**  
別名只使用現有的命令命名空間，您不能建立新的命令空間。例如，由於 `johnsmith` 命令名空間尚未存在，因此您無法使用 `[command johnsmith]` 區段建立別名。

### 建立 Bash 指令碼別名
<a name="cli-usage-alias-create-alias-scripting"></a>

**警告**  
若要使用別名 bash AWS CLI 指令碼，您必須使用與 bash 相容的終端機

您可以透過以下語法，在更進階的流程中使用 Bash 指令碼建立別名。

**語法**

```
aliasname = 
    !f() {
        script content
}; f
```

*aliasname* 是您所命名的別名，*script content* 則是您在呼叫別名時要執行的指令碼。

以下範例使用 `opendns` 來輸出您目前的 IP 地址。由於您可以在其他別名中使用別名，因此以下 `myip` 別名，可用於從其他別名中允許或撤銷 IP 地址的存取權限。

```
myip =
  !f() {
    dig +short myip.opendns.com @resolver1.opendns.com
  }; f
```

下列指令碼範例會呼叫上一個 `aws myip` 別名，以授予您的 IP 地址進入 Amazon EC2 安全群組的權限。

```
authorize-my-ip =
  !f() {
    ip=$(aws myip)
    aws ec2 authorize-security-group-ingress --group-id ${1} --cidr $ip/32 --protocol tcp --port 22
  }; f
```

在您呼叫使用 Bash 指令碼的別名時，變數一律會按照您輸入的順序傳遞。在 Bash 指令碼中，變數名稱不是考慮因素，僅會考量其顯示順序。在下列 `textalert` 別名範例中，`--message` 選項的變數為第一個，而 `--phone-number` 選項為第二個。

```
textalert =
  !f() {
    aws sns publish --message "${1}" --phone-number ${2}
  }; f
```

## 步驟 3：呼叫別名
<a name="cli-usage-alias-call-alias"></a>

若要執行您在 `alias` 檔案中建立的別名，請使用以下語法。您可以在呼叫別名時新增其他選項。

**語法**

```
$ aws aliasname
```

下列範例使用 `aws whoami` 命令別名。

```
$ aws whoami
{
    "UserId": "A12BCD34E5FGHI6JKLM",
    "Account": "1234567890987",
    "Arn": "arn:aws:iam::1234567890987:user/userName"
}
```

以下範例使用 `aws whoami` 別名以及其他選項，以便只將 `Account` 號碼回傳到 `text` 輸出中。

```
$ aws whoami --query Account --output text
1234567890987
```

下列範例使用 `aws ec2 regions`[ 子命令別名](#cli-usage-alias-create-alias-sub-command)。

```
$ aws ec2 regions
[
    "ap-south-1",
    "eu-north-1",
    "eu-west-3",
    "eu-west-2",
...
```

### 使用 Bash 指令碼變數呼叫別名
<a name="cli-usage-alias-call-alias-variables"></a>

在您呼叫使用 Bash 指令碼的別名時，變數會按照您輸入的順序傳遞。在 Bash 指令碼中，變數名稱不是考慮因素，僅會考量其顯示順序。例如，在下列 `textalert` 別名中，`--message` 選項的變數為第一個，而 `--phone-number` 為第二個。

```
textalert =
  !f() {
    aws sns publish --message "${1}" --phone-number ${2}
  }; f
```

在呼叫 `textalert` 別名時，您必須按照變數在別名中的執行順序來傳遞變數。在以下範例中，我們使用變數 `$message` 和 `$phone`。`$message` 變數會作為 `--message` 選項的 `${1}` 傳遞，`$phone` 變數則作為 `--phone-number` 選項的 `${2}` 傳遞。如此會成功呼叫 `textalert` 別名來傳送訊息。

```
$ aws textalert $message $phone
{
    "MessageId": "1ab2cd3e4-fg56-7h89-i01j-2klmn34567"
}
```

在下列範例中，呼叫 `$phone` 和 `$message` 別名時會對調順序。`$message` 變數會作為 `--message` 選項的 `${1}` 傳遞，`$phone` 變數則作為 `--phone-number` 選項的 `${2}` 傳遞。由於變數順序不正確，別名會錯誤傳遞變數。因為 `$message` 的內容與 `--phone-number` 選項的電話號碼格式需求不相符，所以會導致錯誤發生。

```
$ aws textalert $phone $message
usage: aws [options] <command> <subcommand> [<subcommand> ...] [parameters]
To see help text, you can run:

  aws help
  aws <command> help
  aws <command> <subcommand> help

Unknown options: text
```

## 別名儲存庫範例
<a name="cli-usage-alias-examples"></a>

*GitHub* 上的[AWS CLI 別名儲存庫](https://github.com/awslabs/awscli-aliases)包含 AWS CLI 開發人員團隊和社群建立的 AWS CLI 別名範例。您可以使用整個 `alias` 檔案範例，或者自行採用個別別名。

**警告**  
執行本節中的命令會刪除您現有的 `alias` 檔案。為了避免覆寫現有別名檔案，請變更下載位置。

**使用儲存庫中的別名**

1. 安裝 Git。如需安裝說明，請參閱 *Git 文件*中的[新手入門 – 安裝 Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)。

1. 安裝 `jp` 命令。`jp` 命令是用於 `tostring` 別名。如需安裝說明，請參閱 *GitHub* 上的 [JMESPath (jp) README.md](https://github.com/jmespath/jp)。

1. 安裝 `jq` 命令。`jq` 命令是用於 `tostring-with-jq` 別名。如需安裝說明，請參閱 *GitHub* 上的 [JSON processor (jq)](https://stedolan.github.io/jq/download/)。

1. 執行下列其中一項操作來下載 `alias` 檔案：
   + 執行以下命令，即可從儲存庫下載 `alias` 檔案並將它複製到組態資料夾。

------
#### [ Linux and macOS ]

     ```
     $ git clone https://github.com/awslabs/awscli-aliases.git
     $ mkdir -p ~/.aws/cli
     $ cp awscli-aliases/alias ~/.aws/cli/alias
     ```

------
#### [ Windows ]

     ```
     C:\> git clone https://github.com/awslabs/awscli-aliases.git
     C:\> md %USERPROFILE%\.aws\cli
     C:\> copy awscli-aliases\alias %USERPROFILE%\.aws\cli
     ```

------
   + 直接從儲存庫下載，並儲存至 AWS CLI 組態`cli`資料夾中的 資料夾。預設情況下，組態資料夾是 `~/.aws/` (Linux 或 macOS) 或 `%USERPROFILE%\.aws\` (Windows)。

1. 若要驗證別名是否正常運作，請執行以下別名。

   ```
   $ aws whoami
   ```

   如此會顯示與 `aws sts get-caller-identity` 命令相同的回應：

   ```
   {
       "Account": "012345678901",
       "UserId": "AIUAINBADX2VEG2TC6HD6",
       "Arn": "arn:aws:iam::012345678901:user/myuser"
   }
   ```

## Resources
<a name="cli-usage-alias-references"></a>
+ *GitHub* 上的[AWS CLI 別名儲存庫](https://github.com/awslabs/awscli-aliases)包含 AWS CLI 開發人員團隊建立的 AWS CLI 別名範例，以及社群的 AWS CLI 貢獻。
+ 來自 [AWS re：Invent 2016 的別名功能公告：YouTube 上的有效 AWS CLI 使用者](https://www.youtube.com/watch?t=1590&v=Xc1dHtWa9-Q)。 *YouTube* 
+ [https://docs.aws.amazon.com/cli/latest/reference/sts/get-caller-identity.html](https://docs.aws.amazon.com/cli/latest/reference/sts/get-caller-identity.html)
+ [https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html)
+ [https://docs.aws.amazon.com/cli/latest/reference/sns/publish.html](https://docs.aws.amazon.com/cli/latest/reference/sns/publish.html)

# 故障診斷 的錯誤 AWS CLI
<a name="cli-chap-troubleshooting"></a>

本節介紹常見錯誤和解決問題時應遵循的故障診斷步驟。我們建議先遵循[一般故障診斷](#tshoot-general)。

**Contents**
+ [先嘗試的一般故障診斷](#tshoot-general)
  + [檢查您的 AWS CLI 命令格式](#general-formatting)
  + [檢查您的 AWS 區域 AWS CLI 命令正在使用](#general-region)
  + [確認您執行的是最新版本的 AWS CLI](#general-latest)
  + [設定 `--debug` 選項](#general-debug)
  + [啟用和檢閱 AWS CLI 命令歷史記錄日誌](#tshoot-general-history)
  + [確認您的 AWS CLI 已設定](#tshoot-general-config)
+ [命令未找到錯誤](#tshoot-install-not-found)
+ [「`aws --version`」命令傳回的版本與您安裝的版本不同](#tshoot-install-wrong-version)
+ [解除安裝 後，「`aws --version`」命令會傳回版本 AWS CLI](#tshoot-uninstall-1)
+ [已 AWS CLI 處理參數名稱不完整的命令](#tshoot-parameter-abbrev)
+ [存取遭拒錯誤](#tshoot-access-denied)
+ [無效的憑證和金鑰錯誤](#tshoot-permissions-wrongcreds)
+ [簽章不相符錯誤](#tshoot-signature-does-not-match)
+ [SSL 憑證錯誤](#tshoot-certificate-verify-failed)
+ [JSON 無效錯誤](#tshoot-invalid-json)
+ [其他資源](#tshoot-resources)

## 先嘗試的一般故障診斷
<a name="tshoot-general"></a>

如果您收到錯誤或遇到 問題 AWS CLI，我們建議您使用下列一般提示來協助您進行故障診斷。

[回到頁首](#cli-chap-troubleshooting-top)

### 檢查您的 AWS CLI 命令格式
<a name="general-formatting"></a>

如果您收到錯誤，指出命令不存在，或無法辨識文件表示可用的參數 (`Parameter validation failed`)，則您的命令格式可能不正確。我們建議您檢查以下內容：
+ 檢查您的命令是否有拼寫和格式錯誤。
+ 確認所有的[引號和逸出適合您的終端機](cli-usage-parameters-quoting-strings.md)在您的命令中是正確的。
+ 產生 [AWS CLI 骨架](cli-usage-skeleton.md)以確認您的命令結構。
+ 對於 JSON，請另參閱 [JSON 值故障診斷](#tshoot-invalid-json)。如果您在終端處理 JSON 格式時遇到問題，我們建議透過使用 [Blob 將 JSON 資料直接傳遞至 AWS CLI](cli-usage-parameters-types.md#parameter-type-blob)，以跳過終端機的引用規則。

如需如何建構特定命令的詳細資訊，請參閱第 [AWS CLI 2 版參考指南](https://docs.aws.amazon.com/cli/latest/reference/index.html)。

[回到頁首](#cli-chap-troubleshooting-top)

### 檢查您的 AWS 區域 AWS CLI 命令正在使用
<a name="general-region"></a>

**注意**  
使用 AWS 區域 時 AWS CLI，您必須明確或透過設定預設區域來指定 。如需 AWS 區域 您可以指定之所有 的清單，請參閱《》中的[AWS 區域和端點](https://docs.aws.amazon.com/general/latest/gr/rande.html)*Amazon Web Services 一般參考*。所使用的 AWS 區域 指標 AWS CLI 與您在 AWS 管理主控台 URLs和服務端點中看到的名稱相同。

如果您指定的 AWS 服務 無法使用，或您的 資源位於不同的 ，則可能會發生錯誤 AWS 區域 或非預期的結果 AWS 區域。依優先順序， AWS 區域 會以下列方式設定：
+ `--region` 命令列選項。
+ SDK 相容的 `AWS\$1REGION` 環境變數。
+ `AWS\$1DEFAULT\$1REGION` 環境變數。
+ [`region`](cli-configure-files.md#cli-config-region) 設定檔設定。

確認您使用 AWS 區域 正確的 資源。

[回到頁首](#cli-chap-troubleshooting-top)

### 確認您執行的是最新版本的 AWS CLI
<a name="general-latest"></a>

如果您收到錯誤，指出命令不存在，或無法辨識第 [AWS CLI 2 版參考指南](https://docs.aws.amazon.com/cli/latest/reference/index.html)指出可用的參數，請先確認您的命令格式正確。如果格式正確，我們建議您升級到最新版本的 AWS CLI。更新版本的 AWS CLI 幾乎會在每個工作天發行。新的 AWS 服務、功能和參數會在這些新版本的 中推出 AWS CLI。要存取這些新服務、功能或參數的唯一方法，就是升級到該元素首次推出之後所發行的版本。

如何更新 的版本 AWS CLI ，取決於您最初的安裝方式，如 中所述[安裝或更新至最新版本的 AWS CLI](getting-started-install.md)。

如果您使用其中一個隨附的安裝程式，您可能需要移除現有的安裝，然後下載並安裝適用於您作業系統的最新版本安裝程式。

[回到頁首](#cli-chap-troubleshooting-top)

### 設定 `--debug` 選項
<a name="general-debug"></a>

當 AWS CLI 回報您未立即了解的錯誤，或產生您未預期的結果時，您可以使用 `--debug`選項再次執行 命令，以取得有關錯誤的詳細資訊。使用此選項時， AWS CLI 會輸出有關處理命令所需的每個步驟的詳細資訊。輸出中的詳細資訊可協助您判斷錯誤發生在哪個步驟，以及可提供觸發錯誤的線索內容。

您可以將輸出傳送到文字檔案，以供日後檢閱，或在收到要求時將其傳送給 AWS 支援 。

當您包含 `--debug` 選項時，所包括的部分詳細資訊為：
+ 正在尋找的憑證
+ 正在剖析所提供的參數
+ 建構傳送至 AWS 伺服器的請求
+ 傳送至 的請求內容 AWS
+ 原始回應的內容
+ 格式化的輸出

以下是使用和不使用 `--debug` 選項執行命令的範例。

```
$ aws iam list-groups --profile MyTestProfile
{
    "Groups": [
        {
            "Path": "/",
            "GroupName": "MyTestGroup",
            "GroupId": "AGPA0123456789EXAMPLE",
            "Arn": "arn:aws:iam::123456789012:group/MyTestGroup",
            "CreateDate": "2019-08-12T19:34:04Z"
        }
    ]
}
```

```
$ aws iam list-groups --profile MyTestProfile --debug
2019-08-12 12:36:18,305 - MainThread - awscli.clidriver - DEBUG - CLI version: aws-cli/1.16.215 Python/3.7.3 Linux/4.14.133-113.105.amzn2.x86_64 botocore/1.12.205
2019-08-12 12:36:18,305 - MainThread - awscli.clidriver - DEBUG - Arguments entered to CLI: ['iam', 'list-groups', '--debug']
2019-08-12 12:36:18,305 - MainThread - botocore.hooks - DEBUG - Event session-initialized: calling handler <function add_scalar_parsers at 0x7fdf173161e0>
2019-08-12 12:36:18,305 - MainThread - botocore.hooks - DEBUG - Event session-initialized: calling handler <function register_uri_param_handler at 0x7fdf17dec400>
2019-08-12 12:36:18,305 - MainThread - botocore.hooks - DEBUG - Event session-initialized: calling handler <function inject_assume_role_provider_cache at 0x7fdf17da9378>
2019-08-12 12:36:18,307 - MainThread - botocore.credentials - DEBUG - Skipping environment variable credential check because profile name was explicitly set.
2019-08-12 12:36:18,307 - MainThread - botocore.hooks - DEBUG - Event session-initialized: calling handler <function attach_history_handler at 0x7fdf173ed9d8>
2019-08-12 12:36:18,308 - MainThread - botocore.loaders - DEBUG - Loading JSON file: /home/ec2-user/venv/lib/python3.7/site-packages/botocore/data/iam/2010-05-08/service-2.json
2019-08-12 12:36:18,317 - MainThread - botocore.hooks - DEBUG - Event building-command-table.iam: calling handler <function add_waiters at 0x7fdf1731a840>
2019-08-12 12:36:18,320 - MainThread - botocore.loaders - DEBUG - Loading JSON file: /home/ec2-user/venv/lib/python3.7/site-packages/botocore/data/iam/2010-05-08/waiters-2.json
2019-08-12 12:36:18,321 - MainThread - awscli.clidriver - DEBUG - OrderedDict([('path-prefix', <awscli.arguments.CLIArgument object at 0x7fdf171ac780>), ('marker', <awscli.arguments.CLIArgument object at 0x7fdf171b09e8>), ('max-items', <awscli.arguments.CLIArgument object at 0x7fdf171b09b0>)])
2019-08-12 12:36:18,322 - MainThread - botocore.hooks - DEBUG - Event building-argument-table.iam.list-groups: calling handler <function add_streaming_output_arg at 0x7fdf17316510>
2019-08-12 12:36:18,322 - MainThread - botocore.hooks - DEBUG - Event building-argument-table.iam.list-groups: calling handler <function add_cli_input_json at 0x7fdf17da9d90>
2019-08-12 12:36:18,322 - MainThread - botocore.hooks - DEBUG - Event building-argument-table.iam.list-groups: calling handler <function unify_paging_params at 0x7fdf17328048>
2019-08-12 12:36:18,326 - MainThread - botocore.loaders - DEBUG - Loading JSON file: /home/ec2-user/venv/lib/python3.7/site-packages/botocore/data/iam/2010-05-08/paginators-1.json
2019-08-12 12:36:18,326 - MainThread - awscli.customizations.paginate - DEBUG - Modifying paging parameters for operation: ListGroups
2019-08-12 12:36:18,326 - MainThread - botocore.hooks - DEBUG - Event building-argument-table.iam.list-groups: calling handler <function add_generate_skeleton at 0x7fdf1737eae8>
2019-08-12 12:36:18,326 - MainThread - botocore.hooks - DEBUG - Event before-building-argument-table-parser.iam.list-groups: calling handler <bound method OverrideRequiredArgsArgument.override_required_args of <awscli.customizations.cliinputjson.CliInputJSONArgument object at 0x7fdf171b0a58>>
2019-08-12 12:36:18,327 - MainThread - botocore.hooks - DEBUG - Event before-building-argument-table-parser.iam.list-groups: calling handler <bound method GenerateCliSkeletonArgument.override_required_args of <awscli.customizations.generatecliskeleton.GenerateCliSkeletonArgument object at 0x7fdf171c5978>>
2019-08-12 12:36:18,327 - MainThread - botocore.hooks - DEBUG - Event operation-args-parsed.iam.list-groups: calling handler functools.partial(<function check_should_enable_pagination at 0x7fdf17328158>, ['marker', 'max-items'], {'max-items': <awscli.arguments.CLIArgument object at 0x7fdf171b09b0>}, OrderedDict([('path-prefix', <awscli.arguments.CLIArgument object at 0x7fdf171ac780>), ('marker', <awscli.arguments.CLIArgument object at 0x7fdf171b09e8>), ('max-items', <awscli.customizations.paginate.PageArgument object at 0x7fdf171c58d0>), ('cli-input-json', <awscli.customizations.cliinputjson.CliInputJSONArgument object at 0x7fdf171b0a58>), ('starting-token', <awscli.customizations.paginate.PageArgument object at 0x7fdf171b0a20>), ('page-size', <awscli.customizations.paginate.PageArgument object at 0x7fdf171c5828>), ('generate-cli-skeleton', <awscli.customizations.generatecliskeleton.GenerateCliSkeletonArgument object at 0x7fdf171c5978>)]))
2019-08-12 12:36:18,328 - MainThread - botocore.hooks - DEBUG - Event load-cli-arg.iam.list-groups.path-prefix: calling handler <awscli.paramfile.URIArgumentHandler object at 0x7fdf1725c978>
2019-08-12 12:36:18,328 - MainThread - botocore.hooks - DEBUG - Event load-cli-arg.iam.list-groups.marker: calling handler <awscli.paramfile.URIArgumentHandler object at 0x7fdf1725c978>
2019-08-12 12:36:18,328 - MainThread - botocore.hooks - DEBUG - Event load-cli-arg.iam.list-groups.max-items: calling handler <awscli.paramfile.URIArgumentHandler object at 0x7fdf1725c978>
2019-08-12 12:36:18,328 - MainThread - botocore.hooks - DEBUG - Event load-cli-arg.iam.list-groups.cli-input-json: calling handler <awscli.paramfile.URIArgumentHandler object at 0x7fdf1725c978>
2019-08-12 12:36:18,328 - MainThread - botocore.hooks - DEBUG - Event load-cli-arg.iam.list-groups.starting-token: calling handler <awscli.paramfile.URIArgumentHandler object at 0x7fdf1725c978>
2019-08-12 12:36:18,328 - MainThread - botocore.hooks - DEBUG - Event load-cli-arg.iam.list-groups.page-size: calling handler <awscli.paramfile.URIArgumentHandler object at 0x7fdf1725c978>
2019-08-12 12:36:18,328 - MainThread - botocore.hooks - DEBUG - Event load-cli-arg.iam.list-groups.generate-cli-skeleton: calling handler <awscli.paramfile.URIArgumentHandler object at 0x7fdf1725c978>
2019-08-12 12:36:18,329 - MainThread - botocore.hooks - DEBUG - Event calling-command.iam.list-groups: calling handler <bound method CliInputJSONArgument.add_to_call_parameters of <awscli.customizations.cliinputjson.CliInputJSONArgument object at 0x7fdf171b0a58>>
2019-08-12 12:36:18,329 - MainThread - botocore.hooks - DEBUG - Event calling-command.iam.list-groups: calling handler <bound method GenerateCliSkeletonArgument.generate_json_skeleton of <awscli.customizations.generatecliskeleton.GenerateCliSkeletonArgument object at 0x7fdf171c5978>>
2019-08-12 12:36:18,329 - MainThread - botocore.credentials - DEBUG - Looking for credentials via: assume-role
2019-08-12 12:36:18,329 - MainThread - botocore.credentials - DEBUG - Looking for credentials via: assume-role-with-web-identity
2019-08-12 12:36:18,329 - MainThread - botocore.credentials - DEBUG - Looking for credentials via: shared-credentials-file
2019-08-12 12:36:18,329 - MainThread - botocore.credentials - INFO - Found credentials in shared credentials file: ~/.aws/credentials
2019-08-12 12:36:18,330 - MainThread - botocore.loaders - DEBUG - Loading JSON file: /home/ec2-user/venv/lib/python3.7/site-packages/botocore/data/endpoints.json
2019-08-12 12:36:18,334 - MainThread - botocore.hooks - DEBUG - Event choose-service-name: calling handler <function handle_service_name_alias at 0x7fdf1898eb70>
2019-08-12 12:36:18,337 - MainThread - botocore.hooks - DEBUG - Event creating-client-class.iam: calling handler <function add_generate_presigned_url at 0x7fdf18a028c8>
2019-08-12 12:36:18,337 - MainThread - botocore.regions - DEBUG - Using partition endpoint for iam, us-west-2: aws-global
2019-08-12 12:36:18,337 - MainThread - botocore.args - DEBUG - The s3 config key is not a dictionary type, ignoring its value of: None
2019-08-12 12:36:18,340 - MainThread - botocore.endpoint - DEBUG - Setting iam timeout as (60, 60)
2019-08-12 12:36:18,341 - MainThread - botocore.loaders - DEBUG - Loading JSON file: /home/ec2-user/venv/lib/python3.7/site-packages/botocore/data/_retry.json
2019-08-12 12:36:18,341 - MainThread - botocore.client - DEBUG - Registering retry handlers for service: iam
2019-08-12 12:36:18,342 - MainThread - botocore.hooks - DEBUG - Event before-parameter-build.iam.ListGroups: calling handler <function generate_idempotent_uuid at 0x7fdf189b10d0>
2019-08-12 12:36:18,342 - MainThread - botocore.hooks - DEBUG - Event before-call.iam.ListGroups: calling handler <function inject_api_version_header_if_needed at 0x7fdf189b2a60>
2019-08-12 12:36:18,343 - MainThread - botocore.endpoint - DEBUG - Making request for OperationModel(name=ListGroups) with params: {'url_path': '/', 'query_string': '', 'method': 'POST', 'headers': {'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8', 'User-Agent': 'aws-cli/1.16.215 Python/3.7.3 Linux/4.14.133-113.105.amzn2.x86_64 botocore/1.12.205'}, 'body': {'Action': 'ListGroups', 'Version': '2010-05-08'}, 'url': 'https://iam.amazonaws.com/', 'context': {'client_region': 'aws-global', 'client_config': <botocore.config.Config object at 0x7fdf16e9a4a8>, 'has_streaming_input': False, 'auth_type': None}}
2019-08-12 12:36:18,343 - MainThread - botocore.hooks - DEBUG - Event request-created.iam.ListGroups: calling handler <bound method RequestSigner.handler of <botocore.signers.RequestSigner object at 0x7fdf16e9a470>>
2019-08-12 12:36:18,343 - MainThread - botocore.hooks - DEBUG - Event choose-signer.iam.ListGroups: calling handler <function set_operation_specific_signer at 0x7fdf18996f28>
2019-08-12 12:36:18,343 - MainThread - botocore.auth - DEBUG - Calculating signature using v4 auth.
2019-08-12 12:36:18,343 - MainThread - botocore.auth - DEBUG - CanonicalRequest:
POST
/

content-type:application/x-www-form-urlencoded; charset=utf-8
host:iam.amazonaws.com
x-amz-date:20190812T193618Z

content-type;host;x-amz-date
5f776d91EXAMPLE9b8cb5eb5d6d4a787a33ae41c8cd6eEXAMPLEca69080e1e1f
2019-08-12 12:36:18,344 - MainThread - botocore.auth - DEBUG - StringToSign:
AWS4-HMAC-SHA256
20190812T193618Z
20190812/us-east-1/iam/aws4_request
ab7e367eEXAMPLE2769f178ea509978cf8bfa054874b3EXAMPLE8d043fab6cc9
2019-08-12 12:36:18,344 - MainThread - botocore.auth - DEBUG - Signature:
d85a0EXAMPLEb40164f2f539cdc76d4f294fe822EXAMPLE18ad1ddf58a1a3ce7
2019-08-12 12:36:18,344 - MainThread - botocore.endpoint - DEBUG - Sending http request: <AWSPreparedRequest stream_output=False, method=POST, url=https://iam.amazonaws.com/, headers={'Content-Type': b'application/x-www-form-urlencoded; charset=utf-8', 'User-Agent': b'aws-cli/1.16.215 Python/3.7.3 Linux/4.14.133-113.105.amzn2.x86_64 botocore/1.12.205', 'X-Amz-Date': b'20190812T193618Z', 'Authorization': b'AWS4-HMAC-SHA256 Credential=AKIA01234567890EXAMPLE-east-1/iam/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=d85a07692aceb401EXAMPLEa1b18ad1ddf58a1a3ce7EXAMPLE', 'Content-Length': '36'}>
2019-08-12 12:36:18,344 - MainThread - urllib3.util.retry - DEBUG - Converted retries value: False -> Retry(total=False, connect=None, read=None, redirect=0, status=None)
2019-08-12 12:36:18,344 - MainThread - urllib3.connectionpool - DEBUG - Starting new HTTPS connection (1): iam.amazonaws.com:443
2019-08-12 12:36:18,664 - MainThread - urllib3.connectionpool - DEBUG - https://iam.amazonaws.com:443 "POST / HTTP/1.1" 200 570
2019-08-12 12:36:18,664 - MainThread - botocore.parsers - DEBUG - Response headers: {'x-amzn-RequestId': '74c11606-bd38-11e9-9c82-559da0adb349', 'Content-Type': 'text/xml', 'Content-Length': '570', 'Date': 'Mon, 12 Aug 2019 19:36:18 GMT'}
2019-08-12 12:36:18,664 - MainThread - botocore.parsers - DEBUG - Response body:
b'<ListGroupsResponse xmlns="https://iam.amazonaws.com/doc/2010-05-08/">\n  <ListGroupsResult>\n    <IsTruncated>false</IsTruncated>\n    <Groups>\n      <member>\n        <Path>/</Path>\n        <GroupName>MyTestGroup</GroupName>\n        <Arn>arn:aws:iam::123456789012:group/MyTestGroup</Arn>\n        <GroupId>AGPA1234567890EXAMPLE</GroupId>\n        <CreateDate>2019-08-12T19:34:04Z</CreateDate>\n      </member>\n    </Groups>\n  </ListGroupsResult>\n  <ResponseMetadata>\n    <RequestId>74c11606-bd38-11e9-9c82-559da0adb349</RequestId>\n  </ResponseMetadata>\n</ListGroupsResponse>\n'
2019-08-12 12:36:18,665 - MainThread - botocore.hooks - DEBUG - Event needs-retry.iam.ListGroups: calling handler <botocore.retryhandler.RetryHandler object at 0x7fdf16e9a780>
2019-08-12 12:36:18,665 - MainThread - botocore.retryhandler - DEBUG - No retry needed.
2019-08-12 12:36:18,665 - MainThread - botocore.hooks - DEBUG - Event after-call.iam.ListGroups: calling handler <function json_decode_policies at 0x7fdf189b1d90>
{
    "Groups": [
        {
            "Path": "/",
            "GroupName": "MyTestGroup",
            "GroupId": "AGPA123456789012EXAMPLE",
            "Arn": "arn:aws:iam::123456789012:group/MyTestGroup",
            "CreateDate": "2019-08-12T19:34:04Z"
        }
    ]
}
```

[回到頁首](#cli-chap-troubleshooting-top)

### 啟用和檢閱 AWS CLI 命令歷史記錄日誌
<a name="tshoot-general-history"></a>

您可以使用 `cli\$1history` 檔案設定來啟用 AWS CLI 命令歷史記錄日誌。啟用此設定後， 會 AWS CLI 記錄 `aws` 命令的歷史記錄。

您可以使用 `aws history list` 命令來列出歷史記錄，並且在 `aws history show` 命令中使用產生的 command\$1ids 取得詳細資訊。如需詳細資訊，請參閱 *AWS CLI 參考指南*中的 [https://docs.aws.amazon.com/cli/latest/reference/history/index.html](https://docs.aws.amazon.com/cli/latest/reference/history/index.html)。

當您包含 `--debug` 選項時，所包括的部分詳細資訊為：
+ 對 botocore 執行的 API 呼叫
+ 狀態碼
+ HTTP 回應
+ 標頭
+ 傳回碼

您可以使用此資訊來確認參數資料和 API 呼叫以您預期的方式運作，然後推斷出您的命令在過程中的哪個步驟失敗。

[回到頁首](#cli-chap-troubleshooting-top)

### 確認您的 AWS CLI 已設定
<a name="tshoot-general-config"></a>

如果您的 `config` 和 `credentials` 檔案或您的 IAM 使用者或角色未正確配置，可能會出現各種錯誤。有關解決 `config` 和 `credentials` 檔案或您的 IAM 使用者或角色等錯誤的詳細資訊，請參閱 [存取遭拒錯誤](#tshoot-access-denied) 和 [無效的憑證和金鑰錯誤](#tshoot-permissions-wrongcreds)。

[回到頁首](#cli-chap-troubleshooting-top)

## 命令未找到錯誤
<a name="tshoot-install-not-found"></a>

此錯誤表示作業系統找不到 AWS CLI 命令。安裝可能不完整或需要更新。

**可能原因：您嘗試使用比已安裝版本更新的 AWS CLI 功能，或格式不正確**  
*範例錯誤文字：*  

```
$ aws s3 copy
aws: [ERROR]: argument operation: Found invalid choice 'copy'

usage: aws [options] <command> <subcommand> [<subcommand> ...] [parameters]
To see help text, you can run:

  aws help
  aws <command> help
  aws <command> <subcommand> help
```
如果您的命令格式不正確，或者您使用的是該功能發佈之前的早期版本，則可能會出現各種錯誤。若要解決圍繞這兩個問題的錯誤的詳細資訊，請參閱[檢查您的 AWS CLI 命令格式](#general-formatting)和[確認您執行的是最新版本的 AWS CLI](#general-latest)。  
[回到頁首](#cli-chap-troubleshooting-top)

**可能的原因：安裝後需要重新啟動終端機**  
*範例錯誤文字：*  

```
$ aws --version
command not found: aws
```
如果在第一次安裝或更新 後找不到 `aws`命令 AWS CLI，您可能需要重新啟動終端機，才能辨識任何`PATH`更新。  
[回到頁首](#cli-chap-troubleshooting-top)

**可能原因： AWS CLI 未完全安裝**  
*範例錯誤文字：*  

```
$ aws --version
command not found: aws
```
如果在第一次安裝或更新 後找不到`aws`命令 AWS CLI，則可能尚未完全安裝。請遵循 [安裝或更新至最新版本的 AWS CLI](getting-started-install.md) 中適用於您平台的步驟，嘗試重新安裝。  
[回到頁首](#cli-chap-troubleshooting-top)

**可能原因： AWS CLI 沒有許可 (Linux)**  
如果在第一次 AWS CLI 在 Linux 上安裝或更新 之後找不到 `aws`命令，則可能沒有其安裝所在資料夾的`execute`許可。使用 AWS CLI 安裝`PATH`的 執行下列命令，以提供 `[chmod](https://en.wikipedia.org/wiki/Chmod)`許可 AWS CLI：  

```
$ sudo chmod -R 755 /usr/local/aws-cli/
```
[回到頁首](#cli-chap-troubleshooting-top)

**可能原因：安裝期間作業系統的 `PATH` 未更新。**  
*範例錯誤文字：*  

```
$ aws --version
command not found: aws
```
您可能需要將 `aws` 可執行檔新增到作業系統的 `PATH` 環境變數中。若要將 AWS CLI 新增至您的 `PATH`，請針對您的作業系統使用下列指示。  

1. 在您的使用者目錄中尋找 Shell 的描述檔命令碼。如果您不確定您擁有哪個 Shell，請執行 `echo $SHELL`。

   ```
   $ ls -a ~
   .  ..  .bash_logout  .bash_profile  .bashrc  Desktop  Documents  Downloads
   ```
   + **Bash** – `.bash_profile`、`.profile` 或 `.bash_login`
   + **Zsh** – `.zshrc`
   + **Tcsh** – `.tcshrc`、`.cshrc` 或 `.login`

1. 將匯出命令新增至您的描述檔指令碼。以下命令將您的本地 bin 新增至目前的 `PATH` 變數。

   ```
   export PATH=/usr/local/bin:$PATH
   ```

1. 將更新過的設定檔載入到您目前的工作階段。

   ```
   $ source ~/.bash_profile
   ```

1. 在 Windows 命令提示符下，使用 `where` 命令與 `/R path` 參數來尋找 `aws` 檔案位置。結果將傳回所有包含 `aws` 的資料夾。

   ```
   C:\> where /R c:\ aws
   c:\Program Files\Amazon\AWSCLIV2\aws.exe
   ...
   ```

   根據預設，第 2 AWS CLI 版位於：

   ```
   c:\Program Files\Amazon\AWSCLIV2\aws.exe
   ```

1. 按下 Windows 鍵並輸入 **environment variables**。

1. 從建議清單中，選擇**Edit environment variables for your account (編輯您帳戶的環境變數)**。

1. 選擇 **PATH**，然後選擇 **Edit (編輯)**。

1. 將您在第一個步驟中找到的路徑新增至**Variable value (變數值)**欄位中，例如 ***C:\$1Program Files\$1Amazon\$1AWSCLIV2\$1aws.exe***。

1. 選擇 **OK** (確定) 兩次以套用新的設定。

1. 關閉任何正在執行的命令提示，並重新開啟命令提示字元視窗。

[回到頁首](#cli-chap-troubleshooting-top)

## 「`aws --version`」命令傳回的版本與您安裝的版本不同
<a name="tshoot-install-wrong-version"></a>

您的終端機可能`PATH`針對 傳回 AWS CLI 不同於您預期的 。

**可能的原因：安裝後需要重新啟動終端機**  
如果 `aws` 命令顯示錯誤的版本，您可能需要重新啟動終端機才能辨識任何 `PATH` 更新。所有開放終端機都需要被關閉，不僅是您正在使用的終端機而已。  
[回到頁首](#cli-chap-troubleshooting-top)

**可能的原因：安裝後需要重新啟動系統**  
如果 `aws` 命令顯示錯誤的版本，且終端機重新啟動無效，您可能需要為其重新啟動系統以辨識您的 `PATH` 更新。  
[回到頁首](#cli-chap-troubleshooting-top)

**可能原因：您有多個版本的 AWS CLI**  
如果您更新 AWS CLI 並使用與預先存在安裝不同的安裝方法，可能會導致安裝多個版本。例如，如果您在 Linux 或 macOS 上使用 `pip`，但嘗試使用 `.pkg` 安裝檔案，這可能會導致一些衝突，特別是如果您的 `PATH` 指向舊版本。  
若要解決此問題，請[解除安裝所有版本的 AWS CLI](#tshoot-uninstall-multiple-version)，並執行全新安裝。  
解除安裝所有版本後，請遵循適用於您作業系統的指示，安裝所需版本的 [AWS CLI 第 1 版](https://docs.aws.amazon.com/cli/v1/userguide/cli-chap-install.html)或 [AWS CLI 第 2 版](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)。  
如果您在安裝 AWS CLI 版本 2 並預先安裝 AWS CLI 版本 1 之後發生這種情況，請在[從第 1 AWS CLI 版安裝第 2 AWS CLI 版](cliv2-migration-instructions.md)。
[回到頁首](#cli-chap-troubleshooting-top)

## 解除安裝 後，「`aws --version`」命令會傳回版本 AWS CLI
<a name="tshoot-uninstall-1"></a>

這通常發生在系統上仍有 AWS CLI 安裝 的某個位置時。

**可能的原因：解除安裝後需要重新啟動終端機**  
如果 `aws --version` 命令仍可運作，您可能需要重新啟動終端機才能辨識任何終端機更新。  
[回到頁首](#cli-chap-troubleshooting-top)

**可能原因： AWS CLI 您在系統上有多個版本的 ，或未使用與原先安裝 相同的解除安裝方法 AWS CLI**  
如果您 AWS CLI 使用與安裝方法不同的方法來解除安裝 ，或者安裝了多個版本，則 AWS CLI 可能無法正確解除安裝。例如，如果您目前的安裝使用 `pip`，您就必須使用 `pip` 將它解除安裝。若要解決此問題， AWS CLI 請使用您用來安裝的相同方法解除安裝 。  

1. 遵循適用於您作業系統的指示和原始的安裝方法，解除安裝 [AWS CLI 第 1 版](https://docs.aws.amazon.com/cli/v1/userguide/cli-chap-install.html)和 [AWS CLI 第 2 版](https://docs.aws.amazon.com/cli/latest/userguide/uninstall.html)。

1. 關閉所有已打開的終端機。

1. 打開您的首選終端機，輸入以下命令並確認沒有傳回任何版本。

   ```
   $ aws --version
   command not found: aws
   ```

   如果您仍然在輸出中列出版本，則很可能使用不同的方法安裝 AWS CLI ，或者有多個版本。如果您不知道安裝了 的方法 AWS CLI，請遵循適用於您作業系統第 [AWS CLI 1 版](https://docs.aws.amazon.com/cli/v1/userguide/cli-chap-install.html)和第 [AWS CLI 2 版](https://docs.aws.amazon.com/cli/latest/userguide/uninstall.html)的每個解除安裝方法的說明，直到沒有收到版本輸出為止。
**注意**  
如果您使用套件管理工具來安裝 AWS CLI (`pip`、`apt`、`brew` 等)，您就必須使用相同的套件管理工具來予以解除安裝。請務必遵循套件管理工具所提供有關如何解除所有版本安裝套件的指示。
[回到頁首](#cli-chap-troubleshooting-top)

## 已 AWS CLI 處理參數名稱不完整的命令
<a name="tshoot-parameter-abbrev"></a>

**可能的原因：您使用了 AWS CLI 參數的可辨識縮寫**  
由於 AWS CLI 是使用 Python 建置，因此 AWS CLI 使用 Python `argparse`程式庫，包括 [https://docs.python.org/3/library/argparse.html#allow-abbrev](https://docs.python.org/3/library/argparse.html#allow-abbrev)引數。參數的縮寫由 辨識 AWS CLI 並處理。  
以下 [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/create-change-set.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/create-change-set.html) 命令範例會將 CloudFormation 堆疊名稱變更。參數`--change-set-n`會辨識為 的縮寫`--change-set-name`，而 會 AWS CLI 處理 命令。  

```
$ aws cloudformation create-change-set --stack-name my-stack --change-set-n my-change-set
```
當縮寫可能是多個命令時，參數將不會識別為縮寫。  
以下 [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/create-change-set.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/create-change-set.html) 命令範例會將 CloudFormation 堆疊名稱變更。參數 `--change-set-` **不能**以縮寫被識別，因為有可能是多個參數的縮寫，例如 `--change-set-name` 和 `--change-set-type`。因此， AWS CLI **不會**處理 命令。  

```
$ aws cloudformation create-change-set --stack-name my-stack --change-set- my-change-set
```
**請勿**特意使用參數縮寫。它們不可靠，不具向後相容性。如果將任何新參數加入混淆縮寫的命令，它將會中斷您的命令。  
此外，如果參數是單值引數，可能會造成您的命令出現非預期的行為。如果傳遞單值引數的多個執行個體，只會執行最後一個執行個體。在下列範例中，參數 `--filters` 是單值引數。已指定參數 `--filters` 和 `--filter`。`--filter` 參數是 `--filters` 的縮寫。這會導致應用 `--filters` 的兩個實例，並且只應用最後一個 `--filter` 參數。  

```
$ aws ec2 describe-vpc-peering-connections \
    --filters Name=tag:TagName,Values=VpcPeeringConnection \
    --filter Name=status-code,Values=active
```
執行命令之前，請確認您使用的是有效的參數，以防止未預期的行為。
[回到頁首](#cli-chap-troubleshooting-top)

## 存取遭拒錯誤
<a name="tshoot-access-denied"></a>

**可能原因： AWS CLI 程式檔案沒有「執行」許可**  
在 Linux 或 macOS 上，確定 `aws` 程式具有呼叫端使用者的執行許可。一般而言，許可會設定為 `755`。  
若要為您的使用者新增執行許可，請執行下列命令，並以電腦上的程式路徑取代 *\$1/.local/bin/aws* 路徑。  

```
$ chmod +x ~/.local/bin/aws
```
[回到頁首](#cli-chap-troubleshooting-top)

**可能原因：您的 IAM 身分沒有執行此操作的許可**  
*範例錯誤文字：*  

```
$ aws s3 ls
An error occurred (AcessDenied) when calling the ListBuckets operation: Access denied.
```
當您執行 AWS CLI 命令時， AWS 操作會代表您執行，並使用與您 IAM 帳戶或角色建立關聯的登入資料。連接的政策必須授予您許可，才能呼叫與您使用 AWS CLI執行之命令相對應的 API 動作。  
大部分的命令均呼叫單一個名稱與命令名稱相符的動作。但是如 `aws s3 sync` 的自訂命令會呼叫多個 API。您可以利用 `--debug` 選項來查看命令呼叫了哪一些 API。  
如果您確定使用者或角色具有政策指派的適當許可，請確定您的 AWS CLI 命令使用您預期的登入資料。請參閱[下一節有關登入資料](#tshoot-permissions-wrongcreds)，以確認 AWS CLI 使用的登入資料是您所預期的登入資料。  
如需指派 IAM 許可的相關資訊，請參閱《[IAM 使用者指南](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction_access-management.html)》中的*存取管理概觀：許可和政策*。  
[回到頁首](#cli-chap-troubleshooting-top)

## 無效的憑證和金鑰錯誤
<a name="tshoot-permissions-wrongcreds"></a>

*範例錯誤文字：*

```
$ aws s3 ls
An error occurred (InvalidAccessKeyId) when calling the ListBuckets operation: The AWS Access Key Id 
you provided does not exist in our records.
```

```
$ aws s3 ls
An error occurred (InvalidClientTokenId) when calling the ListBuckets operation: The security token 
included in the request is invalid.
```

**可能原因： AWS CLI 正在讀取不正確的登入資料，或從非預期的位置讀取**  
 AWS CLI 可能會從您預期的不同位置讀取登入資料，或您的金鑰對資訊不正確。您可以執行 `aws configure list` 以確認使用哪些憑證。  
以下範例說明如何檢查用於預設描述檔的憑證。  

```
$ aws configure list
NAME       : VALUE                : TYPE                    : LOCATION
profile    : <not set>            : None                    : None
access_key : ****************ABCD : shared-credentials-file : 
secret_key : ****************ABCD : shared-credentials-file : 
region     : us-west-2            : env                     : AWS_DEFAULT_REGION
```
以下範例說明如何檢查具名描述檔的憑證。  

```
$ aws configure list --profile dev01
NAME       : VALUE                : TYPE                    : LOCATION
profile    : dev01                : None                    : --profile
access_key : ****************ABCD : shared-credentials-file : 
secret_key : ****************ABCD : shared-credentials-file : 
region     : us-west-2            : config-file             : ~/.aws/config
```
若要確認您的金鑰對詳細資訊，請查看 `config` 和 `credentials` 檔案。如需 `config` 和 `credentials` 檔案的詳細資訊，請參閱 [中的組態和登入資料檔案設定 AWS CLI](cli-configure-files.md)。如需深入了解憑證與身分驗證，包含憑證優先順序，請參閱 [的身分驗證和存取憑證 AWS CLI](cli-chap-authentication.md)。  
[回到頁首](#cli-chap-troubleshooting-top)

**可能原因：電腦的時鐘不同步。**  
如果您使用的是有效憑證，則您的時鐘可能不同步。在 Linux 或 macOS 上，執行 `date` 來檢查時間。  

```
$ date
```
如果您的系統時鐘誤差在幾分鐘內，則請使用 `ntpd` 來進行同步。  

```
$ sudo service ntpd stop
$ sudo ntpdate time.nist.gov
$ sudo service ntpd start
$ ntpstat
```
在 Windows 上，使用控制台的日期與時間選項來設定系統時鐘。  
[回到頁首](#cli-chap-troubleshooting-top)

## 簽章不相符錯誤
<a name="tshoot-signature-does-not-match"></a>

*範例錯誤文字：*

```
$ aws s3 ls
An error occurred (SignatureDoesNotMatch) when calling the ListBuckets operation: The request signature we 
calculated does not match the signature you provided. Check your key and signing method.
```

當 AWS CLI 執行命令時，它會將加密的請求傳送至 AWS 伺服器，以執行適當的 AWS 服務操作。您的登入資料 （存取金鑰和私密金鑰） 會參與加密，並啟用 AWS 來驗證提出請求的人員。有幾種情況可能會干擾此程序的正確操作，如下所述。

**可能原因：您的時鐘與 AWS 伺服器不同步**  
為了協助防止[重送攻擊](https://wikipedia.org/wiki/Replay_attack)，可以在加密/解密程序期間使用目前時間。如果用戶端和伺服器的時間差異超過允許的數量，程序可能會失敗並拒絕請求。當您在時鐘與主機時鐘不同步的虛擬機器中執行命令，也可能發生這種情況。其中一個可能的原因是虛擬機器休眠，在喚醒後需要一些時間才能與主機的時鐘同步。  
在 Linux 或 macOS 上，執行 `date` 來檢查時間。  

```
$ date
```
如果您的系統時鐘誤差在幾分鐘內，則請使用 `ntpd` 來進行同步。  

```
$ sudo service ntpd stop
$ sudo ntpdate time.nist.gov
$ sudo service ntpd start
$ ntpstat
```
在 Windows 上，使用控制台的日期與時間選項來設定系統時鐘。  
[回到頁首](#cli-chap-troubleshooting-top)

**可能原因：您的作業系統正在錯誤處理包含特定特殊字元的 AWS 金鑰**  
如果您的 AWS 金鑰包含某些特殊字元，例如 `-`、`/`、 `+`或 `%`，則某些作業系統變體會不當處理字串，並導致錯誤解譯金鑰字串。  
如果您使用其他工具或指令碼來處理金鑰，例如在新執行個體上建置登入資料檔案的工具，這些工具和指令碼可能會自行處理特殊字元，導致它們轉換為 AWS 無法辨識的項目。  
我們建議重新產生私密金鑰，以取得不包含導致問題的特殊字元的私密金鑰。  
[回到頁首](#cli-chap-troubleshooting-top)

## SSL 憑證錯誤
<a name="tshoot-certificate-verify-failed"></a>

**可能原因： AWS CLI 不信任代理的憑證**  
*範例錯誤文字：*  

```
$ aws s3 ls
[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed
```
當您使用 AWS CLI 命令時，會收到`[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed`錯誤訊息。這是因為 AWS CLI 不信任代理的憑證，因為代理的憑證是自我簽署等因素，而您的公司設定為憑證授權機構 (CA)。這可防止 AWS CLI 在本機 CA 登錄中找到您公司的 CA 根憑證。  
若要修正此問題，請指示 使用`ca\$1bundle`組態`.pem`檔案設定、**[--ca-bundle](cli-configure-options.md#cli-configure-options-ca-bundle)**命令列選項或`AWS\$1CA\$1BUNDLE`環境變數來尋找公司檔案 AWS CLI 的位置。  
[回到頁首](#cli-chap-troubleshooting-top)

**可能的原因：您的配置未指向正確的 CA 根憑證位置**  
*範例錯誤文字：*  

```
$ aws s3 ls
SSL validation failed for regionname [Errno 2] No such file or directory
```
這是由於您的憑證授權機構 (CA) 套件檔案位置在 AWS CLI中被錯誤設定。若要解決這個問題，請確認您公司 `.pem` 檔案的位置，然後使用 `ca\$1bundle` 組態檔案設定、**[--ca-bundle](cli-configure-options.md#cli-configure-options-ca-bundle)** 命令列選項或 `AWS\$1CA\$1BUNDLE` 環境變數，更新 AWS CLI 組態。  
[回到頁首](#cli-chap-troubleshooting-top)

**可能原因：您的組態未使用正確的 AWS 區域**  
*範例錯誤文字：*  

```
$ aws s3 ls
[SSL: CERTIFICATE_ VERIFY_FAILED] certificate verify failed
```
如果您指定的 AWS 服務 無法使用，或您的資源位於不同的 中，則可能會發生錯誤 AWS 區域 或非預期的結果 AWS 區域。如需疑難排解步驟，請參閱[檢查您的 AWS 區域 AWS CLI 命令正在使用](#general-region)。  
[回到頁首](#cli-chap-troubleshooting-top)

**可能原因：您的 TLS 版本需要更新 **  
*範例錯誤文字：*  

```
$ aws s3 ls
[SSL: UNSAFE_LEGACY_RENEGOTIATION_DISABLED] unsafe legacy renegotiation disabled
```
 AWS 服務 使用的 TLS 版本與您裝置的 TLS 版本不相容。若要解決此問題，請更新至支援的 TLS 版本。如需詳細資訊，請參閱 [為 強制執行最低版本的 TLS AWS CLI](cli-security-enforcing-tls.md)。  
[回到頁首](#cli-chap-troubleshooting-top)

## JSON 無效錯誤
<a name="tshoot-invalid-json"></a>

*範例錯誤文字：*

```
$ aws dynamodb update-table \
    --provisioned-throughput '{"ReadCapacityUnits":15,WriteCapacityUnits":10}' \
    --table-name MyDDBTable
Error parsing parameter '--provisioned-throughput': Invalid JSON: Expecting property name enclosed in 
double quotes: line 1 column 25 (char 24)
JSON received: {"ReadCapacityUnits":15,WriteCapacityUnits":10}
```

當您使用 AWS CLI 命令時，會收到「`Invalid JSON`」錯誤訊息。當您輸入具有預期 JSON 格式的命令，且 AWS CLI 無法正確讀取 JSON 時，通常會看到此錯誤。

**可能原因：您未輸入有效的 JSON AWS CLI 供 使用**  
請確定您已為命令輸入有效的 JSON。我們建議您為有格式化問題的 JSON 使用 JSON 驗證器。  
若要在命令列中使用更進階的 JSON，請考慮使用 `jq` 之類的命令列 JSON 處理器來建立 JSON 字串。如需 `jq` 的詳細資訊，請參閱 *GitHub* 上的 [jq 儲存庫](http://stedolan.github.io/jq/)。  
[回到頁首](#cli-chap-troubleshooting-top)

**可能原因：終端機的引號規則阻止有效的 JSON 傳送至 AWS CLI**  
從命令 AWS CLI 接收任何內容之前，您的終端機會使用自己的引號和逸出規則來處理命令。由於終端機的格式化規則，您的部分 JSON 內容可能在命令傳遞至 AWS CLI之前遭除去。格式化命令時，務必使用[終端機的引號規則](cli-usage-parameters-quoting-strings.md)。  
若要進行疑難排解，請使用 `echo` 命令查看 shell 如何處理您的參數：  

```
$ echo {"ReadCapacityUnits":15,"WriteCapacityUnits":10}
ReadCapacityUnits:15 WriteCapacityUnits:10
```

```
$ echo '{"ReadCapacityUnits":15,"WriteCapacityUnits":10}'
{"ReadCapacityUnits":15,"WriteCapacityUnits":10}
```
修改您的命令，直到傳回有效的 JSON 為止。  
如需深入疑難排解的詳細資訊，請使用 `--debug` 參數查看偵錯日誌，日誌將準確顯示傳遞至 AWS CLI的內容：  

```
$ aws dynamodb update-table \
    --provisioned-throughput '{"ReadCapacityUnits":15,WriteCapacityUnits":10}' \
    --table-name MyDDBTable \
    --debug
2022-07-19 22:25:07,741 - MainThread - awscli.clidriver - DEBUG - CLI version: aws-cli/1.18.147 
Python/2.7.18 Linux/5.4.196-119.356.amzn2int.x86_64 botocore/1.18.6
2022-07-19 22:25:07,741 - MainThread - awscli.clidriver - DEBUG - Arguments entered to CLI: 
['dynamodb', 'update-table', '--provisioned-throughput', '{"ReadCapacityUnits":15,WriteCapacityUnits":10}',
 '--table-name', 'MyDDBTable', '--debug']
```
請用終端機的引號規則修正 JSON 輸入在傳送至 AWS CLI時可能發生的任何問題。如需引號規則的詳細資訊，請參閱[在 中使用引號和常值搭配字串 AWS CLI](cli-usage-parameters-quoting-strings.md)。  
如果您在取得有效的 JSON 到 時遇到問題 AWS CLI，建議您使用 Blob 直接將 JSON 資料傳遞至 ，以略過終端機的 JSON 資料輸入引號規則 AWS CLI。如需 Blobs 的詳細資訊，請參閱 [Blob](cli-usage-parameters-types.md#parameter-type-blob)。
[回到頁首](#cli-chap-troubleshooting-top)

## 其他資源
<a name="tshoot-resources"></a>

如需 AWS CLI 問題的其他協助，請造訪 *GitHub* 上的 [AWS CLI 社群](https://github.com/aws/aws-cli/issues)或 [AWS re:Post 社群](https://repost.aws/)。

[回到頁首](#cli-chap-troubleshooting-top)