

# Using the AWS CLI
<a name="cli-chap-using"></a>

This section provides a comprehensive overview of the general use, common features, and options available in the AWS Command Line Interface (AWS CLI), going beyond the details covered in the Configuration [Using endpoints in the AWS CLI](cli-configure-endpoints.md) section. 

This guide delves into the fundamental aspects of writing AWS CLI commands, including their basic structure, formatting, and filtering capabilities. By understanding these core elements, you'll be able to construct commands that precisely target the resources and actions you require, without the need to navigate complex web-based consoles.

Additionally, this highlights the help content and documentation available for the AWS CLI. From the built-in command line help to the comprehensive [AWS CLI version 2 reference guide](https://docs.aws.amazon.com/cli/latest/reference/), you'll have access to information to assist you in exploring the features and capabilities of the AWS CLI. 

For AWS service specific examples and use cases, see [Examples for the AWS CLI](cli-chap-code-examples.md) or the [AWS CLI version 2 reference guide](https://docs.aws.amazon.com/cli/latest/reference/). These provide command specific information and demonstrate examples on how to leverage the AWS CLI for various AWS services.

**Note**  
By default, the AWS CLI sends requests to AWS services by using HTTPS on TCP port 443. To ensure successful use of the AWS CLI, you must be able to make outbound connections on this port.

**Topics**
+ [Accessing help and resources for the AWS CLI](cli-usage-help.md)
+ [Command structure in the AWS CLI](cli-usage-commandstructure.md)
+ [Specifying parameter values in the AWS CLI](cli-usage-parameters.md)
+ [Enabling and using command prompts in the AWS CLI](cli-usage-parameters-prompting.md)
+ [Controlling command output in the AWS CLI](cli-usage-output.md)
+ [Command line return codes in the AWS CLI](cli-usage-returncodes.md)
+ [Using custom wizards to run interactive commands in the AWS CLI](cli-usage-wizard.md)
+ [Creating and using aliases in the AWS CLI](cli-usage-alias.md)
+ [Troubleshooting errors for the AWS CLI](cli-chap-troubleshooting.md)

# Accessing help and resources for the AWS CLI
<a name="cli-usage-help"></a>

This topic describes how to access help content for the AWS Command Line Interface (AWS CLI).

**Topics**
+ [The built-in AWS CLI help command](#cli-usage-help-command)
+ [AWS CLI reference guide](#cli-reference)
+ [API documentation](#api-reference)
+ [Troubleshooting errors](#help-tshoot)
+ [Additional help](#help-additional)

## The built-in AWS CLI help command
<a name="cli-usage-help-command"></a>

You can get help with any command when using the AWS Command Line Interface (AWS CLI). To do so, simply type `help` at the end of a command name. 

For example, the following command displays help for the general AWS CLI options and the available top-level commands. 

```
$ aws help
```

The following command displays the available Amazon Elastic Compute Cloud (Amazon EC2) specific commands. 

```
$ aws ec2 help
```

The following example displays detailed help for the Amazon EC2 `DescribeInstances` operation. The help includes descriptions of its input parameters, available filters, and what is included as output. It also includes examples showing how to type common variations of the command.

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

As of version `2.31.0` The display for the `help` command is configured by the `cli_help_output` setting, and has the following values:
+  **(default)** `terminal` ‐ Open the man page in the terminal.
+ `browser` ‐ Open the man page as a local HTML file in your default browser. A notice is printed to your terminal when your default browser is being opened, and an error message if the AWS CLI cannot open your browser.
+ `url` ‐ Print the URL to the online AWS CLI Reference Guide for the version of the AWS CLI you have installed. Settings for client-side paging, such as the `AWS_PAGER` environment variable, is respected.

The help content for each command is divided into six sections:

Name  
The name of the command.  

```
NAME
       describe-instances -
```

Description  
A description of the API operation that the command invokes.  

```
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  
The basic syntax for using the command and its options. If an option is shown in square brackets, it's optional, has a default value, or has an alternative option that you can use.  

```
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]
```
For example, `describe-instances` has a default behavior that describes ***all*** instances in the current account and AWS Region. You can optionally specify a list of `instance-ids` to describe one or more instances; `dry-run` is an optional Boolean flag that doesn't take a value. To use a Boolean flag, specify either shown value, in this case `--dry-run` or `--no-dry-run`. Likewise, `--generate-cli-skeleton` doesn't take a value. If there are conditions on an option's use, they are described in the `OPTIONS` section, or shown in the examples.

Options  
A description of each of the options shown in the synopsis.  

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

Examples  
Examples showing the usage of the command and its options. If no example is available for a command or use case that you need, request one using the feedback link on this page, or in the AWS CLI command reference on the help page for the command.  

```
    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  
Descriptions of each of the fields and data types included in the response from AWS.  
For `describe-instances`, the output is a list of reservation objects, each of which contains several fields and objects that contain information about the instances associated with it. This information comes from the [API documentation for the reservation data type](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_Reservation.html) used by Amazon EC2.  

```
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.
...
```
When the AWS CLI renders the output into JSON, it becomes an array of reservation objects, similar to the following example.  

```
{
    "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"
                    },
...
```
Each reservation object contains fields describing the reservation and an array of instance objects, each with its own fields (for example, `PublicDnsName`) and objects (for example, `State`) that describe it.  
**Windows users**  
You can *pipe* (\$1) the output of the help command to the `more` command to view the help file one page at a time. Press the space bar or **PgDn** to view more of the document, and **q** to quit.   

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

## AWS CLI reference guide
<a name="cli-reference"></a>

The help files contain links that cannot be viewed or navigated to from the command line. You can view and interact with these links by using the online [AWS CLI version 2 reference guide](https://docs.aws.amazon.com/cli/latest/reference/index.html). The reference also contains the help content for all AWS CLI commands. The descriptions are presented for easy navigation and viewing on mobile, tablet, or desktop screens. 

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

All commands in the AWS CLI correspond to requests made to an AWS service's public API. Each service with a public API has an API reference that can be found on the service's home page on the [AWS Documentation website](https://docs.aws.amazon.com/). The content for an API reference varies based on how the API is constructed and which protocol is used. Typically, an API reference contains detailed information about the operations supported by the API, the data sent to and from the service, and any error conditions that the service can report. 

**API Documentation Sections**
+  **Actions** – Detailed information on each operation and its parameters (including constraints on length or content, and default values). It lists the errors that can occur for this operation. Each operation corresponds to a subcommand in the AWS CLI. 
+  **Data Types** – Detailed information about structures that a command might require as a parameter, or return in response to a request.
+  **Common Parameters** – Detailed information about the parameters that are shared by all of action for the service. 
+  **Common Errors** – Detailed information about errors that can be returned by any of the service's operations. 

The name and availability of each section can vary, depending on the service. 

**Service-specific CLIs**  
Some services have a separate CLI that dates from before a single AWS CLI was created to work with all services. These service-specific CLIs have separate documentation that is linked from the service's documentation page. Documentation for service-specific CLIs do not apply to the AWS CLI. 

## Troubleshooting errors
<a name="help-tshoot"></a>

For help diagnosing and fixing AWS CLI errors, see [Troubleshooting errors for the AWS CLI](cli-chap-troubleshooting.md).

## Additional help
<a name="help-additional"></a>

For additional help with your AWS CLI issues, visit the [AWS CLI community](https://github.com/aws/aws-cli/issues) on *GitHub*.

# Command structure in the AWS CLI
<a name="cli-usage-commandstructure"></a>

This topic covers how AWS Command Line Interface (AWS CLI) command is structured, and how to use wait commands.

**Topics**
+ [Command structure](#cli-usage-commandstructure-structure.title)
+ [Wait commands](#cli-usage-commandstructure-wait)

## Command structure
<a name="cli-usage-commandstructure-structure.title"></a>

The AWS CLI uses a multipart structure on the command line that must be specified in this order:

1. The base call to the `aws` program.

1. The top-level *command*, which typically corresponds to an AWS service supported by the AWS CLI.

1. The *subcommand* that specifies which operation to perform.

1. General AWS CLI options or parameters required by the operation. You can specify these in any order as long as they follow the first three parts. If an exclusive parameter is specified multiple times, only the *last value* applies.

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

Parameters can take various types of input values, such as numbers, strings, lists, maps, and JSON structures. What is supported is dependent upon the command and subcommand you specify.

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

**Amazon S3**

The following example lists all of your Amazon S3 buckets.

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

For more information on the Amazon S3 commands, see [https://docs.aws.amazon.com/cli/latest/reference/s3/index.html](https://docs.aws.amazon.com/cli/latest/reference/s3/index.html) in the *AWS CLI Command Reference*.

**AWS CloudFormation**

The following [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)command example changes the cloudformation stack name to *my-change-set*.

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

For more information on the AWS CloudFormation commands, see [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/index.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/index.html) in the *AWS CLI Command Reference*.

## Wait commands
<a name="cli-usage-commandstructure-wait"></a>

Some AWS services have `wait` commands available. Any command that uses `aws wait` usually waits until a command is complete before it moves on to the next step. This is especially useful for multipart commands or scripting, as you can use a wait command to prevent moving to subsequent steps if the wait command fails.

The AWS CLI uses a multipart structure on the command line for the `wait` command that must be specified in this order:

1. The base call to the `aws` program.

1. The top-level *command*, which typically corresponds to an AWS service supported by the AWS CLI.

1. The `wait` command.

1. The *subcommand* that specifies which operation to perform.

1. General CLI options or parameters required by the operation. You can specify these in any order as long as they follow the first three parts. If an exclusive parameter is specified multiple times, only the *last value* applies.

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

Parameters can take various types of input values, such as numbers, strings, lists, maps, and JSON structures. What is supported is dependent upon the command and subcommand you specify.

**Note**  
Not every AWS service supports `wait` commands. See the [AWS CLI version 2 reference guide](https://docs.aws.amazon.com/cli/latest/reference/index.html) to see if your service supports `wait` commands.

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

**AWS CloudFormation**

The following [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) command examples pauses and resumes only after it can confirm that the *my-change-set* change set in the *my-stack* stack is ready to run.

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

For more information on the AWS CloudFormation `wait` commands, see [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/wait/index.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/wait/index.html) in the *AWS CLI Command Reference*.

**AWS CodeDeploy**

The following [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) command examples pauses until the *d-A1B2C3111* deployment completes successfully.

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

For more information on the AWS CodeDeploy `wait` commands, see [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/wait/index.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/wait/index.html) in the *AWS CLI Command Reference*.

# Specifying parameter values in the AWS CLI
<a name="cli-usage-parameters"></a>

Many parameters used in the AWS Command Line Interface (AWS CLI) are simple string or numeric values, such as the key-pair name `my-key-pair` in the following `aws ec2 create-key-pair` command example. 

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

Formatting for command can vary between terminals. For example, most terminals are case sensitive but Powershell is case insensitive. This means the two following command examples would yield different results for case sensitive terminals as they view `MyFile*.txt` and `myfile*.txt` as **different** parameters. 

However, PowerShell would process these requests as the same as it sees `MyFile*.txt` and `myfile*.txt` as the **same** parameters. The following command example demonstrates these paramaters using the `aws s3 cp` command:

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

For more information on PowerShell's case insensitivy, see [about\$1Case-Sensitivity](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_case-sensitivity) in the *PowerShell documentation*.

Sometimes you need to use quotation marks or literals around strings that include special or space characters. The rules around this formatting can also vary between terminals. For more information about using quotation marks around complex parameters, see [Using quotation marks and literals with strings in the AWS CLI](cli-usage-parameters-quoting-strings.md).

These topics cover the most common terminal formatting rules. If you are having issues with your terminal recognizing your parameter values, be sure to review the topics in this section and also to check your terminal's documentation for their specific syntax rules.

**Topics**
+ [Common parameter types in the AWS CLI](cli-usage-parameters-types.md)
+ [Using quotation marks and literals with strings in the AWS CLI](cli-usage-parameters-quoting-strings.md)
+ [Loading a parameter from a file in the AWS CLI](cli-usage-parameters-file.md)
+ [AWS CLI skeletons and input files in the AWS CLI](cli-usage-skeleton.md)
+ [Using shorthand syntax in the AWS CLI](cli-usage-shorthand.md)

# Common parameter types in the AWS CLI
<a name="cli-usage-parameters-types"></a>

This section describes some of the common parameter types and the typical required format. 

If you are having trouble formatting a parameter for a specific command, check the help by entering **help** after the command name. The help for each subcommand includes an option's name and description. The option's parameter type is listed in parentheses. For more information on viewing help, see [Accessing help and resources for the AWS CLI](cli-usage-help.md).

**Topics**
+ [String](#parameter-type-string)
+ [Timestamp](#parameter-type-timestamp)
+ [List](#parameter-type-list)
+ [Boolean](#parameter-type-boolean)
+ [Integer](#parameter-type-integer)
+ [Binary / blob (binary large object) and streaming blob](#parameter-type-blobs)
+ [Map](#parameter-type-map)
+ [Document](#parameter-type-document)

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

String parameters can contain alphanumeric characters, symbols, and white spaces from the [ASCII](https://wikipedia.org/wiki/ASCII) character set. Strings that contain white spaces must be surrounded by quotation marks. We recommend that you don't use symbols or white spaces other than the standard space character and to observe your terminal's [quoting rules](cli-usage-parameters-quoting-strings.md) to prevent unexpected results.

Some string parameters can accept binary data from a file. See [Binary files](cli-usage-parameters-file.md#cli-usage-parameters-file-binary) for an example. 

## Timestamp
<a name="parameter-type-timestamp"></a>

Timestamps are formatted according to the [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) standard. These are often referred to as "`DateTime`" or "`Date`" parameters. 

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

Acceptable formats include:
+ *YYYY*-*MM*-*DD*T*hh*:*mm*:*ss.sss**TZD (UTC)*, for example, 2014-10-01T20:30:00.000Z
+ *YYYY*-*MM*-*DD*T*hh*:*mm*:*ss.sss**TZD (with offset)*, for example, 2014-10-01T12:30:00.000-08:00
+ *YYYY*-*MM*-*DD*, for example, 2014-10-01
+ Unix time in seconds, for example, 1412195400. This is sometimes referred to as [Unix Epoch time](https://wikipedia.org/wiki/Unix_time) and represents the number of seconds since midnight, January 1, 1970 UTC.

By default, the AWS CLI version 2 translates all ***response*** DateTime values to ISO 8601 format.

You can set the timestamp format by using the `cli\$1timestamp\$1format` file setting.

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

One or more strings separated by spaces. If any of the string items contain a space, you must put quotation marks around that item. Observe your terminal's [quoting rules](cli-usage-parameters-quoting-strings.md) to prevent unexpected results.

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

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

Binary flag that turns an option on or off. For example, `ec2 describe-spot-price-history` has a Boolean `--dry-run` parameter that, when specified, validates the query with the service without actually running the query. 

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

The output indicates whether the command was well formed. This command also includes a `--no-dry-run` version of the parameter that you can use to explicitly indicate that the command should be run normally. Including it isn't necessary because this is the default behavior. 

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

An unsigned, whole number.

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

## Binary / blob (binary large object) and streaming blob
<a name="parameter-type-blobs"></a>

In the AWS CLI, you can pass a binary value as a string directly on the command line. There are two types of blobs:
+ [Blob](#parameter-type-blob)
+ [Streaming blob](#parameter-type-streaming-blob)

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

To pass a value to a parameter with type `blob`, you must specify a path to a local file that contains the binary data using the `fileb://` prefix. Files referenced using the `fileb://` prefix are always treated as raw unencoded binary. The specified path is interpreted as being relative to the current working directory. For example, the `--plaintext` parameter for `aws kms encrypt` is a blob.

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

**Note**  
For backwards compatibility, you can use the `file://` prefix. There are two formats used based on the file setting `cli\$1binary\$1format` or `--cli-binary-format` command line option:  
Default for the AWS CLI version 2. If the setting's value is `base64`, files referenced using the `file://` prefix are treated as base64-encoded text. 
Default for the AWS CLI version 1. If the setting's value is `raw-in-base64-out`, files referenced using the `file://` prefix is read as text and then the AWS CLI attempts to encode it to binary.
For more information, see the file setting `cli\$1binary\$1format` or `--cli-binary-format` command line option.

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

Streaming blobs such as `aws cloudsearchdomain upload-documents` do not use prefixes. Instead, streaming blob parameters are formatted using the direct file path. The following example uses the direct file path `document-batch.json` for the `aws cloudsearchdomain upload-documents` command:

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

A set of key-value pairs specified in JSON or by using the CLI's [shorthand syntax](cli-usage-shorthand.md). The following JSON example reads an item from an Amazon DynamoDB table named *my-table* with a map parameter, `--key`. The parameter specifies the primary key named *id* with a number value of *1* in a nested JSON structure.

For more advanced JSON usage in a command line, consider using a command line JSON processor, like `jq`, to create JSON strings. For more information on `jq`, see the [jq repository](http://stedolan.github.io/jq/) on *GitHub*.

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

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

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

**Note**  
[Shorthand syntax](cli-usage-shorthand.md) is not compatible with document types.

Document types are used to send data without needing to embed JSON inside strings. The document type enables services to provide arbitrary schemas for you to use more flexible data types. 

This allows for sending JSON data without needing to escape values. For example, instead of using the following escaped JSON input:

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

You can use the following document type:

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

### Valid values for document types
<a name="parameter-type-document-valid"></a>

Due to the flexible nature of document types, there are multiple valid value types. Valid values include the following:

**String**  

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

**Number**  

```
--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"}]'
```

**Object**  

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

# Using quotation marks and literals with strings in the AWS CLI
<a name="cli-usage-parameters-quoting-strings"></a>

There are primarily two ways single and double quotes are used in the AWS CLI.
+ [Using quotation marks around strings that contain white spaces](#cli-usage-parameters-quoting-strings-around)
+ [Using quotation marks inside strings](#cli-usage-parameters-quoting-strings-containing)

## Using quotation marks around strings that contain white spaces
<a name="cli-usage-parameters-quoting-strings-around"></a>

Parameter names and their values are separated by spaces on the command line. If a string value contains an embedded space, then you must surround the entire string with quotation marks to prevent the AWS CLI from misinterpreting the space as a divider between the value and the next parameter name. Which type of quotation mark you use depends on the operating system you are running the AWS CLI on.

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

Use single quotation marks `' '` 

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

For more information on using quotes, see the user documentation for your preferred shell.

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

**Single quotations (recommended)**

Single quotation marks `' '` are called `verbatim` strings. The string is passed to the command exactly as you type it, which means PowerShell variables will not pass through.

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

**Double quotations**

Double quotation marks `" "` are called `expandable` string. Variables can be passed in expandable strings.

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

For more information on using quotes, see [About Quoting Rules](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_quoting_rules?view=powershell-7) in the *Microsoft PowerShell Docs*.

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

Use double quotation marks `" "` .

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

------

Optionally, you can separate the parameter name from the value with an equals sign `=` instead of a space. This is typically necessary only if the value of the parameter starts with a hyphen.

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

## Using quotation marks inside strings
<a name="cli-usage-parameters-quoting-strings-containing"></a>

Strings might contain quotation marks, and your shell might require escaping quotations for them to work properly. One of the common parameter value types is a JSON string. This is complex since it includes spaces and double quotation marks `" "` around each element name and value in the JSON structure. The way you enter JSON-formatted parameters on the command line differs depending on your operating system. 

For more advanced JSON usage in the command line, consider using a command line JSON processor, like `jq`, to create JSON strings. For more information on `jq`, see the [jq repository](http://stedolan.github.io/jq/) on *GitHub*.

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

For Linux and macOS to interpret strings literally use single quotation marks `' '` to enclose the JSON data structure, as in the following example. You do not need to escape double quotation marks embedded in the JSON string, as they are being treated literally. Since the JSON is enclosed in single quotation marks, any single quotation marks in the string will need to be escaped, this is usually accomplished using a backslash before the single quote `\'`.

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

For more information on using quotes, see the user documentation for your preferred shell.

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

Use single quotation marks `' '` or double quotation marks `" "`.

**Single quotations (recommended)**

Single quotation marks `' '` are called `verbatim` strings. The string is passed to the command exactly as you type it, which means PowerShell variables will not pass through.

Since JSON data structures include double quotes, we suggest **single** quotation marks `' '` to enclose it. If you use **single** quotation marks, you do not need to escape **double** quotation marks embedded in the JSON string. However, you need to escape each **single** quotation mark with a backtick ``` within the JSON structure.

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

**Double quotations**

Double quotation marks `" "` are called `expandable` strings. Variables can be passed in expandable strings.

If you use **double** quotation marks, you do not need to escape **single** quotation marks embedded in the JSON string. However, you need to escape each **double** quotation mark with a backtick ``` within the JSON structure, as with the following example.

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

For more information on using quotes, see [About Quoting Rules](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_quoting_rules?view=powershell-7) in the *Microsoft PowerShell Docs*.

**Warning**  
Before PowerShell sends a command to the AWS CLI, it determines if your command is interpreted using typical PowerShell or `CommandLineToArgvW` quoting rules. When PowerShell processes using `CommandLineToArgvW`, you must escape characters with a backslash `\`.  
For more information on `CommandLineToArgvW` in PowerShell, see [What's up with the strange treatment of quotation marks and backslashes by CommandLineToArgvW](https://devblogs.microsoft.com/oldnewthing/20100917-00/?p=12833) in the *Microsoft DevBlogs*, [Everyone quotes command line arguments the wrong way](https://docs.microsoft.com/en-us/archive/blogs/twistylittlepassagesallalike/everyone-quotes-command-line-arguments-the-wrong-way) in the *Microsoft Docs Blog*, and [CommandLineToArgvW function](https://docs.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-commandlinetoargvw#remarks) in the *Microsoft Docs*.  
**Single quotations**  
Single quotation marks `' '` are called `verbatim` strings. The string is passed to the command exactly as you type it, which means PowerShell variables will not pass through. Escape characters with a backslash `\`.  

```
PS C:\> aws ec2 run-instances `
    --image-id ami-12345678 `
    --block-device-mappings '[{\"DeviceName\":\"/dev/sdb\",\"Ebs\":{\"VolumeSize\":20,\"DeleteOnTermination\":false,\"VolumeType\":\"standard\"}}]'
```
**Double quotations**  
Double quotation marks `" "` are called `expandable` strings. Variables can be passed in `expandable` strings. For double quoted strings you have to escape twice using *`\$1* for each quote instead of only using a backtick. The backtick escapes the backslash, and then the backslash is used as an escape character for the `CommandLineToArgvW` process.  

```
PS C:\> aws ec2 run-instances `
    --image-id ami-12345678 `
    --block-device-mappings "[{`\"DeviceName`\":`\"/dev/sdb`\",`\"Ebs`\":{`\"VolumeSize`\":20,`\"DeleteOnTermination`\":false,`\"VolumeType`\":`\"standard`\"}}]"
```
**Blobs (recommended)**  
To bypass PowerShell quoting rules for JSON data input, use Blobs to pass your JSON data directly to the AWS CLI. For more information on Blobs, see [Blob](cli-usage-parameters-types.md#parameter-type-blob).

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

The Windows command prompt requires double quotation marks `" "` to enclose the JSON data structure. Also, to prevent the command processor from misinterpreting the double quotation marks embedded in the JSON, you must also escape (precede with a backslash `\` character) each double quotation mark `"` within the JSON data structure itself, as in the following example. 

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

Only the outermost double quotation marks are not escaped.

------

# Loading a parameter from a file in the AWS CLI
<a name="cli-usage-parameters-file"></a>

Some parameters expect file names as arguments, from which the AWS CLI loads the data. Other parameters enable you to specify the parameter value as either text typed on the command line or read from a file. Whether a file is required or optional, you must encode the file correctly so that the AWS CLI can understand it. The file's encoding must match the reading system's default locale. You can determine this by using the Python `locale.getpreferredencoding()` method.

This method is for loading a file for a single parameter. For information on loading multiple parameters with a single file, see [AWS CLI skeletons and input files in the AWS CLI](cli-usage-skeleton.md).

**Note**  
By default, Windows PowerShell outputs text as UTF-16, which conflicts with the UTF-8 encoding used by JSON files and many Linux systems. We recommend that you use `-Encoding ascii` with your PowerShell `Out-File` commands to ensure the AWS CLI can read the resulting file. 

**Topics**
+ [How to load a parameter from a file](#cli-usage-parameters-file-how)
+ [Binary files](#cli-usage-parameters-file-binary)
+ [Loading a file as a shorthand syntax value](#cli-usage-parameters-file-shorthand)

## How to load a parameter from a file
<a name="cli-usage-parameters-file-how"></a>

Sometimes it's convenient to load a parameter value from a file instead of trying to type it all as a command line parameter value, such as when the parameter is a complex JSON string. To specify a file that contains the value, specify a file URL in the following format.

```
file://complete/path/to/file
```
+ The first two slash '/' characters are part of the specification. If the required path begins with a '/', the result is three slash characters: `file:///folder/file`.
+ The URL provides the path to the file that contains the actual parameter content. 
+ When using files with spaces or special characters, follow the [quoting and escaping rules](cli-usage-parameters-quoting-strings.md) for your terminal. 

The file paths in the following examples are interpreted to be relative to the current working directory.

------
#### [ 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"
```

------

The `file://` prefix option supports Unix-style expansions, including "`~/`", "`./`", and "`../`". On Windows, the "`~/`" expression expands to your user directory, stored in the `%USERPROFILE%` environment variable. For example, on Windows 10 you would typically have a user directory under `%USERPROFILE%`.

You must still escape JSON documents that are embedded as the value of another JSON document.

```
$ 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\"}"
}
```

## Binary files
<a name="cli-usage-parameters-file-binary"></a>

For commands that take binary data as a parameter, specify that the data is binary content by using the `fileb://` prefix. Commands that accept binary data include: 
+  **`aws ec2 run-instances:`** `--user-data` parameter. 
+  **`aws s3api put-object:`** `--sse-customer-key` parameter. 
+  **`aws kms decrypt:`** `--ciphertext-blob` parameter. 

The following example generates a binary 256-bit AES key using a Linux command line tool, and then provides it to Amazon S3 to encrypt an uploaded file server-side. 

```
$ 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\""
}
```

For another example referencing a file containing JSON-formatted parameters, see [Attaching an IAM managed policy to a user](cli-services-iam.md#cli-services-iam-policy). 

## Loading a file as a shorthand syntax value
<a name="cli-usage-parameters-file-shorthand"></a>

When using shorthand syntax where a value is large or complex, it is often easier to load in a file as a value. To load a file as a shorthand syntax value, the formatting will change slightly. Instead of `key=value` you'll use the `@=` operator instead of the `=` operator. The `@=` signifies to the AWS CLI that the value should be read as a file path and not a string. The following example shows a key-value pair loading a file for its value.

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

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

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

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

------

The following example demonstrates loading a certificate file for the `aws rolesanywhere create-trust-anchor` command.

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

For more information on shorthand syntax, see [Using shorthand syntax in the AWS CLI](cli-usage-shorthand.md).

# AWS CLI skeletons and input files in the AWS CLI
<a name="cli-usage-skeleton"></a>

Most of the AWS CLI commands accept importing parameter inputs from a file. These templates can be generated using the `generate-cli-skeleton` option and then be imported using the `--cli-input-json` and `--cli-input-yaml` parameters.

**Topics**
+ [About AWS CLI skeletons and input files](#cli-usage-skeleton-about)
+ [Generate and import a command skeleton](#cli-usage-skeleton-generate)
+ [Combining input files and command line parameters](#cli-usage-skeleton-combine)

## About AWS CLI skeletons and input files
<a name="cli-usage-skeleton-about"></a>

Most of the AWS Command Line Interface (AWS CLI) commands support the ability to accept parameter inputs from a file using the `--cli-input-json` and `--cli-input-yaml` parameters.

Those same commands use the `--generate-cli-skeleton` parameter to generate a file in either JSON or YAML format with all of the parameters that you can edit and fill in. Then you can run the command with the `--cli-input-json` or `--cli-input-yaml` parameter and point to the filled-in file.

**Important**  
Custom AWS CLI commands, such as the [`aws s3` commands](https://docs.aws.amazon.com/cli/latest/reference/s3/index.html) don't support either the `--generate-cli-skeleton` or `--cli-input-json` and `--cli-input-yaml` parameters described in this topic. To check if a specific command supports these parameters, run the [`help` command](cli-usage-help.md#cli-usage-help-command) for the command you want to use or refer to the [AWS CLI version 2 reference guide](https://docs.aws.amazon.com/cli/latest/reference/index.html).

The `--generate-cli-skeleton` generates and displays a parameter template that you can customize and use as input on a command. The generated template includes all of the parameters that the command supports.

The `--generate-cli-skeleton` parameter accepts one of the following values:
+ `input` – The generated template includes all input parameters formatted as JSON. This is the default value.
+ `yaml-input` – The generated template includes all input parameters formatted as YAML.
+ `output` – The generated template includes all output parameters formatted as JSON. You can't currently request the output parameters as YAML. 

Because the AWS CLI is essentially a "wrapper" around the service's API, the skeleton file expects you to reference all parameters by their underlying API parameter names. This is likely different from the AWS CLI parameter name. For example, an AWS CLI parameter named `user-name` might map to the AWS service's API parameter named `UserName` (notice the altered capitalization and missing dash). We recommend that you use the `--generate-cli-skeleton` option to generate the template with the "correct" parameter names to avoid errors. You can reference the API Reference Guide for the service to see the expected parameter names. You can delete any parameters from the template that are not required and for which you don't want to supply a value.

For example, if you run the following command, it generates the parameter template for the Amazon Elastic Compute Cloud (Amazon EC2) command **run-instances**.

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

The following example shows how to generate a template formatted in JSON by using the default value (`input`) for the `--generate-cli-skeleton` parameter.

```
$ 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 ]

The following example shows how to generate a template formatted in YAML by using the value `yaml-input` for the `--generate-cli-skeleton` parameter.

```
$ 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.
```

------

## Generate and import a command skeleton
<a name="cli-usage-skeleton-generate"></a>

**To generate and use a parameter skeleton file**

1. Run the command with the `--generate-cli-skeleton` parameter to produce either JSON or YAML and direct the output to a file to save it.

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

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

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

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

------

1. Open the parameter skeleton file in your text editor and remove any of the parameters that you don't need. For example, you might strip the template down to the following. Confirm the file is still valid JSON or YAML after you remove the elements you don't need.

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

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

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

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

------

   In this example, we leave the `DryRun` parameter set to `true` to use the Amazon EC2 dry run feature. This feature lets you safely test the command without actually creating or modifying any resources. 

1. Fill in the remaining values with values appropriate for your scenario. In this example, we provide the instance type, key name, security group, and identifier of the Amazon Machine Image (AMI) to use. This example assumes the default AWS Region. The AMI `ami-dfc39aef` is a 64-bit Amazon Linux image hosted in the `us-west-2` Region. If you use a different Region, you must [find the correct AMI ID to use](http://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. Run the command with the completed parameters by passing the completed template file to either the `--cli-input-json` or --`cli-input-yaml` parameter by using the `file://` prefix. The AWS CLI interprets the path to be relative to your current working directory. The following example the AWS CLI looks for the file in the current working directory.

------
#### [ 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.
   ```

------

   The dry run error indicates that the JSON or YAML is formed correctly and that the parameter values are valid. If other issues are reported in the output, fix them and repeat the previous step until the "`Request would have succeeded`" message is displayed. 

1. Now you can set the `DryRun` parameter to `false` to disable dry run.

------
#### [ 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 the command, and `run-instances` actually launches an Amazon EC2 instance and displays the details generated by the successful launch. The format of the output is controlled by the `--output` parameter, separately from the format of your input parameter template.

------
#### [ 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:
   ...
   ```

------

## Combining input files and command line parameters
<a name="cli-usage-skeleton-combine"></a>

An input file can be used for all parameters, or can be combined with parameters specified in the AWS CLI. You can use this feature for settings you frequently reuse in an input file, while keeping your individual settings in the command itself.

The following `aws ec2 run-instances` examples combine the use of an input file and parameters. We provide the instance type, key name, security group, identifier of the Amazon Machine Image (AMI) to use and assume the default AWS Region. The AMI `ami-dfc39aef` is a 64-bit Amazon Linux image hosted in the `us-west-2` Region. If you use a different Region, you must [find the correct AMI ID to use](http://aws.amazon.com/amazon-linux-ami/).

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

Contents of the JSON file:

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

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

Contents of the YAML file:

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

------

The following example uses the input file in combination with the `--dry-run` parameter to perform a dry-run of the command to confirm whether you have the required permissions and have filled out the file with valid values.

------
#### [ 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.
```

------

The following example then uses the same input file, but with the `--no-dry-run` parameter to perform the command in full.

------
#### [ 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:
...
```

------

# Using shorthand syntax in the AWS CLI
<a name="cli-usage-shorthand"></a>

The AWS Command Line Interface (AWS CLI) can accept many of its option parameters in JSON format. However, it can be tedious to enter large JSON lists or structures on the command line. To make this easier, the AWS CLI also supports a shorthand syntax that enables a simpler representation of your option parameters than using the full JSON format.

**Topics**
+ [Structure parameters with key-value pairs](#shorthand-structure-parameters)
+ [Loading a file as a shorthand syntax value](#shorthand-files)
+ [Using shorthand syntax with the AWS CLI](#shorthand-list-parameters)

## Structure parameters with key-value pairs
<a name="shorthand-structure-parameters"></a>

The shorthand syntax in the AWS CLI makes it easier for users to input parameters that are flat (non-nested structures). The format is a comma-separated list of key-value pairs. Be sure to use the [quoting](cli-usage-parameters-quoting-strings.md) and escaping rules appropriate for your terminal as shorthand syntax are strings.

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

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

Is equivalent to the following example, formatted in JSON.

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

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

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

Is equivalent to the following example, formatted in JSON.

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

------

There must be no white space between each comma-separated key-value pair. Here is an example of the Amazon DynamoDB `update-table` command with the `--provisioned-throughput` option specified in shorthand.

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

This is equivalent to the following example formatted in JSON.

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

## Loading a file as a shorthand syntax value
<a name="shorthand-files"></a>

When a value is large or complex, it is often easier to load in as a value. To load a file as a shorthand syntax value, the formatting will change slightly. Instead of `key=value` you'll use the `@=` operator instead of the `=` operator. The `@=` signifies to the AWS CLI that the value should be read as a file path and not a string. When loading files in shorthand syntax, the usual [AWS CLI file formatting rules apply](cli-usage-parameters-file.md). The following example shows a key-value pair loading a file for its value.

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

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

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

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

------

The following example demonstrates loading a certificate file for the `aws rolesanywhere create-trust-anchor` command.

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

## Using shorthand syntax with the AWS CLI
<a name="shorthand-list-parameters"></a>

You can specify Input parameters in a list form in two ways: JSON or shorthand. The AWS CLI shorthand syntax is designed to make it easier to pass in lists with number, string, or non-nested structures. 

The basic format is shown here, where values in the list are separated by a single space.

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

This is equivalent to the following example, formatted in JSON.

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

As previously mentioned, you can specify a list of numbers, a list of strings, or a list of non-nested structures in shorthand. The following is an example of the `stop-instances` command for Amazon Elastic Compute Cloud (Amazon EC2), where the input parameter (list of strings) for the `--instance-ids` option is specified in shorthand.

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

This is equivalent to the following example formatted in JSON.

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

The following example shows the Amazon EC2 `create-tags` command, which takes a list of non-nested structures for the `--tags` option. The `--resources` option specifies the ID of the instance to tag.

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

This is equivalent to the following example, formatted in JSON. The JSON parameter is written over multiple lines for readability.

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

# Enabling and using command prompts in the AWS CLI
<a name="cli-usage-parameters-prompting"></a>

You can have the AWS CLI version 2 prompt you commands, parameters, and resources when you run an `aws` command.

**Topics**
+ [How it works](#cli-usage-auto-prompt-about)
+ [Auto-prompt features](#cli-usage-auto-prompt-features)
+ [Auto-prompt modes](#cli-usage-auto-prompt-modes)
+ [Configure auto-prompt](#cli-usage-auto-prompt-configure)

## How it works
<a name="cli-usage-auto-prompt-about"></a>

If enabled, the auto-prompt enables you to use the **ENTER** key to complete a partially entered command. After pressing the **ENTER** key, commands, parameters, and resources are suggested based on what you continue to type. The suggestions list the name of the command, parameter, or resource on the left and a description of it on the right. To select and use a suggestion, use the arrows keys to highlight a row, and then press the **SPACE** key. When you've finished entering in your command, press **ENTER** to use the command. The following example demonstrates what a suggested list from auto-prompt looks like.

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

## Auto-prompt features
<a name="cli-usage-auto-prompt-features"></a>

The auto-prompt contains the following useful features:

**Documentation panel**  
Provides the help documentation for the current command. To open the documentation, press the **F3** key.

**Command completion**  
Suggests `aws` commands to use. To see a list, partially enter the command. The following example is searching for a service starting with the letter `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
```

**Parameter completion**  
After a command is typed, auto-prompt starts to suggest parameters. The descriptions for the parameters include the value type, and a description of what the parameter is. Required parameters are listed first, and are labeled as required. The following example shows the auto-prompt list of parameters for `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...
```

**Resource completion**  
The auto-prompt makes AWS API calls using available AWS resource properties to suggest resource values. This allows for auto-prompt to suggest possible resources you own when entering in parameters. In the following example auto-prompt lists your table names when filling in the `--table-name` parameter for the `aws dynamodb describe-table` command.  

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

**Shorthand completion**  
For parameters that use shorthand syntax, auto-prompt suggests values to use. In the following example, auto-prompt lists shorthand syntax values for the `--placement` parameter in the `aws ec2 run-instances` command.  

```
$ 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...
```

**File completion**  
When filling out parameters in `aws` commands, auto-complete suggests local filenames after using the prefix `file://` or `fileb://`. In the following example, auto-prompt suggests local files after entering in `--item file://` for the `aws ec2 run-instances` command.  

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

**Region completion**  
When using the global parameter `--region`, auto-prompt lists possible Regions to select from. In the following example, auto-prompt suggests Regions in alphabetical order after entering in `--region` for the `aws dynamodb list-tables` command.  

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

**Profile completion**  
When using the global parameter `--profile`, auto-prompt lists your profiles. In the following example, auto-prompt suggests your profiles after entering in `--profile` for the `aws dynamodb list-tables` command.  

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

**Fuzzy searching**  
Complete commands and values that contain a specific set of characters. In the following example, auto-prompt suggests Regions that contain `eu` after entering in `--region eu` for the `aws dynamodb list-tables` command.  

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

**History**  
To view and run previously used commands in auto-prompt mode, press **CTRL \$1 R**. History lists previous commands that you can select by using the arrow keys. In the following example, the auto-prompt mode history is displayed.  

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

## Auto-prompt modes
<a name="cli-usage-auto-prompt-modes"></a>

Auto-prompt for the AWS CLI version 2 has 2 modes that can be configured:
+ **Full mode:** Uses auto-prompt each time you attempt to run an `aws` command, whether you manually call it using the `--cli-auto-prompt` parameter or permanently enabled it. This includes pressing **ENTER** after both a complete command or incomplete command.
+ **Partial mode:** Uses auto-prompt if a command is incomplete or cannot be run due to client-side validation errors. This mode is particular useful if you have pre-existing scripts, runbooks, or you only want to be auto-prompted for commands you are unfamiliar with rather than prompted on every command.

## Configure auto-prompt
<a name="cli-usage-auto-prompt-configure"></a>

To configure auto-prompt you can use the following methods in order of precedence: 
+ **Command line options** enable or disable auto-prompt for a single command. Use `--cli-auto-prompt` to call auto-prompt and `--no-cli-auto-prompt` to disable auto-prompt.
+ **Environment variables** use the `aws\$1cli\$1auto\$1prompt` variable.
+ **Shared config files** use the `cli\$1auto\$1prompt` setting.

# Controlling command output in the AWS CLI
<a name="cli-usage-output"></a>

This section describes the different ways to control the output from the AWS Command Line Interface (AWS CLI). Customizing the AWS CLI output in your terminal can improve readability, streamline scripting automation and provide easier navigation through larger data sets.

The AWS CLI supports multiple [output formats](cli-usage-output-format.md), including [`json`](cli-usage-output-format.md#json-output), [`text`](cli-usage-output-format.md#text-output), [`yaml`](cli-usage-output-format.md#yaml-output), [`off`](cli-usage-output-format.md#off-output), and [`table`](cli-usage-output-format.md#table-output). Some services have server-side [pagination](cli-usage-pagination.md) for their data and the AWS CLI provides it's own client-side features for additional pagination options.

Lastly, the AWS CLI has both[ server-side and client-side filtering](cli-usage-filter.md) that you can use individually or together to filter your AWS CLI output.

**Topics**
+ [Sensitive output](#cli-usage-output-sensitive)
+ [Server-side vs client-side output options](#cli-usage-output-server-client)
+ [Setting the output format in the AWS CLI](cli-usage-output-format.md)
+ [Structured error output in the AWS CLI](cli-usage-error-format.md)
+ [Using the pagination options in the AWS CLI](cli-usage-pagination.md)
+ [Filtering output in the AWS CLI](cli-usage-filter.md)

## Sensitive output
<a name="cli-usage-output-sensitive"></a>

Some operations of the AWS CLI might return information that could be considered sensitive, including information from environment variables. The exposure of this information might represent a security risk in certain scenarios; for example, the information could be included in continuous integration and continuous deployment (CI/CD) logs. It is therefore important that you review when you are including such output as part of your logs, and suppress the output when not needed.

For additional information about protecting sensitive data, see [Data protection in the AWS CLI](data-protection.md).

Consider the following best practices:
+ Consider programmatically retrieving your secrets from a secrets store, such as AWS Secrets Manager.
+ Review the contents of your build logs to ensure they do not contain sensitive information. Consider approaches such as piping to `/dev/null` or capturing the output as a bash or PowerShell variable to suppress command outputs. 

  The following is a bash example for redirecting output, but not errors, to `/dev/null`:

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

  For specifics on suppressing output for your terminal, see the user documentation of the terminal you use.
+ Consider the access of your logs and scope the access appropriately for your use case.

## Server-side vs client-side output options
<a name="cli-usage-output-server-client"></a>

The AWS CLI has both[ server-side and client-side filtering](cli-usage-filter.md) that you can use individually or together to filter your AWS CLI output. Server-side filtering is processed first and returns your output for client-side filtering. Server-side filtering is supported by the service API. Client-side filtering is supported by the AWS CLI client using the `--query` parameter.

**Server-side** output options are features directly supported by the AWS service API. Any data that is filtered or paged out is not sent to the client, which can speed up HTTP response times and improve bandwidth for larger data sets.

**Client-side** output options are features created by the AWS CLI. All data is sent to the client, then the AWS CLI filters or pages the content displayed. Client-side operations do not save on speed or bandwidth for larger datasets.

When server-side and client-side options are used together, server-side operations are completed first and then sent to the client for client-side operations. This uses the potential speed and bandwidth savings of server-side options, while using additional AWS CLI features to get your desired output.

# Setting the output format in the AWS CLI
<a name="cli-usage-output-format"></a>

This topic describes the different output formats for the AWS Command Line Interface (AWS CLI). The AWS CLI supports the following output formats:
+ **[`json`](#json-output)** – The output is formatted as a [JSON](https://json.org/) string.
+  **[`yaml`](#yaml-output)** – The output is formatted as a [YAML](https://yaml.org/) string.
+ **[`yaml-stream`](#yaml-stream-output)** – The output is streamed and formatted as a [YAML](https://yaml.org/) string. Streaming allows for faster handling of large data types.
+ **[`text`](#text-output)** – The output is formatted as multiple lines of tab-separated string values. This can be useful to pass the output to a text processor, like `grep`, `sed`, or `awk`.
+ **[`table`](#table-output)** – The output is formatted as a table using the characters \$1\$1- to form the cell borders. It typically presents the information in a "human-friendly" format that is much easier to read than the others, but not as programmatically useful.
+ **[`off`](#off-output)** – The output suppresses all command output to stdout. This is useful in automation scripts and CI/CD pipelines where you only need to check the command's exit code without processing the output.

## How to select the output format
<a name="cli-usage-output-format-how"></a>

As explained in the [configuration](cli-chap-configure.md) topic, you can specify the output format in three ways:
+ **Using the `output` option in a named profile in the `config` file** – The following example sets the default output format to `text`.

  ```
  [default]
  output=text
  ```
+ **Using the `AWS_DEFAULT_OUTPUT` environment variable** – The following output sets the format to `table` for the commands in this command line session until the variable is changed or the session ends. Using this environment variable overrides any value set in the `config` file.

  ```
  $ export AWS_DEFAULT_OUTPUT="table"
  ```
+ **Using the `--output` option on the command line ** – The following example sets the output of only this one command to `json`. Using this option on the command overrides any currently set environment variable or the value in the `config` file.

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

**Important**  
The output type you specify changes how the `--query` option operates:  
If you specify `--output text`, the output is paginated *before* the `--query` filter is applied, and the AWS CLI runs the query once on *each page* of the output. Due to this, the query includes the first matching element on each page which can result in unexpected extra output. To additionally filter the output, you can use other command line tools such as `head` or `tail`.
If you specify `--output json`, `--output yaml`, or `--output yaml-stream` the output is completely processed as a single, native structure before the `--query` filter is applied. The AWS CLI runs the query only once against the entire structure, producing a filtered result that is then output.

## JSON output format
<a name="json-output"></a>

[JSON](https://json.org) is the default output format of the AWS CLI. Most programming languages can easily decode JSON strings using built-in functions or with publicly available libraries. You can combine JSON output with the [--query option](cli-usage-filter.md) in powerful ways to filter and format the AWS CLI JSON-formatted output. 

For more advanced filtering that you might not be able to do with `--query`, you can consider `jq`, a command line JSON processor. You can download it and find the official tutorial at [http://stedolan.github.io/jq/](http://stedolan.github.io/jq/).

The following is an example of JSON output.

```
$ 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 output format
<a name="yaml-output"></a>

[YAML](https://yaml.org) is a good choice for handling the output programmatically with services and tools that emit or consume [YAML](https://yaml.org)-formatted strings, such as CloudFormation with its support for [YAML-formatted templates](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-formats.html).

For more advanced filtering that you might not be able to do with `--query`, you can consider `yq`, a command line YAML processor. You can download `yq` in the [yq repository](https://github.com/mikefarah/yq) on *GitHub*.

The following is an example of YAML output.

```
$ 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 stream output format
<a name="yaml-stream-output"></a>

The `yaml-stream` format takes advantage of the [YAML](https://yaml.org) format while providing more responsive/faster viewing of large data sets by streaming the data to you. You can start viewing and using YAML data before the entire query downloads. 

For more advanced filtering that you might not be able to do with `--query`, you can consider `yq`, a command line YAML processor. You can download `yq` in the [yq repository](https://github.com/mikefarah/yq) on *GitHub*.

The following is an example of `yaml-stream` output.

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

The following is an example of `yaml-stream` output in conjunction with using the `--page-size` parameter to paginate the streamed YAML content.

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

## Text output format
<a name="text-output"></a>

The `text` format organizes the AWS CLI output into tab-delimited lines. It works well with traditional Unix text tools such as `grep`, `sed`, and `awk`, and the text processing performed by PowerShell. 

The `text` output format follows the basic structure shown below. The columns are sorted alphabetically by the corresponding key names of the underlying JSON object.

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

The following is an example of `text` output. Each field is tab separated from the others, with an extra tab where there is an empty field.

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

The fourth column is the `PasswordLastUsed` field, and is empty for the last two entries because those users never sign in to the AWS Management Console.

**Important**  
*We strongly recommend that if you specify `text` output, you also always use the [`--query`](cli-usage-filter.md) option to ensure consistent behavior*.   
This is because the text format alphabetically orders output columns by the key name of the underlying JSON object returned by the AWS service, and similar resources might not have the same key names. For example, the JSON representation of a Linux-based Amazon EC2 instance might have elements that are not present in the JSON representation of a Windows-based instance, or vice versa. Also, resources might have key-value elements added or removed in future updates, altering the column ordering. This is where `--query` augments the functionality of the `text` output to provide you with complete control over the output format.   
In the following example, the command specifies which elements to display and *defines the ordering* of the columns with the list notation `[key1, key2, ...]`. This gives you full confidence that the correct key values are always displayed in the expected column. Finally, notice how the AWS CLI outputs `None` as the value for keys that don't exist.  

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

The following example shows how you can use `grep` and `awk` with the `text` output from the `aws ec2 describe-instances` command. The first command displays the Availability Zone, current state, and the instance ID of each instance in `text` output. The second command processes that output to display only the instance IDs of all running instances in the `us-west-2a` Availability Zone.

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

The following example goes a step further and shows not only how to filter the output, but how to use that output to automate changing instance types for each stopped instance.

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

The `text` output can also be useful in PowerShell. Because the columns in `text` output are tab delimited, you can easily split the output into an array by using PowerShell's ``t` delimiter. The following command displays the value of the third column (`InstanceId`) if the first column (`AvailabilityZone`) matches the string `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
```

Notice that although the previous example does show how to use the `--query` parameter to parse the underlying JSON objects and pull out the desired column, PowerShell has its own ability to handle JSON, if cross-platform compatibility isn't a concern. Instead of handling the output as text, as most command shells require, PowerShell lets you use the `ConvertFrom-JSON` cmdlet to produce a hierarchically structured object. You can then directly access the member you want from that object.

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

**Tip**  
If you output text, and filter the output to a single field using the `--query` parameter, the output is a single line of tab-separated values. To get each value onto a separate line, you can put the output field in brackets, as shown in the following examples.  
Tab separated, single-line output:  

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

```
HRDepartment    Developers      SpreadsheetUsers  LocalAdmins
```
Each value on its own line by putting `[GroupName]` in brackets:  

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

```
HRDepartment
Developers
SpreadsheetUsers
LocalAdmins
```

## Table output format
<a name="table-output"></a>

The `table` format produces human-readable representations of complex AWS CLI output in a tabular form.

```
$ 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    ||
+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
```

You can combine the `--query` option with the `table` format to display a set of elements preselected from the raw output. Notice the output differences between dictionary and list notations: in the first example, column names are ordered alphabetically, and in the second example, unnamed columns are ordered as defined by the user. For more information about the `--query` option, see [Filtering output in the 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  |
+--------------+--------------+--------------+-----+
```

## Off output format
<a name="off-output"></a>

The `off` format suppresses all command output to stdout. This is useful in automation scripts and CI/CD pipelines where you only need to check the command's exit code without processing the output. Error messages are still displayed on stderr.

The following example shows how the `off` format suppresses successful output. You can check the exit code to determine success:

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

This is particularly useful in shell scripts where you want to verify a resource exists without capturing output:

```
#!/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
```

**Note**  
The `off` format only suppresses stdout. Errors are still written to stderr.

# Structured error output in the AWS CLI
<a name="cli-usage-error-format"></a>

This topic describes the structured error output formats for the AWS Command Line Interface (AWS CLI). The CLI writes errors to stderr and supports the following formats:
+ **[`enhanced`](#cli-error-format-enhanced)** (default) – Error message with additional details displayed inline. Use for human-readable debugging.
+ **[`json`](#cli-error-format-json)** – The output is formatted as a [JSON](https://json.org/) string with all error fields. Use for automation and scripting.
+ **[`yaml`](#cli-error-format-yaml)** – The output is formatted as a [YAML](https://yaml.org/) string with all error fields. Use for automation and scripting.
+ **[`text`](#cli-error-format-text)** – Formats errors using the text formatter. Use for quick visual scanning.
+ **[`table`](#cli-error-format-table)** – Formats errors using the table formatter. Use for quick visual scanning.
+ **[`legacy`](#cli-error-format-legacy)** – Original error format without structured details. Use for backward compatibility.

## Configuring error format
<a name="cli-error-format-configuring"></a>

You can configure the error format using any of the following methods:

Command-line flag  

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

Configuration file (`~/.aws/config`)  

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

Environment variable  

```
$ export AWS_CLI_ERROR_FORMAT=yaml
```

## Error output formats
<a name="cli-error-output-formats"></a>

The following sections describe each format:

### Enhanced format (default)
<a name="cli-error-format-enhanced"></a>

The enhanced format displays error messages with additional details inline for simple values. For complex structures, the format provides a hint to use JSON or YAML.

**Example: Missing region configuration**

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

**Example: Nonexistent Lambda function with additional fields**

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

The "Additional error details" section displays only fields that are defined in the service's error shape model. Unmodeled fields from the error response are not shown.

**Example: Complex error fields**

```
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
<a name="cli-error-format-json"></a>

The JSON format provides a structured representation with all error fields.

**Example: Missing region configuration**

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

**Example: Nonexistent Lambda function**

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

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

The YAML format provides a structured representation with all error fields.

**Example: Missing region configuration**

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

**Example: Nonexistent Lambda function**

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

### Text format
<a name="cli-error-format-text"></a>

The text format uses the same formatter as successful command output.

**Example: Nonexistent Lambda function**

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

### Table format
<a name="cli-error-format-table"></a>

The table format uses the same formatter as successful command output.

**Example: Nonexistent Lambda function**

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

### Legacy format
<a name="cli-error-format-legacy"></a>

The legacy format provides the original error format without structured details. This format does not include the "An error occurred (ErrorCode):" prefix for CLI exceptions.

**Example: Missing region configuration**

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

**Example: Nonexistent Lambda function**

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

**Note**  
Errors now consistently include the `aws: [ERROR]:` prefix for CLI exceptions. Earlier versions did not always include this prefix.  
The following exceptions always use the legacy format regardless of the configured error format:  
`UnknownArgumentError` – Displays usage information
Keyboard interrupts (`KeyboardInterrupt`)

## Complete example
<a name="cli-error-format-example"></a>

The following example shows a command with JSON error formatting:

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

Output (stderr):

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

The `Type` field is a modeled error member defined in the Lambda service's error shape. Only fields defined in the service's error model are included in the structured error output.

# Using the pagination options in the AWS CLI
<a name="cli-usage-pagination"></a>

This topic describes the different ways to paginate output from the AWS Command Line Interface (AWS CLI). 

There are primarily two ways to control pagination from the AWS CLI.
+ [Using server-side pagination parameters.](#cli-usage-pagination-serverside)
+ [Using your default output client-side paging program](#cli-usage-pagination-clientside).

Server-side pagination parameters process first and any output is sent to client-side pagination.

## Server-side pagination
<a name="cli-usage-pagination-serverside"></a>

For most commands that return a large list of items, the AWS CLI has multiple server-side options to control the number of items included in the output when the AWS CLI calls a service's API to populate the list. Server-side pagination in the AWS CLI is enabled by the AWS service API, therefore these options only work if the service API enables them.

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

By default, the AWS CLI uses a page size determined by the individual service and retrieves all available items. For example, Amazon S3 has a default page size of 1000. If you run `aws s3api list-objects` on an Amazon S3 bucket that contains 3,500 objects, the AWS CLI automatically makes four calls to Amazon S3, handling the service-specific pagination logic for you in the background and returning all 3,500 objects in the final output.

For information about whether a specific command has server-side pagination, see the [AWS CLI version 2 reference guide](https://docs.aws.amazon.com/cli/latest/reference/index.html).

### How to use the --no-paginate parameter
<a name="cli-usage-pagination-nopaginate"></a>

The `--no-paginate` option disables following pagination tokens on the client side. When using a command, by default the AWS CLI automatically makes multiple calls to return all possible results to create pagination. One call for each page. Disabling pagination has the AWS CLI only call once for the first page of command results. 

For example, if you run `aws s3api list-objects` on an Amazon S3 bucket that contains 3,500 objects, the AWS CLI only makes the first call to Amazon S3, returning only the first 1,000 objects in the final output.

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

### How to use the --page-size parameter
<a name="cli-usage-pagination-pagesize"></a>

If you see issues when running list commands on a large number of resources, the default page size might be too high. This can cause calls to AWS services to exceed the maximum allowed time and generate a "timed out" error. You can use the `--page-size` option to specify that the AWS CLI request a smaller number of items from each call to the AWS service. The AWS CLI still retrieves the full list, but performs a larger number of service API calls in the background and retrieves a smaller number of items with each call. This gives the individual calls a better chance of succeeding without a timeout. Changing the page size doesn't affect the output; it affects only the number of API calls that need to be made to generate the output.

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

### How to use the --max-items parameter
<a name="cli-usage-pagination-maxitems"></a>

To include fewer items at a time in the AWS CLI output, use the `--max-items` option. The AWS CLI still handles pagination with the service as described previously, but prints out only the number of items at a time that you specify.

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

### How to use the --starting-token parameter
<a name="cli-usage-pagination-startingtoken"></a>

If the number of items output (`--max-items`) is fewer than the total number of items returned by the underlying API calls, the output includes a `NextToken` that you can pass to a subsequent command to retrieve the next set of items. The following example shows how to use the `NextToken` value returned by the previous example, and enables you to retrieve the second 100 items.

**Note**  
The parameter `--starting-token` cannot be null or empty. If the previous command does not return a `NextToken` value, there are no more items to return and you do not need to call the command again.

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

The specified AWS service might not return items in the same order each time you call. If you specify different values for `--page-size` and `--max-items`, you can get unexpected results with missing or duplicated items. To prevent this, use the same number for `--page-size` and `--max-items` to sync the AWS CLI pagination with the pagination of the underlying service. You can also retrieve the whole list and perform any necessary paging operations locally.

## Client-side pager
<a name="cli-usage-pagination-clientside"></a>

AWS CLI version 2 provides the use of a client-side pager program for output. By default, this feature returns all output through your operating system’s default pager program. 

In order of precedence, you can specify the output pager in the following ways:
+ Using the `cli_pager` setting in the `config` file in the `default` or named profile.
+ Using the `AWS_PAGER` environment variable.
+ Using the `PAGER` environment variable.

In order of precedence, you can disable all use of an external paging program in the following ways:
+ Use the `--no-cli-pager` command line option to disable the pager for a single command use. 
+ Set the `cli_pager` setting or `AWS_PAGER` variable to an empty string.

**Topics**
+ [cli\$1pager](#cli-usage-pagination-clipager)
+ [AWS\$1PAGER](#cli-usage-pagination-awspager)
+ [--no-cli-pager](#cli-usage-pagination-noclipager)
+ [Pager flags](#cli-usage-pagination-flags)

### How to use the cli\$1pager setting
<a name="cli-usage-pagination-clipager"></a>

You can save your frequently used configuration settings and credentials in files that are maintained by the AWS CLI. Settings in a name profile take precedence over settings in the `default` profile. For more information on configuration settings, see [Configuration and credential file settings in the AWS CLI](cli-configure-files.md).

The following example sets the default output pager to the `less` program.

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

The following example sets the default to disable the use of a pager.

```
[default]
cli_pager=
```



### How to set the AWS\$1PAGER environment variable
<a name="cli-usage-pagination-awspager"></a>

The following example sets the default output pager to the `less` program. For more information on environment variables, see [Configuring environment variables for the AWS CLI](cli-configure-envvars.md).

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

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

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

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

------

### How to use the --no-cli-pager option
<a name="cli-usage-pagination-noclipager"></a>

To disable the use of a pager on a single command, use the `--no-cli-pager` option. For more information on command line options, see [Command line options in the AWS CLI](cli-configure-options.md).

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

### How to use pager flags
<a name="cli-usage-pagination-flags"></a>

You can specify flags to use automatically with your paging program. Flags are dependent on the paging program you use. The below examples are for the typical defaults of `less` and `more`.

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

If you do not specify otherwise, the pager AWS CLI version 2 uses by default is `less`. If you don't have the `LESS` environment variable set, the AWS CLI version 2 uses the `FRX` flags. You can combine flags by specifying them when setting the AWS CLI pager.

The following example uses the `S` flag. This flag then combines with the default `FRX` flags to create a final `FRXS` flag.

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

If you don't want any of the `FRX` flags, you can negate them. The following example negates the `F` flag to create a final `RX` flag.

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

For more information on `less` flags see [less](http://manpages.org/less/1#options) on *manpages.org*. 

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

If you do not specify otherwise, the pager AWS CLI version 2 uses by default is `more` with no additional flags.

The following example uses the `/c` parameter.

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

For more information on `more` flags, see `[more](https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/more)` on *Microsoft Docs*.

------

# Filtering output in the AWS CLI
<a name="cli-usage-filter"></a>

The AWS Command Line Interface (AWS CLI) has both server-side and client-side filtering that you can use individually or together to filter your AWS CLI output. Server-side filtering is processed first and returns your output for client-side filtering. 
+ Server-side filtering is supported by the API, and you usually implement it with a `--filter` parameter. The service only returns matching results which can speed up HTTP response times for large data sets.
+ Client-side filtering is supported by the AWS CLI client using the `--query` parameter. This parameter has capabilities the server-side filtering might not have.

**Topics**
+ [Server-side filtering](#cli-usage-filter-server-side)
+ [Client-side filtering](#cli-usage-filter-client-side)
+ [Combining server-side and client-side filtering](#cli-usage-filter-combining)
+ [Additional resources](#cli-usage-filter-resources)

## Server-side filtering
<a name="cli-usage-filter-server-side"></a>

Server-side filtering in the AWS CLI is provided by the AWS service API. The AWS service only returns the records in the HTTP response that match your filter, which can speed up HTTP response times for large data sets. Since server-side filtering is defined by the service API, the parameter names and functions vary between services. Some common parameter names used for filtering are: 
+ `--filter` such as [ses](https://docs.aws.amazon.com/cli/latest/reference/ses/create-receipt-filter.html) and [ce](https://docs.aws.amazon.com/cli/latest/reference/ce/get-cost-and-usage.html). 
+ `--filters` such as [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), and [rds](https://docs.aws.amazon.com/cli/latest/reference/rds/describe-db-instances.html). 
+ Names starting with the word `filter`, for example `--filter-expression` for the [https://docs.aws.amazon.com/cli/latest/reference/dynamodb/scan.html](https://docs.aws.amazon.com/cli/latest/reference/dynamodb/scan.html) command.

For information about whether a specific command has server-side filtering and the filtering rules, see the [AWS CLI version 2 reference guide](https://docs.aws.amazon.com/cli/latest/reference/index.html).

## Client-side filtering
<a name="cli-usage-filter-client-side"></a>

The AWS CLI provides built-in JSON-based client-side filtering capabilities with the `--query` parameter. The `--query` parameter is a powerful tool you can use to customize the content and style of your output. The `--query` parameter takes the HTTP response that comes back from the server and filters the results before displaying them. Since the entire HTTP response is sent to the client before filtering, client-side filtering can be slower than server-side filtering for large data-sets.

Querying uses [JMESPath syntax](https://jmespath.org/) to create expressions for filtering your output. To learn JMESPath syntax, see [Tutorial](https://jmespath.org/tutorial.html) on the *JMESPath website*.

**Important**  
The output type you specify changes how the `--query` option operates:  
If you specify `--output text`, the output is paginated *before* the `--query` filter is applied, and the AWS CLI runs the query once on *each page* of the output. Due to this, the query includes the first matching element on each page which can result in unexpected extra output. To additionally filter the output, you can use other command line tools such as `head` or `tail`.
If you specify `--output json`, `--output yaml`, or `--output yaml-stream` the output is completely processed as a single, native structure before the `--query` filter is applied. The AWS CLI runs the query only once against the entire structure, producing a filtered result that is then output.

**Topics**
+ [Before you start](#cli-usage-filter-client-side-output)
+ [Identifiers](#cli-usage-filter-client-side-identifiers)
+ [Selecting from a list](#cli-usage-filter-client-side-select-list)
+ [Filtering nested data](#cli-usage-filter-client-side-nested)
+ [Flattening results](#cli-usage-filter-client-side-specific-flattening)
+ [Filtering for specific values](#cli-usage-filter-client-side-specific-values)
+ [Piping expressions](#cli-usage-filter-client-side-pipe)
+ [Filtering for multiple identifier values](#cli-usage-filter-client-side-miltiselect-list)
+ [Adding labels to identifier values](#cli-usage-filter-client-side-multiselect-hash)
+ [Functions](#cli-usage-filter-client-side-functions)
+ [Advanced `--query` examples](#cli-usage-filter-client-side-advanced)

### Before you start
<a name="cli-usage-filter-client-side-output"></a>

**Note**  
These filter expression examples are written for basic linux-like shells. When using these examples, be sure to use the correct quoting rules for your terminal shell. The way your terminal interprets your inputs can vastly change what is sent to the AWS CLI. How your terminal reads single quotes`'`, double quotes `"`, or backticks ``` can change how content is read.  
For more information, see [Using quotation marks and literals with strings in the AWS CLI](cli-usage-parameters-quoting-strings.md).

The following JSON output shows an example of what the `--query` parameter can produce. The output describes three Amazon EBS volumes attached to separate Amazon EC2 instances.

#### Example output
<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
    }
  ]
}
```

### Identifiers
<a name="cli-usage-filter-client-side-identifiers"></a>

Identifier are the labels for output values. When creating filters, you use identifiers to narrow down your query results. In the following output example, all identifiers such as `Volumes`, `AvailabilityZone`, and `AttachTime` are highlighted. 

```
$ 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
    }
  ]
}
```

For more information, see [Identifiers](https://jmespath.org/specification.html#identifiers ) on the *JMESPath website*.

### Selecting from a list
<a name="cli-usage-filter-client-side-select-list"></a>

A list or array is an identifier that is followed by a square bracket "`[`" such as `Volumes` and `Attachments` in the [Before you start](#cli-usage-filter-client-side-output). 

**Syntax**

```
<listName>[ ]
```

To filter through all output from an array, you can use the wildcard notation. [Wildcard](http://jmespath.org/specification.html#wildcard-expressions) expressions are expressions used to return elements using the `*` notation. 

The following example queries all `Volumes` content.

```
$ 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
  }
]
```

To view a specific volume in the array by index, you call the array index. For example, the first item in the `Volumes` array has an index of 0, resulting in the `Volumes[0]` query. For more information about array indexes, see [index expressions](http://jmespath.org/specification.html#index-expressions) on the *JMESPath website*.

```
$ 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
}
```

To view a specific range of volumes by index, use `slice` with the following syntax, where **start** is the starting array index, **stop** is the index where the filter stops processing, and **step** is the skip interval. 

**Syntax**

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

If any of these are omitted from the slice expression, they use the following default values:
+ Start – The first index in the list, 0.
+ Stop – The last index in the list.
+ Step – No step skipping, where the value is 1.

To return only the first two volumes, you use a start value of 0, a stop value of 2, and a step value of 1 as shown in the following example.

```
$ 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
  }
]
```

Since this example contains default values, you can shorten the slice from `Volumes[0:2:1]` to `Volumes[:2]`.

The following example omits default values and returns every two volumes in the entire array.

```
$ 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
  }
]
```

Steps can also use negative numbers to filter in the reverse order of an array as shown in the following example. 

```
$ 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
  }
]
```

For more information, see [Slices](https://jmespath.org/specification.html#slices) on the *JMESPath website*.

### Filtering nested data
<a name="cli-usage-filter-client-side-nested"></a>

To narrow the filtering of the `Volumes[*]` for nested values, you use subexpressions by appending a period and your filter criteria.

**Syntax**

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

The following example shows all `Attachments` information for all volumes.

```
$ 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"
    }
  ]
]
```

To filter further into the nested values, append the expression for each nested indentifier. The following example lists the `State` for all `Volumes`.

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

### Flattening results
<a name="cli-usage-filter-client-side-specific-flattening"></a>

For more information, see [SubExpressions](https://jmespath.org/specification.html#subexpressions) on the *JMESPath website*.

You can flatten the results for `Volumes[*].Attachments[*].State` by removing the wildcard notation resulting in the `Volumes[*].Attachments[].State` query. Flattening often is useful to improve the readablity of results.

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

For more information, see [Flatten](https://jmespath.org/specification.html#flatten) on the *JMESPath website*.

### Filtering for specific values
<a name="cli-usage-filter-client-side-specific-values"></a>

To filter for specific values in a list, you use a filter expression as shown in the following syntax.

**Syntax**

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

Expression comparators include `==`, `!=`, `<`, `<=`, `>`, and `>=` . The following example filters for the `VolumeIds` for all `Volumes` in an `Attached``State`.

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

This can then be flattened resulting in the following example.

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

The following example filters for the `VolumeIds` of all `Volumes` that have a size less than 20.

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

For more information, see [Filter Expressions](https://jmespath.org/specification.html#filterexpressions) on the *JMESPath website*.

### Piping expressions
<a name="cli-usage-filter-client-side-pipe"></a>

You can pipe results of a filter to a new list, and then filter the result with another expression using the following syntax: 

**Syntax**

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

The following example takes the filter results of the `Volumes[*].Attachments[].InstanceId` expression and outputs the first result in the array. 

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

This example does this by first creating the array from the following expression.

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

And then returns the first element in that array.

```
"i-a071c394"
```

For more information, see [Pipe Expressions](https://jmespath.org/specification.html#pipe-expressions) on the *JMESPath website*.

### Filtering for multiple identifier values
<a name="cli-usage-filter-client-side-miltiselect-list"></a>

To filter for multiple identifiers, you use a multiselect list by using the following syntax: 

**Syntax**

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

In the following example, `VolumeId` and `VolumeType` are filtered in the `Volumes` list resulting in the following expression.

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

To add nested data to the list, you add another multiselect list. The following example expands on the previous example by also filtering for `InstanceId` and `State` in the nested `Attachments` list. This results in the following expression.

```
$ 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"
      ]
    ]
  ]
]
```

To be more readable, flatten out the expression as shown in the following example.

```
$ 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"
  ]
]
```

For more information, see [Multiselect list](https://jmespath.org/specification.html#multiselectlist) on the *JMESPath website*.

### Adding labels to identifier values
<a name="cli-usage-filter-client-side-multiselect-hash"></a>

To make this output easier to read, use a multiselect hash with the following syntax.

**Syntax**

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

Your identifier label does not need to be the same as the name of the identifier. The following example uses the label `VolumeType` for the `VolumeType` values.

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

For simplicity, the following example keeps the identifier names for each label and displays the `VolumeId`, `VolumeType`, `InstanceId`, and `State` for all volumes:

```
$ 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"
  }
]
```

For more information, see [Multiselect hash](https://jmespath.org/specification.html#multiselecthash) on the *JMESPath website*.

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

The JMESPath syntax contains many functions that you can use for your queries. For information on JMESPath functions, see [Built-in Functions](https://jmespath.org/specification.html#built-in-functions) on the *JMESPath website*.

To demonstrate how you can incorporate a function into your queries, the following example uses the `sort_by` function. The `sort_by` function sorts an array using an expression as the sort key using the following syntax:

**Syntax**

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

The following example uses the previous [multiselect hash example](#cli-usage-filter-client-side-multiselect-hash) and sorts the output by `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"
  }
]
```

For more information, see [sort\$1by](https://jmespath.org/specification.html#sort-by) on the *JMESPath website*.

### Advanced `--query` examples
<a name="cli-usage-filter-client-side-advanced"></a>

**To extract information from a specific item**

The following example uses the `--query` parameter to find a specific item in a list and then extracts information from that item. The example lists all of the `AvailabilityZones` associated with the specified service endpoint. It extracts the item from the `ServiceDetails` list that has the specified `ServiceName`, then outputs the `AvailabilityZones` field from that selected item. 

```
$ 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"
    ]
]
```

**To show snapshots after the specified creation date**

The following example shows how to list all of your snapshots that were created after a specified date, including only a few of the available fields in the output.

```
$ 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
    }
]
```

**To show the most recent AMIs**

The following example lists the five most recent Amazon Machine Images (AMIs) that you created, sorted from most recent to oldest.

```
$ 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"
    }
]
```

**To show unhealthy Auto Scaling instances**

The following example shows only the `InstanceId` for any unhealthy instances in the specified Auto Scaling group.

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

**To include volumes with the specified tag**

The following example describes all instances with a `test` tag. As long as there is another tag beside `test` attached to the volume, the volume is still returned in the results.

The below expression to return all tags with the `test` tag in an array. Any tags that are not the `test` tag contain a `null` value.

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

**To exclude volumes with the specified tag**

The following example describes all instances without a `test` tag. Using a simple `?Value != `test`` expression does not work for excluding a volume as volumes can have multiple tags. As long as there is another tag beside `test` attached to the volume, the volume is still returned in the results.

To exclude all volumes with the `test` tag, start with the below expression to return all tags with the `test` tag in an array. Any tags that are not the `test` tag contain a `null` value.

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

Then filter out all the positive `test` results using the `not_null` function. 

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

Pipe the results to flatten out the results resulting in the following query.

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

## Combining server-side and client-side filtering
<a name="cli-usage-filter-combining"></a>

You can use server-side and client-side filtering together. Server-side filtering is completed first, which sends the data to the client that the `--query` parameter then filters. If you're using large data sets, using server-side filtering first can lower the amount of data sent to the client for each AWS CLI call, while still keeping the powerful customization that client-side filtering provides.

The following example lists Amazon EC2 volumes using both server-side and client-side filtering. The service filters a list of all attached volumes in the `us-west-2a` Availability Zone. The `--query` parameter further limits the output to only those volumes with a `Size` value that is larger than 50, and shows only the specified fields with user-defined names.

```
$ 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"
    }
]
```

The following example retrieves a list of images that meet several criteria. It then uses the `--query` parameter to sort the output by `CreationDate`, selecting only the most recent. Finally, it displays the `ImageId` of that one image.

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

The following example displays the number of available volumes that are more than 1000 IOPS by using `length` to count how many are in a list.

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

The following example retrieves the names of Auto Scaling groups that are using launch configurations in the specified AWS Region that are using CloudFormation stacks.

```
$ 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"
]
```

## Additional resources
<a name="cli-usage-filter-resources"></a>

**AWS CLI autoprompt**  
When beginning to use filter expressions, you can use the auto-prompt feature in the AWS CLI version 2. The auto-prompt feature provides a preview when you press the **F5** key. For more information, see [Enabling and using command prompts in the AWS CLI](cli-usage-parameters-prompting.md).

**JMESPath Terminal**  
JMESPath Terminal is an interactive terminal command to experiment with JMESPath expressions that are used for client-side filtering. Using the `jpterm` command, the terminal shows immediate query results as you're typing. You can directly pipe AWS CLI output to the terminal, enabling advanced querying experimentation.   
The following example pipes `aws ec2 describe-volumes` output directly to JMESPath Terminal.  

```
$ aws ec2 describe-volumes | jpterm
```
For more information on JMESPath Terminal and installation instructions, see [JMESPath Terminal](https://github.com/jmespath/jmespath.terminal) on *GitHub*.

**jq utility**  
The `jq` utility provides you a way to transform your output on the client-side to an output format you desire. For more information on `jq` and installation instructions, see [jq](https://stedolan.github.io/jq/) on *GitHub*.

# Command line return codes in the AWS CLI
<a name="cli-usage-returncodes"></a>

The return code is usually a hidden code sent after running a AWS Command Line Interface (AWS CLI) command which describes the status of the command. You can use the `echo` command to display the code sent from the last AWS CLI command and use these codes to determine if a command was successful or if it failed, and why a command might have an error. In addition to the return codes, you can view more details about a failure by running your commands with the `--debug` switch. This switch produces a detailed report of the steps the AWS CLI uses to process the command, and what the result of each step was.

To determine the return code of an AWS CLI command, run one of the following commands immediately after running the CLI command. 

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

```
$ echo $?
0
```

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

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

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

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

------

The following are the return code values that can be returned at the end of running an AWS Command Line Interface (AWS CLI) command.


| Code | Meaning | 
| --- | --- | 
| 0 |  The service responded with an HTTP response status code of 200 indicating that there were no errors generated by the AWS CLI and AWS service the request was sent to.  | 
| 1 |  One or more Amazon S3 transfer operations failed. *Limited to S3 commands.*  | 
| 2 |  The meaning of this return code depends on the command:  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cli/latest/userguide/cli-usage-returncodes.html)  | 
| 130 |  The command was interrupted by a SIGINT. This is the signal sent by you to cancel a command with `Ctrl`\$1`C`.  | 
| 252 |  Command syntax was invalid, an unknown parameter was provided, or a parameter value was incorrect and prevented the command from running.  | 
| 253 |  The system environment or configuration was invalid. While the command provided might be syntactically valid, missing configuration or credentials prevented the command from running.  | 
| 254 |  The command successfully parsed and a request made to the specified service but the service returned an error. This will generally indicate incorrect API usage or other service specific issues.  | 
| 255 |  The command failed. There were errors generated by the AWS CLI or by the AWS service to which the request was sent.  | 

# Using custom wizards to run interactive commands in the AWS CLI
<a name="cli-usage-wizard"></a>

The AWS Command Line Interface (AWS CLI) provides the ability to use a wizard for some commands. To contribute or view the full list of available AWS CLI wizards, see the [AWS CLI wizards folder](https://github.com/aws/aws-cli/tree/v2/awscli/customizations/wizard/wizards) on GitHub. 

## How it works
<a name="cli-usage-wizard-how"></a>

Similar to the AWS console, the AWS CLI has a UI wizard that guides you through managing your AWS resources. To use the wizard, you call the `wizard` subcommand and the wizard name after the service name in a command. The command structure is as follows:

**Syntax:**

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

The following example is calling the wizard to create a new `dynamodb` table.

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

`aws configure` is the only wizard that does not have a wizard name. When running the wizard, run the `aws configure wizard` command as the following example demonstrates:

```
$ aws configure wizard
```

After calling a wizard, a form in the shell is displayed. For each parameter, you are either provided a list of options to select from or prompted to enter in a string. To select from a list, use your up and down arrow keys and press **ENTER**. To view details on an option, press the right arrow key. When you've finished filling out a parameter, press **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:
```

To edit previous prompts, use **SHIFT** \$1 **TAB**. For some wizards, after filling in all prompts, you can preview an AWS CloudFormation template or the AWS CLI command filled with your information. This preview mode is useful to learn the AWS CLI, service APIs, and creating templates for scripts.

Press **ENTER** after previewing or the last prompt to run the final command.

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

# Creating and using aliases in the AWS CLI
<a name="cli-usage-alias"></a>

Aliases are shortcuts you can create in the AWS Command Line Interface (AWS CLI) to shorten commands or scripts that you frequently use. You create aliases in the `alias` file located in your configuration folder.

**Topics**
+ [Prerequisites](#cli-usage-alias-prepreqs)
+ [Step 1: Creating the alias file](#cli-usage-alias-create-file)
+ [Step 2: Creating an alias](#cli-usage-alias-create-alias)
+ [Step 3: Calling an alias](#cli-usage-alias-call-alias)
+ [Alias repository examples](#cli-usage-alias-examples)
+ [Resources](#cli-usage-alias-references)

## Prerequisites
<a name="cli-usage-alias-prepreqs"></a>

To use alias commands, you need to complete the following:
+ Install and configure the AWS CLI. For more information, see [Installing or updating to the latest version of the AWS CLI](getting-started-install.md) and [Authentication and access credentials for the AWS CLI](cli-chap-authentication.md).
+ Use a minimum AWS CLI version of 1.11.24 or 2.0.0.
+ (Optional) To use AWS CLI alias bash scripts, you must use a bash-compatible terminal.

## Step 1: Creating the alias file
<a name="cli-usage-alias-create-file"></a>

To create the `alias` file, you can use your file navigation and a text editor, or use your preferred terminal by using the step-by-step procedure. To quickly create your alias file, use the following command block.

------
#### [ 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
```

------

**To create the alias file**

1. Create a folder named `cli` in your AWS CLI configuration folder. By default the configuration folder is `~/.aws/` on Linux or macOS and `%USERPROFILE%\.aws\` on Windows. You can create this through your file navigation or by using the following command.

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

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

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

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

------

   The resulting `cli` folder default path is `~/.aws/cli/` on Linux or macOS and `%USERPROFILE%\.aws\cli` on Windows.

1. In the `cli` folder, create a text file named `alias` with no extension and add `[toplevel]` to the first line. You can create this file through your preferred text editor or use the following command.

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

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

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

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

------

## Step 2: Creating an alias
<a name="cli-usage-alias-create-alias"></a>

You can create an alias using basic commands or bash scripting.

**Warning**  
On Windows, alias arguments are processed by `cmd.exe`, which expands `%VAR%` environment variable references even inside double quotes. If delayed expansion is enabled, `!VAR!` references are also expanded.

### Creating a basic command alias
<a name="cli-usage-alias-create-alias-basic"></a>

You can create your alias by adding a command using the following syntax in the `alias` file you created in the previous step. 

**Syntax**

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

The *aliasname* is what you call your alias. The *command* is the command you want to call, which can include other aliases. You can include options or parameters in your alias, or add them when calling your alias.

The following example creates an alias named `aws whoami` using the [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) command. Since this alias calls an existing AWS CLI command, you can write the command without the `aws` prefix.

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

The following example takes the previous `whoami` example and adds the `Account` filter and text `output` options.

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

### Creating a sub-command alias
<a name="cli-usage-alias-create-alias-sub-command"></a>

**Note**  
The sub-command alias feature requires a minimum AWS CLI version of 1.11.24 or 2.0.0

You can create an alias for sub-commands by adding a command using the following syntax in the `alias` file you created in the previous step. 

**Syntax**

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

The *commandGroup* is the command namespace, e.g. The command `aws ec2 describe-regions` is under the `ec2` command group. The *aliasname* is what you call your alias. The *command* is the command you want to call, which can include other aliases. You can include options or parameters in your alias, or add them when calling your alias.

The following example creates an alias named `aws ec2 regions` using the [https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-regions.html](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-regions.html) command. Since this alias calls an existing AWS CLI command under the `ec2` command namespace, you can write the command without the `aws ec2` prefix.

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

To create aliases from commands outside of the command namespace, prefix the full command with an exclamation mark. The following example creates an alias named `aws ec2 instance-profiles` using the [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) command.

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

**Note**  
Aliases only use existing command namespaces and you cannot create new ones. e.g. You can't create an alias with the `[command johnsmith]` section as the `johnsmith` command namespace does not already exist.

### Creating a bash scripting alias
<a name="cli-usage-alias-create-alias-scripting"></a>

**Warning**  
To use AWS CLI alias bash scripts, you must use a bash-compatible terminal

You can create an alias using bash scripts for more advanced processes using the following syntax.

**Syntax**

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

The *aliasname* is what you call your alias and *script content* is the script you want to run when you call the alias.

The following example uses `opendns` to output your current IP address. Since you can use aliases in other aliases, the following `myip` alias is useful to allow or revoke access for your IP address from within other aliases. 

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

The following script example calls the previous `aws myip` alias to authorize your IP address for an Amazon EC2 security group ingress.

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

When you call aliases that use bash scripting, the variables are always passed in the order that you entered them. In bash scripting, the variable names are not taken into consideration, only the order they appear. In the following `textalert` alias example, the variable for the `--message` option is first and `--phone-number` option is second.

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

## Step 3: Calling an alias
<a name="cli-usage-alias-call-alias"></a>

To run the alias you created in your `alias` file use the following syntax. You can add additional options when you call your alias.

**Syntax**

```
$ aws aliasname
```

The following example uses the `aws whoami` command alias.

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

The following example uses the `aws whoami` alias with additional options to only return the `Account` number in `text` output.

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

The following example uses the `aws ec2 regions`[ sub-command alias](#cli-usage-alias-create-alias-sub-command).

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

### Calling an alias using bash scripting variables
<a name="cli-usage-alias-call-alias-variables"></a>

When you call aliases that use bash scripting, variables are passed in the order they are entered. In bash scripting, the name of the variables are not taken into consideration, only the order they appear. For example, in the following `textalert` alias, the variable for the option `--message` is first and `--phone-number` is second.

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

When you call the `textalert` alias, you need to pass variables in the same order as they are run in the alias. In the following example we use the variables `$message` and `$phone`. The `$message` variable is passed as `${1}` for the `--message` option and the `$phone` variable is passed as `${2}` for the `--phone-number` option. This results in successfully calling the `textalert` alias to send a message.

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

In the following example, the order is switched when calling the alias to `$phone` and `$message`. The `$phone` variable is passed as `${1}` for the `--message` option and the `$message` variable is passed as `${2}` for the `--phone-number` option. Since the variables are out of order, the alias passes the variables incorrectly. This causes an error because the contents of `$message` do not match the phone number formatting requirements for the `--phone-number` option.

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

## Alias repository examples
<a name="cli-usage-alias-examples"></a>

The [AWS CLI alias repository](https://github.com/awslabs/awscli-aliases) on *GitHub* contains AWS CLI alias examples created by the AWS CLI developer team and community. You can use the entire `alias` file example or take individual aliases for your own use.

**Warning**  
Running the commands in this section deletes your existing `alias` file. To avoid overwriting your existing alias file, change your download location.

**To use aliases from the repository**

1. Install Git. For installation instructions, see [Getting Started - Installing Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) in the *Git Documentation*.

1. Install the `jp` command. The `jp` command is used in the `tostring` alias. For installation instructions, see the [JMESPath (jp) README.md](https://github.com/jmespath/jp) on *GitHub*.

1. Install the `jq` command. The `jq` command is used in the `tostring-with-jq` alias. For installation instructions, see the [JSON processor (jq)](https://stedolan.github.io/jq/download/) on *GitHub*.

1. Download the `alias` file by doing one of the following:
   + Run the following commands that downloads from the repository and copies the `alias` file to your configuration folder.

------
#### [ 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
     ```

------
   + Download directly from the repository and save to the `cli` folder in your AWS CLI configuration folder. By default the configuration folder is `~/.aws/` on Linux or macOS and `%USERPROFILE%\.aws\` on Windows. 

1. To verify the aliases are working, run the following alias.

   ```
   $ aws whoami
   ```

   This displays the same response as the `aws sts get-caller-identity` command:

   ```
   {
       "Account": "012345678901",
       "UserId": "AIUAINBADX2VEG2TC6HD6",
       "Arn": "arn:aws:iam::012345678901:user/myuser"
   }
   ```

## Resources
<a name="cli-usage-alias-references"></a>
+ The [AWS CLI alias repository](https://github.com/awslabs/awscli-aliases) on *GitHub* contains AWS CLI alias examples created by the AWS CLI developer team and the contribution of the AWS CLI community.
+ The alias feature announcement from [AWS re:Invent 2016: The Effective AWS CLI User](https://www.youtube.com/watch?t=1590&v=Xc1dHtWa9-Q) on *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)

# Troubleshooting errors for the AWS CLI
<a name="cli-chap-troubleshooting"></a>

This section covers common errors and troubleshooting steps to follow to resolve your issue. We suggest following the [general troubleshooting](#tshoot-general) first.

**Contents**
+ [General troubleshooting to try first](#tshoot-general)
  + [Check your AWS CLI command formatting](#general-formatting)
  + [Check the AWS Region your AWS CLI command is using](#general-region)
  + [Confirm that you're running a recent version of the AWS CLI](#general-latest)
  + [Use the `--debug` option](#general-debug)
  + [Enable and review the AWS CLI command history logs](#tshoot-general-history)
  + [Confirm that your AWS CLI is configured](#tshoot-general-config)
+ [Command not found errors](#tshoot-install-not-found)
+ [The "`aws --version`" command returns a different version than you installed](#tshoot-install-wrong-version)
+ [The "`aws --version`" command returns a version after uninstalling the AWS CLI](#tshoot-uninstall-1)
+ [The AWS CLI processed a command with an incomplete parameter name](#tshoot-parameter-abbrev)
+ [Access denied errors](#tshoot-access-denied)
+ [Invalid credentials and key errors](#tshoot-permissions-wrongcreds)
+ [Signature does not match errors](#tshoot-signature-does-not-match)
+ [SSL certificate errors](#tshoot-certificate-verify-failed)
+ [Invalid JSON errors](#tshoot-invalid-json)
+ [Additional resources](#tshoot-resources)

## General troubleshooting to try first
<a name="tshoot-general"></a>

If you receive an error or encounter an issue with the AWS CLI, we suggest the following general tips to help you troubleshoot.

[Back to top](#cli-chap-troubleshooting-top)

### Check your AWS CLI command formatting
<a name="general-formatting"></a>

If you receive an error that indicates that a command doesn't exist, or that it doesn't recognize a parameter (`Parameter validation failed`) that the documentation says is available , then your command might be formatted incorrectly. We suggest that you check the following:
+ Check your command for spelling and formatting errors.
+ Confirm all [quotes and escaping appropriate for your terminal](cli-usage-parameters-quoting-strings.md) is correct in your command.
+ Generate an [AWS CLI skeleton](cli-usage-skeleton.md) to confirm your command structure.
+ For JSON, see the additional [troubleshooting for JSON values](#tshoot-invalid-json). If you're having issues with your terminal processing JSON formatting, we suggest skipping past the terminal's quoting rules by using [Blobs to pass JSON data directly to the AWS CLI](cli-usage-parameters-types.md#parameter-type-blob).

For more information on how a specific command should be structured, see the [AWS CLI version 2 reference guide](https://docs.aws.amazon.com/cli/latest/reference/index.html).

[Back to top](#cli-chap-troubleshooting-top)

### Check the AWS Region your AWS CLI command is using
<a name="general-region"></a>

**Note**  
You must specify an AWS Region when using the AWS CLI, either explicitly or by setting a default Region. For a list of all of the AWS Regions that you can specify, see [AWS Regions and Endpoints](https://docs.aws.amazon.com/general/latest/gr/rande.html) in the *Amazon Web Services General Reference*. The AWS Region designators used by the AWS CLI are the same names that you see in AWS Management Console URLs and service endpoints.

Errors or unexpected results might occur if an AWS service isn't available for your specified AWS Region or your resources are located in a different AWS Region. In order of precedence, the AWS Region is set in the following ways:
+ The `--region` command line option.
+ The SDK compatible `AWS\$1REGION` environment variable.
+ The `AWS\$1DEFAULT\$1REGION` environment variable.
+ The [`region`](cli-configure-files.md#cli-config-region) profile setting.

Confirm you're using the correct AWS Region for your resources. 

[Back to top](#cli-chap-troubleshooting-top)

### Confirm that you're running a recent version of the AWS CLI
<a name="general-latest"></a>

If you receive an error that indicates that a command doesn't exist, or that it doesn't recognize a parameter that the [AWS CLI version 2 reference guide](https://docs.aws.amazon.com/cli/latest/reference/index.html) says is available, first confirm that your command is correctly formatted. If the formatting is correct, then we recommend that you upgrade to the most recent version of the AWS CLI. Updated versions of the AWS CLI are released almost every business day. New AWS services, features, and parameters are introduced in those new versions of the AWS CLI. The only way to get access to those new services, features, or parameters is to upgrade to a version that was released after that element was first introduced.

How you update your version of the AWS CLI depends on how you originally installed it as described in [Installing or updating to the latest version of the AWS CLI](getting-started-install.md).

If you used one of the bundled installers, you might need to remove the existing installation before you download and install the latest version for your operating system.

[Back to top](#cli-chap-troubleshooting-top)

### Use the `--debug` option
<a name="general-debug"></a>

When the AWS CLI reports an error that you don't immediately understand, or produces results that you don't expect, you can get more detail about the error by running the command again with the `--debug` option. With this option, the AWS CLI outputs details about every step it takes to process your command. The details in the output can help you to determine when the error occurs and provides clues about where it started.

You can send the output to a text file for later review, or to send to AWS Support when asked for it.

When you include the `--debug` option, some of the details include:
+ Looking for credentials
+ Parsing the provided parameters
+ Constructing the request sent to AWS servers
+ The contents of the request sent to AWS
+ The contents of the raw response
+ The formatted output

Here's an example of a command run with and without the `--debug` option.

```
$ 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"
        }
    ]
}
```

[Back to top](#cli-chap-troubleshooting-top)

### Enable and review the AWS CLI command history logs
<a name="tshoot-general-history"></a>

You can enable the AWS CLI command history logs using the `cli\$1history` file setting. After enabling this setting, the AWS CLI records the history of `aws` commands.

You can this list your history using the `aws history list` command, and use the resulting command\$1ids in the `aws history show` command for details. For more information see [https://docs.aws.amazon.com/cli/latest/reference/history/index.html](https://docs.aws.amazon.com/cli/latest/reference/history/index.html) in the *AWS CLI reference guide*.

When you include the `--debug` option, some of the details include:
+ API calls made to botocore
+ Status codes
+ HTTP responses
+ Headers
+ Return codes

You can use this information to confirm paramater data and API calls are behaving in the way you expect, and can then deduce at what step in the process your command is failing.

[Back to top](#cli-chap-troubleshooting-top)

### Confirm that your AWS CLI is configured
<a name="tshoot-general-config"></a>

Various errors can occur if your `config` and `credentials` files or your IAM user or role is not configured correctly. For more information on resolving errors with `config` and `credentials` files or your IAM user or roles, see [Access denied errors](#tshoot-access-denied) and [Invalid credentials and key errors](#tshoot-permissions-wrongcreds).

[Back to top](#cli-chap-troubleshooting-top)

## Command not found errors
<a name="tshoot-install-not-found"></a>

This error means that the operating system can't find the AWS CLI command. The installation might be incomplete or requires updating.

**Possible cause: You're trying to use an AWS CLI feature newer than your installed version, or have incorrect formatting**  
*Example error text:*  

```
$ 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
```
Various errors can occur if your command is formatted incorrectly or you are using an earlier version from before the feature was released. For more information on resolving errors around these two issues, see [Check your AWS CLI command formatting](#general-formatting) and [Confirm that you're running a recent version of the AWS CLI](#general-latest).  
[Back to top](#cli-chap-troubleshooting-top)

**Possible cause: The terminal needs to be restarted after installation**  
*Example error text:*  

```
$ aws --version
command not found: aws
```
If the `aws` command cannot be found after first installing or updating the AWS CLI, you might need to restart your terminal for it to recognize any `PATH` updates.  
[Back to top](#cli-chap-troubleshooting-top)

**Possible cause: The AWS CLI did not fully install**  
*Example error text:*  

```
$ aws --version
command not found: aws
```
If the `aws` command cannot be found after first installing or updating the AWS CLI, it might not have been fully installed. Try reinstalling by following the steps for your platform in [Installing or updating to the latest version of the AWS CLI](getting-started-install.md).  
[Back to top](#cli-chap-troubleshooting-top)

**Possible cause: The AWS CLI does not have permissions (Linux)**  
If the `aws` command cannot be found after first installing or updating the AWS CLI on Linux, it might not have `execute` permissions for the folder it installed in. Run the following command with the `PATH` to your AWS CLI installation,to provide `[chmod](https://en.wikipedia.org/wiki/Chmod)` permissions to the AWS CLI:  

```
$ sudo chmod -R 755 /usr/local/aws-cli/
```
[Back to top](#cli-chap-troubleshooting-top)

**Possible cause: The operating system `PATH` was not updated during installation**  
*Example error text:*  

```
$ aws --version
command not found: aws
```
You might need to add the `aws` executable to your operating system's `PATH` environment variable. To add the AWS CLI to your `PATH`, use the following instructions for your operating system.  

1. Find your shell's profile script in your user directory. If you're not sure which shell you have, run `echo $SHELL`.

   ```
   $ ls -a ~
   .  ..  .bash_logout  .bash_profile  .bashrc  Desktop  Documents  Downloads
   ```
   + **Bash** – `.bash_profile`, `.profile`, or `.bash_login`
   + **Zsh** – `.zshrc`
   + **Tcsh** – `.tcshrc`, `.cshrc`, or `.login`

1. Add an export command to your profile script. The following command adds your local bin to the current `PATH` variable.

   ```
   export PATH=/usr/local/bin:$PATH
   ```

1. Reload the updated profile into your current session.

   ```
   $ source ~/.bash_profile
   ```

1. In a Windows Command Prompt, use the `where` command with the `/R path` parameter to find the `aws` file location. The results return all folders containing `aws`.

   ```
   C:\> where /R c:\ aws
   c:\Program Files\Amazon\AWSCLIV2\aws.exe
   ...
   ```

   By default, the AWS CLI version 2 is located in:

   ```
   c:\Program Files\Amazon\AWSCLIV2\aws.exe
   ```

1. Press the Windows key and enter **environment variables**.

1. From the list of suggestions, choose **Edit environment variables for your account**.

1. Choose **PATH**, and then choose **Edit**.

1. Add the path you found in the first step into the **Variable value** field, for example, ***C:\$1Program Files\$1Amazon\$1AWSCLIV2\$1aws.exe***.

1. Choose **OK** twice to apply the new settings.

1. Close any running command prompts and reopen the command prompt window.

[Back to top](#cli-chap-troubleshooting-top)

## The "`aws --version`" command returns a different version than you installed
<a name="tshoot-install-wrong-version"></a>

Your terminal might be returning a different `PATH` for the AWS CLI than you expect.

**Possible cause: The terminal needs to be restarted after installing**  
If the `aws` command shows the wrong version, you might need to restart your terminal for it to recognize any `PATH` updates. All open terminals needs to be closed, not just your active terminal.  
[Back to top](#cli-chap-troubleshooting-top)

**Possible cause: The system needs to be restarted after installing**  
If the `aws` command shows the wrong version and restarting the terminal didn't work, you might need to restart your system for it to recognize your `PATH` updates.  
[Back to top](#cli-chap-troubleshooting-top)

**Possible cause: You have multiple versions of the AWS CLI**  
If you updated the AWS CLI and used a different install method than your pre-existing installation, it might cause multiple versions to be installed. For example, if on Linux or macOS you used `pip` for your current install, but tried to update using the `.pkg` install file, this could cause some conflicts especially with your `PATH` pointing to the old version.  
To resolve this, [uninstall all versions of the AWS CLI](#tshoot-uninstall-multiple-version) and perform a clean install.   
After uninstalling all versions, follow instructions appropriate for your operating system to install your desired version of the [AWS CLI version 1](https://docs.aws.amazon.com/cli/v1/userguide/cli-chap-install.html) or [AWS CLI version 2](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html).  
If this is happening after you installed the AWS CLI version 2 with a pre-existing install of AWS CLI version 1, follow the migration instructions in  [Installing AWS CLI version 2 from AWS CLI version 1](cliv2-migration-instructions.md).
[Back to top](#cli-chap-troubleshooting-top)

## The "`aws --version`" command returns a version after uninstalling the AWS CLI
<a name="tshoot-uninstall-1"></a>

This often occurs when there is still an AWS CLI installed somewhere on your system.

**Possible cause: The terminal needs to be restarted after uninstalling**  
If the `aws --version` command still works, you might need to restart your terminal for it to recognize any terminal updates.  
[Back to top](#cli-chap-troubleshooting-top)

**Possible cause: You have multiple versions of the AWS CLI on your system, or didn't use the same uninstall method that you used to originally install the AWS CLI**  
The AWS CLI might not uninstall correctly if you uninstalled the AWS CLI using a different method than you used to install it, or if you installed multiple versions. For example, if you used `pip` for your current install, you must use `pip` to uninstall it. To resolve this, uninstall AWS CLI using the same method that you used to install it.  

1. Follow the instructions appropriate for your operating system and your original installation method to uninstall the [AWS CLI version 1](https://docs.aws.amazon.com/cli/v1/userguide/cli-chap-install.html) and [AWS CLI version 2](https://docs.aws.amazon.com/cli/latest/userguide/uninstall.html).

1. Close all terminals you have open.

1. Open your preferred terminal, enter in the following command and confirm that no version is returned.

   ```
   $ aws --version
   command not found: aws
   ```

   If you still have a version listed in the output, the AWS CLI was most likely installed using a different method or there are multiple versions. If you don't know which method you installed the AWS CLI, follow the instructions for each uninstall method for the [AWS CLI version 1](https://docs.aws.amazon.com/cli/v1/userguide/cli-chap-install.html) and [AWS CLI version 2](https://docs.aws.amazon.com/cli/latest/userguide/uninstall.html) appropriate to your operating system until no version output is received.
**Note**  
If you used a package manager to install the AWS CLI (`pip`, `apt`, `brew`, etc.), you must use the same package manager to uninstall it. Be sure to follow the instructions provided by the package manager on how to uninstall all versions of a package. 
[Back to top](#cli-chap-troubleshooting-top)

## The AWS CLI processed a command with an incomplete parameter name
<a name="tshoot-parameter-abbrev"></a>

**Possible cause: You used a recognized abbreviation of the AWS CLI parameter**  
Since the AWS CLI is built using Python, the AWS CLI uses the Python `argparse` library, including the [https://docs.python.org/3/library/argparse.html#allow-abbrev](https://docs.python.org/3/library/argparse.html#allow-abbrev) argument. Abbreviations of parameters are recognized by the AWS CLI and processed.  
The following [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) command example changes the CloudFormation stack name. The parameter `--change-set-n` is recognized as an abbreviation of `--change-set-name`, and the AWS CLI processes the command.  

```
$ aws cloudformation create-change-set --stack-name my-stack --change-set-n my-change-set
```
When your abbreviation could be multiple commands, the parameter will not be recognized as an abbreviation.  
The following [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) command example changes the CloudFormation stack name. The parameter `--change-set-` is **not** recognized as an abbreviation, as there are there are multiple parameters it could be an abbreviation of, such as `--change-set-name` and `--change-set-type`. Therefore the AWS CLI does **not** process the command.  

```
$ aws cloudformation create-change-set --stack-name my-stack --change-set- my-change-set
```
**Do not** purposefully use parameter abbreviations. They are unreliable and are not backwards compatible. If any new parameters are added to a command that confuse your abbreviations, it will break your commands.  
Additionally, if the parameter is a single-value argument, it can cause unexpected behavior with your commands. If multiple instances of a single-value argument is passed, only the last instance will run. In the following example, the parameter `--filters` is a single-valued argument. The parameters `--filters` and `--filter` are specified. The `--filter` parameter is an abbreviation of `--filters`. This cause two instances of `--filters` being applied and only the last `--filter` argument applies.   

```
$ aws ec2 describe-vpc-peering-connections \
    --filters Name=tag:TagName,Values=VpcPeeringConnection \
    --filter Name=status-code,Values=active
```
Confirm you are using valid parameters before running a command to prevent unexpected behavior.
[Back to top](#cli-chap-troubleshooting-top)

## Access denied errors
<a name="tshoot-access-denied"></a>

**Possible cause: The AWS CLI program file doesn't have "run" permission**  
On Linux or macOS, make sure that the `aws` program has run permissions for the calling user. Typically, the permissions are set to `755`.  
To add run permission for your user, run the following command, substituting *\$1/.local/bin/aws* with the path to the program on your computer.  

```
$ chmod +x ~/.local/bin/aws
```
[Back to top](#cli-chap-troubleshooting-top)

**Possible cause: Your IAM identity doesn't have permission to perform the operation**  
*Example error text:*  

```
$ aws s3 ls
An error occurred (AcessDenied) when calling the ListBuckets operation: Access denied.
```
When you run a AWS CLI command, AWS operations are performed on your behalf, using credentials that associate you with an IAM account or role. The policies attached must grant you permission to call the API actions that correspond to the commands that you run with the AWS CLI.   
Most commands call a single action with a name that matches the command name. However, custom commands like `aws s3 sync` call multiple APIs. You can see which APIs a command calls by using the `--debug` option.  
If you are sure that the user or role has the proper permissions assigned by policy, make sure that your AWS CLI command is using the credentials you expect. See the [next section about credentials](#tshoot-permissions-wrongcreds) to verify that the credentials the AWS CLI is using are the ones that you expect.  
For information about assigning IAM permissions, see [Overview of Access Management: Permissions and Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction_access-management.html) in the *IAM User Guide*.  
[Back to top](#cli-chap-troubleshooting-top)

## Invalid credentials and key errors
<a name="tshoot-permissions-wrongcreds"></a>

*Example error text:*

```
$ 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.
```

**Possible cause: The AWS CLI is reading incorrect credentials or from an unexpected location**  
The AWS CLI might be reading credentials from a different location than you expect, or your key pair information is incorrect. You can run `aws configure list` to confirm which credentials are used.  
The following example shows how to check the credentials used for the default profile.  

```
$ 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
```
The following example shows how to check the credentials of a named profile.  

```
$ 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
```
To confirm your key pair details, check your `config` and `credentials` files. For more information on `config` and `credentials` files, see [Configuration and credential file settings in the AWS CLI](cli-configure-files.md). For more information on credentials and authentication, including credentials precedence, see [Authentication and access credentials for the AWS CLI](cli-chap-authentication.md).  
[Back to top](#cli-chap-troubleshooting-top)

**Possible cause: Your computer's clock is out of sync**  
If you are using valid credentials, your clock might be out of sync. On Linux or macOS, run `date` to check the time.  

```
$ date
```
If your system clock is not correct within a few minutes, use `ntpd` to sync it.  

```
$ sudo service ntpd stop
$ sudo ntpdate time.nist.gov
$ sudo service ntpd start
$ ntpstat
```
On Windows, use the date and time options in the Control Panel to configure your system clock.  
[Back to top](#cli-chap-troubleshooting-top)

## Signature does not match errors
<a name="tshoot-signature-does-not-match"></a>

*Example error text:*

```
$ 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.
```

When the AWS CLI runs a command, it sends an encrypted request to the AWS servers to perform the appropriate AWS service operations. Your credentials (the access key and secret key) are involved in the encryption and enable AWS to authenticate the person making the request. There are several things that can interfere with the correct operation of this process, as follows.

**Possible cause: Your clock is out of sync with the AWS servers**  
To help protect against [replay attacks](https://wikipedia.org/wiki/Replay_attack), the current time can be used during the encryption/decryption process. If the time of the client and server disagree by more than the allowed amount, the process can fail and the request is rejected. This can also happen when you run a command in a virtual machine whose clock is out of sync with the host machine's clock. One possible cause is when the virtual machine hibernates and takes some time after waking up to sync the clock with the host machine.  
On Linux or macOS, run `date` to check the time.  

```
$ date
```
If your system clock is not correct within a few minutes, use `ntpd` to sync it.  

```
$ sudo service ntpd stop
$ sudo ntpdate time.nist.gov
$ sudo service ntpd start
$ ntpstat
```
On Windows, use the date and time options in the Control Panel to configure your system clock.   
[Back to top](#cli-chap-troubleshooting-top)

**Possible cause: Your operating system is mishandling AWS keys that contain certain special characters**  
If your AWS keys include certain special characters, such as `-`, `+`, `/`, or `%`, some operating system variants process the string improperly and cause the key string to be interpreted incorrectly.  
If you process your keys using other tools or scripts, such as tools that build the credentials file on a new instance as part of its creation, those tools and scripts might have their own handling of special characters that causes them to be transformed into something that AWS no longer recognizes.  
We suggest regenerating the secret key to get one that does not include the special character causing issues.  
[Back to top](#cli-chap-troubleshooting-top)

## SSL certificate errors
<a name="tshoot-certificate-verify-failed"></a>

**Possible cause: The AWS CLI doesn't trust your proxy's certificate**  
*Example error text:*  

```
$ aws s3 ls
[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed
```
When you use a AWS CLI command, you receive an `[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed` error message. This is caused by the AWS CLI not trusting your proxy's certificate due to factors such as your proxy's certificate being self-signed, with your company set as the Certification Authority (CA). This prevents the AWS CLI from finding your companies CA root certificate in the local CA registry.  
To fix this, instruct the AWS CLI where to find your companies `.pem` file using the `ca\$1bundle` configuration file setting, **[--ca-bundle](cli-configure-options.md#cli-configure-options-ca-bundle)** command line option, or the `AWS\$1CA\$1BUNDLE` environment variable.  
[Back to top](#cli-chap-troubleshooting-top)

**Possible cause: Your configuration isn't pointing to the correct CA root certificate location**  
*Example error text:*  

```
$ aws s3 ls
SSL validation failed for regionname [Errno 2] No such file or directory
```
This is caused by your Certification Authority (CA) bundle file location being configured incorrectly in the AWS CLI. To fix this, confirm where your companies `.pem` file is located and update the AWS CLI configuration by using the `ca\$1bundle` configuration file setting, **[--ca-bundle](cli-configure-options.md#cli-configure-options-ca-bundle)** command line option, or the `AWS\$1CA\$1BUNDLE` environment variable.  
[Back to top](#cli-chap-troubleshooting-top)

**Possible cause: Your configuration isn't using the correct AWS Region**  
*Example error text:*  

```
$ aws s3 ls
[SSL: CERTIFICATE_ VERIFY_FAILED] certificate verify failed
```
Errors or unexpected results might occur if an AWS service isn't available for your specified AWS Region or your resources are located in a different AWS Region. For troubleshooting steps, see [Check the AWS Region your AWS CLI command is using](#general-region).  
[Back to top](#cli-chap-troubleshooting-top)

**Possible cause: Your TLS version needs to be updated **  
*Example error text:*  

```
$ aws s3 ls
[SSL: UNSAFE_LEGACY_RENEGOTIATION_DISABLED] unsafe legacy renegotiation disabled
```
The AWS service is using a version of TLS that is incompatible with your device's TLS version. To resolve this issue, update to a supported TLS version. For more information, see [Enforcing a minimum version of TLS for the AWS CLI](cli-security-enforcing-tls.md).  
[Back to top](#cli-chap-troubleshooting-top)

## Invalid JSON errors
<a name="tshoot-invalid-json"></a>

*Example error text:*

```
$ 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}
```

When you use an AWS CLI command, you receive a "`Invalid JSON`" error message. This is usually an error seen when you enter a command with an expected JSON format and the AWS CLI cannot read your JSON correctly.

**Possible cause: You did not enter valid JSON for the AWS CLI to use**  
Confirm you have valid JSON entered for your command. We suggest using a JSON validator for JSON you're having issues formatting.   
For more advanced JSON usage in the command line, consider using a command line JSON processor, like `jq`, to create JSON strings. For more information on `jq`, see the [jq repository](http://stedolan.github.io/jq/) on *GitHub*.  
[Back to top](#cli-chap-troubleshooting-top)

**Possible cause: Your terminal's quoting rules are preventing valid JSON being sent to the AWS CLI**  
Before the AWS CLI receives anything from a command, your terminal processes the command using it's own quoting and escaping rules. Due to a terminal's formatting rules, some of your JSON content may be stripped before the command is passed to the AWS CLI. When formulating commands, be sure to use your [terminal's quoting rules](cli-usage-parameters-quoting-strings.md).  
To troubleshoot, use the `echo` command to see how the shell is handling your parameters:  

```
$ echo {"ReadCapacityUnits":15,"WriteCapacityUnits":10}
ReadCapacityUnits:15 WriteCapacityUnits:10
```

```
$ echo '{"ReadCapacityUnits":15,"WriteCapacityUnits":10}'
{"ReadCapacityUnits":15,"WriteCapacityUnits":10}
```
Modify your command until your until valid JSON is returned.  
For more in-depth troubleshooting, use the `--debug` parameter to view the debug logs as they'll display exactly what got passed to the 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']
```
Use your terminal's quoting rules to fix any issues your JSON input has when being sent to the AWS CLI. For more information on quoting rules, see [Using quotation marks and literals with strings in the AWS CLI](cli-usage-parameters-quoting-strings.md).  
If you're having issues with getting valid JSON to the AWS CLI, we recommend to bypass a terminal's quoting rules for JSON data input by using Blobs to pass your JSON data directly to the AWS CLI. For more information on Blobs, see [Blob](cli-usage-parameters-types.md#parameter-type-blob).
[Back to top](#cli-chap-troubleshooting-top)

## Additional resources
<a name="tshoot-resources"></a>

For additional help with your AWS CLI issues, visit the [AWS CLI community](https://github.com/aws/aws-cli/issues) on *GitHub* or the [AWS re:Post community](https://repost.aws/).

[Back to top](#cli-chap-troubleshooting-top)