

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

AWS Command Line Interface（AWS CLI）中使用的很多参数都是简单的字符串或数值，例如下面的 `aws ec2 create-key-pair` 命令示例中的密钥对名称 `my-key-pair`。

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

终端之间的命令格式可能会有所不同。例如，大多数终端区分大小写，但 Powershell 不区分大小写。这意味着，以下两个命令示例对于区分大小写的终端会产生不同的结果，因为它们将 `MyFile*.txt` 和 `myfile*.txt` 视为**不同的**参数。

但是，PowerShell 会将 `MyFile*.txt` 和 `myfile*.txt` 视为**相同的**参数来处理这些请求。以下命令示例使用 `aws s3 cp` 命令演示了这些参数：

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

有关 PowerShell 的不区分大小写的更多信息，请参阅 PowerShell 文档**中的 [about\$1Case-Sensitivity](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_case-sensitivity)

有时，您需要在包含特殊字符或空格字符的字符串周围使用引号或文字。有关此格式的规则也可能因终端而异。有关在复杂参数周围使用引号的更多信息，请参阅 [在 AWS CLI 中将引号和文本与字符串结合使用](cli-usage-parameters-quoting-strings.md)。

这些主题涵盖最常见的终端格式设置规则。如果您在终端识别参数值时遇到问题，请务必查看本节中的主题，并查看终端文档以了解其特定语法规则。

**Topics**
+ [AWS CLI 中的通用参数类型](cli-usage-parameters-types.md)
+ [在 AWS CLI 中将引号和文本与字符串结合使用](cli-usage-parameters-quoting-strings.md)
+ [在 AWS CLI 中从文件加载参数](cli-usage-parameters-file.md)
+ [在 AWS CLI 中生成 AWS CLI 骨架和输入文件](cli-usage-skeleton.md)
+ [在 AWS CLI 中使用速记语法](cli-usage-shorthand.md)

# AWS CLI 中的通用参数类型
<a name="cli-usage-parameters-types"></a>

本节介绍一些通用参数类型以及典型的所需格式。

如果您不知道如何设置特定命令的参数格式，请在命令名称后输入 **help** 来查看帮助。每个子命令的帮助均包括一个选项的名称和描述。该选项的参数类型在括号中列出。有关查看帮助的更多信息，请参阅 [在 AWS CLI 中获取帮助和资源](cli-usage-help.md)。

**Topics**
+ [字符串](#parameter-type-string)
+ [Timestamp](#parameter-type-timestamp)
+ [列表](#parameter-type-list)
+ [布尔值](#parameter-type-boolean)
+ [整数](#parameter-type-integer)
+ [二进制/Blob（二进制大型对象）和流式传输 Blob](#parameter-type-blobs)
+ [映射](#parameter-type-map)
+ [文档](#parameter-type-document)

## 字符串
<a name="parameter-type-string"></a>

字符串参数可以包含 [ASCII](https://wikipedia.org/wiki/ASCII) 字符集中的字母数字字符、符号和空格。包含空格的字符串必须用引号引起来。建议您不要使用标准空格字符以外的符号或空格，并遵循终端的[引用规则](cli-usage-parameters-quoting-strings.md)，以防止出现意外结果。

一些字符串参数可接受来自文件的二进制数据。有关示例，请参阅[二进制文件](cli-usage-parameters-file.md#cli-usage-parameters-file-binary)。

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

时间戳根据 [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) 标准设置格式。这些通常称为“`DateTime`”或“`Date`”参数。

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

可接受的格式包括：
+ *YYYY*-*MM*-*DD*T*hh*:*mm*:*ss.sss**TZD (UTC)*，例如，2014-10-01T20:30:00.000Z
+ *YYYY*-*MM*-*DD*T*hh*:*mm*:*ss.sss**TZD（带偏移量）*，例如，2014-10-01T12:30:00.000-08:00
+ *YYYY*-*MM*-*DD*，例如，2014-10-01
+ 以秒为单位的 Unix 时间，如 1412195400。这有时称为 [Unix 纪元时间](https://wikipedia.org/wiki/Unix_time)，表示自 1970 年 1 月 1 日午夜 (UTC) 以来经历的秒数。

预设情况下，AWS CLI 版本 2 会将所有***响应*** DateTime 值转换为 ISO 8601 格式。

您可以使用 `cli\$1timestamp\$1format` 文件设置来设置时间戳格式。

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

以空格分隔的一个或多个字符串。如果任何字符串项目包含空格，则必须用引号括起该项目。遵循您终端的[引号规则](cli-usage-parameters-quoting-strings.md)以防止出现意外结果。

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

## 布尔值
<a name="parameter-type-boolean"></a>

打开或关闭某一选项的二进制标志。例如，`ec2 describe-spot-price-history` 有一个布尔 `--dry-run` 参数，如果指定该参数，则针对服务验证查询而不实际运行查询。

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

输出指示命令格式是否正确。此命令还包含一个 `--no-dry-run` 参数版本，可以用来显式指示命令应正常运行。不过不是必须包含此参数，因为这是默认行为。

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

无符号整数。

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

## 二进制/Blob（二进制大型对象）和流式传输 Blob
<a name="parameter-type-blobs"></a>

在 AWS CLI 中，您可以将二进制值作为字符串直接在命令行上传递。共有两种类型的 blob：
+ [Blob](#parameter-type-blob)
+ [流式 blob](#parameter-type-streaming-blob)

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

要将值传递给类型为 `blob` 的参数，必须使用 `fileb://` 前缀指定包含二进制数据的本地文件的路径。使用 `fileb://` 前缀引用的文件始终被作为原始未编码二进制文件进行处理。指定的路径被解释为相对于当前工作目录。例如，适用于 `aws kms encrypt` 的 `--plaintext` 参数是一个 blob。

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

**注意**  
为了向后兼容，您可以使用 `file://` 前缀。根据文件设置 `cli\$1binary\$1format` 或 `--cli-binary-format` 命令行选项，可以使用两种格式：  
AWS CLI 版本 2 的默认值。如果设置的值为 `base64`，则使用 `file://` 前缀引用的文件将被作为 base64 编码文本进行处理。
AWS CLI 版本 1 的默认值。如果设置的值为 `raw-in-base64-out`，则使用 `file://` 前缀引用的文件会作为文本进行读取，然后 AWS CLI 尝试将其编码为二进制。
有关更多信息，请参阅文件设置 `cli\$1binary\$1format` 或 `--cli-binary-format` 命令行选项。

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

`aws cloudsearchdomain upload-documents` 等流式 Blob 不使用前缀。相反，流式传输 blob 参数使用直接文件路径进行格式化。以下示例对于 `aws cloudsearchdomain upload-documents` 命令使用直接文件路径 `document-batch.json`：

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

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

使用 JSON 或 CLI 的[速记语法](cli-usage-shorthand.md)指定的一系列密钥值对。以下 JSON 示例使用 map 参数 `--key` 从名为 *my-table* 的 Amazon DynamoDB 表中读取项目。此参数在嵌套的 JSON 结构中指定名为 *id* 且数值为 *1* 的主键。

要在命令行中使用更高级的 JSON，请考虑使用 `jq` 等命令行 JSON 处理器来创建 JSON 字符串。有关 `jq` 的更多信息，请参阅 *GitHub* 上的 [jq 存储库](http://stedolan.github.io/jq/)。

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

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

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

**注意**  
[速记语法](cli-usage-shorthand.md)与文档类型不兼容。

文档类型用于发送数据，无需在字符串中嵌入 JSON。文档类型使服务能够提供任意架构，以便您使用更灵活的数据类型。

这使得无需对值转义，即可发送 JSON 数据。例如，不使用以下转义的 JSON 输入：

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

您可以使用以下文档类型：

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

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

由于文档类型本身多种多样，因此存在多个有效值类型。有效值包括：

**字符串**  

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

**数字**  

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

**布尔值**  

```
--option true
```

**Null**  

```
--option null
```

**数组**  

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

**对象**  

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

# 在 AWS CLI 中将引号和文本与字符串结合使用
<a name="cli-usage-parameters-quoting-strings"></a>

在 AWS CLI 中使用单引号和双引号主要有两种方式。
+ [在包含空格的字符串周围使用引号](#cli-usage-parameters-quoting-strings-around)
+ [在字符串内使用引号](#cli-usage-parameters-quoting-strings-containing)

## 在包含空格的字符串周围使用引号
<a name="cli-usage-parameters-quoting-strings-around"></a>

参数名称及其值由命令行中的空格分隔。如果字符串值包含嵌入式空格，则必须用引号将整个字符串括起来，以防止 AWS CLI 将空格误解为值与下一个参数名称之间的分隔符。您使用的引号类型取决于您运行 AWS CLI 的操作系统。

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

使用单引号 `' '` 

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

有关使用引号的更多信息，请参阅首选 Shell 的用户文档。

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

**单引号（推荐）**

单引号 `' '` 称为 `verbatim` 字符串。字符串将完全按照您键入的方式传递给命令，这意味着 PowerShell 变量将不会传递。

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

**双引号**

双引号 `" "` 称为 `expandable` 字符串。变量可以在可展开的字符串中传递。

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

有关使用引号的更多信息，请参阅 *Microsoft PowerShell 文档* 中的[关于引号规则](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_quoting_rules?view=powershell-7)。

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

使用双引号 `" "`。

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

------

（可选）您可以用等号 `=` 而不是空格将参数名称和值分隔开。这通常仅在参数的值以连字符开头时有必要。

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

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

字符串可能包含引号，并且您的 Shell 可能需要对引号进行转义才能让其正常发挥作用。常见的参数值类型之一是 JSON 字符串。这很复杂，因为它在 JSON 结构中的每个元素名称和值周围都包含空格和双引号 `" "`。在命令行中输入 JSON 格式参数的方式因操作系统而异。

要在命令行中使用更高级的 JSON，请考虑使用 `jq` 等命令行 JSON 处理器来创建 JSON 字符串。有关 `jq` 的更多信息，请参阅 *GitHub* 上的 [jq 存储库](http://stedolan.github.io/jq/)。

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

为了让 Linux 和 macOS 按字面含义解释字符串，请使用单引号 `' '` 将 JSON 数据结构括住，如以下示例所示。您不需要对嵌入在 JSON 字符串中的双引号进行转义，因为会按字面含义对它们进行处理。由于 JSON 用单引号括住，因此字符串中的任何单引号都需要进行转义，这通常通过在单引号 `\'` 前面使用反斜杠来实现。

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

有关使用引号的更多信息，请参阅首选 Shell 的用户文档。

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

使用单引号 `' '` 或双引号 `" "`。

**单引号（推荐）**

单引号 `' '` 称为 `verbatim` 字符串。字符串将完全按照您键入的方式传递给命令，这意味着 PowerShell 变量将不会传递。

由于 JSON 数据结构包含双引号，因此我们建议使用**单** 引号 `' '` 将其括起来。如果使用**单** 引号，则不需要对嵌入在 JSON 字符串中的**双** 引号进行转义。但是，您需要在 JSON 结构中使用反撇号 ``` 对每个**单** 引号进行转义。

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

**双引号**

双引号 `" "` 称为 `expandable` 字符串。变量可以在可展开的字符串中传递。

如果您使用**双** 引号，则不需要对嵌入在 JSON 字符串中的**单** 引号进行转义。但是，您需要在 JSON 结构中使用反撇号 ``` 对每个**双** 引号进行转义，如以下示例所示。

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

有关使用引号的更多信息，请参阅 *Microsoft PowerShell 文档* 中的[关于引号规则](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_quoting_rules?view=powershell-7)。

**警告**  
PowerShell 在向 AWS CLI 发送命令之前，它会确定是使用典型 PowerShell 还是 `CommandLineToArgvW` 引用规则来解释您的命令。PowerShell 使用 `CommandLineToArgvW` 进行处理时，必须用反斜杠 `\` 对字符进行转义。  
有关 PowerShell 中 `CommandLineToArgvW` 的更多信息，请参阅 *Microsoft DevBlogs* 上的 [What's up with the strange treatment of quotation marks and backslashes by CommandLineToArgvW](https://devblogs.microsoft.com/oldnewthing/20100917-00/?p=12833)（CommandLineToArgvW 对引号和反斜杠的奇怪处理是怎么回事）、*Microsoft Docs Blog* 中的 [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)（每个人引用命令行参数的方法都错了）以及 *Microsoft Docs* 上的 [CommandLineToArgvW function](https://docs.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-commandlinetoargvw#remarks)（CommandLineToArgvW 函数）。  
**单引号**  
单引号 `' '` 称为 `verbatim` 字符串。字符串将完全按照您键入的方式传递给命令，这意味着 PowerShell 变量将不会传递。使用反斜杠 `\` 对字符进行转义。  

```
PS C:\> aws ec2 run-instances `
    --image-id ami-12345678 `
    --block-device-mappings '[{\"DeviceName\":\"/dev/sdb\",\"Ebs\":{\"VolumeSize\":20,\"DeleteOnTermination\":false,\"VolumeType\":\"standard\"}}]'
```
**双引号**  
双引号 `" "` 称为 `expandable` 字符串。变量可以在 `expandable` 字符串中传递。对于双引号字符串，必须对每个引号使用 *`\$1* 进行两次转义，而不是仅使用反引号。反引号对反斜杠进行转义，然后将反斜杠用作 `CommandLineToArgvW` 流程的转义字符。  

```
PS C:\> aws ec2 run-instances `
    --image-id ami-12345678 `
    --block-device-mappings "[{`\"DeviceName`\":`\"/dev/sdb`\",`\"Ebs`\":{`\"VolumeSize`\":20,`\"DeleteOnTermination`\":false,`\"VolumeType`\":`\"standard`\"}}]"
```
**Blob（推荐）**  
要绕过 JSON 数据输入的 PowerShell 引用规则，请使用 Blob 将 JSON 数据直接传递到 AWS CLI。有关 Blob 的更多信息，请参阅[Blob](cli-usage-parameters-types.md#parameter-type-blob)。

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

Windows 命令提示符要求使用双引号 `" "` 括住 JSON 数据结构。此外，为了防止命令处理器误解 JSON 中嵌入的双引号，还必须对 JSON 数据结构本身中的每个双引号 `\` 进行转义（在前面加一个反斜杠 `"` 字符），如以下示例所示。

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

只有最外层双引号不进行转义。

------

# 在 AWS CLI 中从文件加载参数
<a name="cli-usage-parameters-file"></a>

有些参数需要文件名作为变量，AWS CLI 将从这些变量中加载数据。其他参数允许您将参数值指定为在命令行上键入的文本或从文件中读取的文本。无论文件是必需的还是可选的，您都必须对文件进行正确编码，以便 AWS CLI 能够理解它。该文件的编码必须与读取系统的默认区域设置相匹配。您可以通过使用 Python `locale.getpreferredencoding()` 方法来确定这一点。

此方法用于为单个参数加载文件。有关使用单个文件加载多个参数的信息，请参阅[在 AWS CLI 中生成 AWS CLI 骨架和输入文件](cli-usage-skeleton.md)。

**注意**  
默认情况下，Windows PowerShell 将文本输出为 UTF-16，这与 JSON 文件和许多 Linux 系统使用的 UTF-8 编码冲突。建议您将 `-Encoding ascii` 与 PowerShell `Out-File` 命令一起使用，以确保 AWS CLI 可以读取生成的文件。

**Topics**
+ [如何从文件加载参数](#cli-usage-parameters-file-how)
+ [二进制文件](#cli-usage-parameters-file-binary)
+ [将文件作为速记语法值进行加载](#cli-usage-parameters-file-shorthand)

## 如何从文件加载参数
<a name="cli-usage-parameters-file-how"></a>

有时，从文件加载参数值（而不是尝试将其全部键入为命令行参数值）很方便，例如当参数为复杂的 JSON 字符串时。要指定包含该值的文件，请按以下格式指定文件 URL。

```
file://complete/path/to/file
```
+ 前两个斜杠“/”字符是规范的一部分。如果所需的路径以“/”开头，结果为三个斜杠字符：`file:///folder/file`。
+ URL 提供包含实际参数内容的文件的路径。
+ 使用带空格或特殊字符的文件时，请遵循终端的[引用和转义规则](cli-usage-parameters-quoting-strings.md)。

以下示例中的文件路径被解读为相对于当前工作目录。

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

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

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

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

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

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

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

------

`file://` 前缀选项支持包含“`~/`”、“`./`”和“`../`”的 Unix 式扩展。在 Windows 上，“`~/`”表达式将展开到您的用户目录（存储在 `%USERPROFILE%` 环境变量中）。例如，在 Windows 10 上，您通常在 `%USERPROFILE%` 下有一个用户目录。

仍必须对作为另一个 JSON 文档的值嵌入的 JSON 文档进行转义。

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

**attributes.json**

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

## 二进制文件
<a name="cli-usage-parameters-file-binary"></a>

对于将二进制数据用作参数的命令，请使用 `fileb://` 前缀指定该数据为二进制内容。接受二进制数据的命令包括：
+  **`aws ec2 run-instances:`** `--user-data` 参数。
+  **`aws s3api put-object:`** `--sse-customer-key` 参数。
+  **`aws kms decrypt:`** `--ciphertext-blob` 参数。

以下示例使用 Linux 命令行工具生成一个二进制 256 位 AES 密钥，然后将该密钥提供给 Amazon S3 以对上载的文件服务器端进行加密。

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

有关引用包含 JSON 格式参数的文件的更多示例，请参阅[将 IAM 托管式策略附加到用户](cli-services-iam.md#cli-services-iam-policy)。

## 将文件作为速记语法值进行加载
<a name="cli-usage-parameters-file-shorthand"></a>

如果在值较大或较复杂的情况下使用速记语法，通常更易以值的形式加载文件。要将文件作为速记语法值进行加载，格式将略有变化。使用 `@=` 运算符代替 `=` 运算符，而不使用 `key=value`。`@=` 告知 AWS CLI，值应作为文件路径而不是字符串进行读取。以下示例显示一个键值对，该键值对为其值加载文件。

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

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

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

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

------

以下示例演示如何为 `aws rolesanywhere create-trust-anchor` 命令加载证书文件。

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

有关速记语法的更多信息，请参阅[在 AWS CLI 中使用速记语法](cli-usage-shorthand.md)。

# 在 AWS CLI 中生成 AWS CLI 骨架和输入文件
<a name="cli-usage-skeleton"></a>

大多数 AWS CLI 命令接受从文件导入参数输入。可以使用 `generate-cli-skeleton` 选项生成这些模板，然后使用 `--cli-input-json` 和 `--cli-input-yaml` 参数将其导入。

**Topics**
+ [关于 AWS CLI 框架和输入文件](#cli-usage-skeleton-about)
+ [生成和导入命令骨架](#cli-usage-skeleton-generate)
+ [合并输入文件和命令行参数](#cli-usage-skeleton-combine)

## 关于 AWS CLI 框架和输入文件
<a name="cli-usage-skeleton-about"></a>

大多数 AWS Command Line Interface（AWS CLI）命令支持使用 `--cli-input-json` 和 `--cli-input-yaml` 参数接受文件中的参数输入的功能。

这些相同的命令使用 `--generate-cli-skeleton` 参数通过所有可编辑和填写的参数以 JSON 或 YAML 格式生成文件。然后，您可以运行带 `--cli-input-json` 或 `--cli-input-yaml` 参数的命令并指向填充的文件。

**重要**  
自定义 AWS CLI 命令（例如 [`aws s3` 命令](https://docs.aws.amazon.com/cli/latest/reference/s3/index.html)）不支持本主题中介绍的 `--generate-cli-skeleton` 或 `--cli-input-json` 和 `--cli-input-yaml` 参数。要检查特定命令是否支持这些参数，请为要使用的命令运行 [`help` 命令](cli-usage-help.md#cli-usage-help-command)，或参阅 [AWS CLI 版本 2 参考指南](https://docs.aws.amazon.com/cli/latest/reference/index.html)。

`--generate-cli-skeleton` 生成和显示可自定义并用作命令输入的参数模板。生成的模板包含命令支持的所有参数。

`--generate-cli-skeleton` 参数接受以下值之一：
+ `input` – 生成的模板包括格式化为 JSON 的所有输入参数。这是默认值。
+ `yaml-input` – 生成的模板包括格式化为 YAML 的所有输入参数。
+ `output` – 生成的模板包括格式化为 JSON 的所有输出参数。您当前无法请求输出参数作为 YAML。

由于 AWS CLI 本质上是围绕服务 API 的“包装程序”，骨架文件预计您会通过他们底层的 API 参数名称引用所有参数。该参数名称可能与 AWS CLI 参数名称不同。例如，一个名为 AWS CLI 的 `user-name` 参数可能映射到名为 AWS 的 `UserName` 服务 API 参数（注意，更改后的大写字母和缺失的破折号）。我们建议您使用 `--generate-cli-skeleton` 选项，用“正确”的参数名称生成模板，以避免错误。您可以参考服务的《API 参考指南》，查看预期的参数名称。您可以从模板中删除不需要的和不想为其提供值的任何参数。

例如，如果您运行以下命令，它会为 Amazon Elastic Compute Cloud（Amazon EC2）命令 **run-instances** 生成参数模板。

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

以下示例演示如何使用 `input` 参数的默认值（`--generate-cli-skeleton`）生成格式化为 JSON 的模板。

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

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

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

以下示例演示如何使用 `--generate-cli-skeleton` 参数的值 `yaml-input` 生成格式化为 YAML 的模板。

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

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

------

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

**生成并使用参数框架文件**

1. 使用 `--generate-cli-skeleton` 参数运行命令以生成 JSON 或 YAML，并将输出定向到某个文件以保存它。

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

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

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

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

------

1. 在文本编辑器中打开参数骨架文件，并删除任何不需要的参数。例如，您可以将模板缩减到以下内容。请确认在删除不需要的元素后，文件仍是有效的 JSON 或 YAML。

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

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

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

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

------

   在此示例中，我们将 `DryRun` 参数设置为 `true` 以使用 Amazon EC2 空运行功能。通过此功能，您可以安全地测试命令，而无需实际创建或修改任何资源。

1. 使用适合您的场景的值填入剩余的值。在本例中，我们提供要使用的 Amazon 机器映像（AMI）的实例类型、密钥名称、安全组和标识符。此示例假定默认 AWS 区域。AMI `ami-dfc39aef` 是 `us-west-2` 区域中托管的 64 位 Amazon Linux 映像。如果您使用不同的区域，您必须[查找正确 AMI ID 来使用](https://aws.amazon.com/amazon-linux-ami/)。

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

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

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

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

------

1. 通过使用 `file://` 前缀将完成的模板文件传递到 `--cli-input-json` 或 --`cli-input-yaml` 参数，使用填写的参数运行命令。AWS CLI 将路径解释为相对于当前工作目录。在以下示例中，AWS CLI 在当前工作目录中查找文件。

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

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

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

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

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

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

------

   空运行错误表明，JSON 或 YAML 格式正确且参数值有效。如果输出中报告了其他问题，请解决这些问题并重复上一步，直到显示“`Request would have succeeded`”消息。

1. 现在，您可以将 `DryRun` 参数设置为 `false` 以禁用空运行。

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

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

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

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

------

1. 运行此命令，`run-instances` 实际上会启动 Amazon EC2 实例并显示成功启动所生成的详细信息。输出格式由 `--output` 参数控制，与输入参数模板的格式分开。

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

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

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

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

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

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

------

## 合并输入文件和命令行参数
<a name="cli-usage-skeleton-combine"></a>

输入文件可用于所有参数，也可与 AWS CLI 中指定的参数组合使用。您可以将此功能用于在输入文件中频繁重用的设置，并将个人设置保留在命令本身中。

以下 `aws ec2 run-instances` 示例结合使用了输入文件和参数。我们提供要使用的亚马逊机器映像（AMI）的实例类型、密钥名称、安全组和标识符，并假定默认 AWS 区域。AMI `ami-dfc39aef` 是 `us-west-2` 区域中托管的 64 位 Amazon Linux 映像。如果您使用不同的区域，您必须[查找正确 AMI ID 来使用](https://aws.amazon.com/amazon-linux-ami/)。

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

JSON 文件的内容：

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

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

YAML 文件的内容：

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

------

以下示例结合使用输入文件与 `--dry-run` 参数来试运行命令，以确认您是否拥有所需的权限并在文件中填入了有效值。

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

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

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

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

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

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

------

之后，以下示例将同一输入文件与 `--no-dry-run` 参数结合使用来执行完整命令。

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

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

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

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

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

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

------

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

AWS Command Line Interface（AWS CLI）可以接受 JSON 格式的许多选项。但是，在命令行上输入较大的 JSON 列表或结构会比较繁琐。为了简化此过程，AWS CLI 还支持一种速记语法，允许采用比完整 JSON 格式更简单的方式表示选项参数。

**Topics**
+ [使用键值对组织参数。](#shorthand-structure-parameters)
+ [将文件作为速记语法值进行加载](#shorthand-files)
+ [将速记语法与 AWS CLI 结合使用](#shorthand-list-parameters)

## 使用键值对组织参数。
<a name="shorthand-structure-parameters"></a>

通过 AWS CLI 中的速记语法，用户更容易输入平面（非嵌套结构）参数。格式采用以逗号分隔的键值对列表。请务必使用适用于终端的[引用](cli-usage-parameters-quoting-strings.md)以及转义规则，因为速记语法是字符串。

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

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

等同于以下 JSON 格式的示例。

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

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

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

等同于以下 JSON 格式的示例。

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

------

各逗号分隔的键值对之间不能有空格。下面的示例 Amazon DynamoDB `update-table` 命令包含采用速记语法指定的 `--provisioned-throughput` 选项。

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

该示例等同于以下 JSON 格式的示例。

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

## 将文件作为速记语法值进行加载
<a name="shorthand-files"></a>

当值较大或较复杂时，通常更易以值的形式加载。要将文件作为速记语法值进行加载，格式将略有变化。使用 `@=` 运算符代替 `=` 运算符，而不使用 `key=value`。`@=` 告知 AWS CLI，值应作为文件路径而不是字符串进行读取。在使用以速记语法加载文件时，常见的 [AWS CLI 文件格式设置规则将适用](cli-usage-parameters-file.md)。以下示例显示一个键值对，该键值对为其值加载文件。

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

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

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

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

------

以下示例演示如何为 `aws rolesanywhere create-trust-anchor` 命令加载证书文件。

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

## 将速记语法与 AWS CLI 结合使用
<a name="shorthand-list-parameters"></a>

您可以使用两种方法以列表形式指定输入参数：JSON 或速记。使用 AWS CLI 速记语法，可更方便地传入含有数字、字符串或非嵌套结构的列表。

下面显示了基本格式，列表中的值用单个空格分隔。

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

该示例等同于以下 JSON 格式的示例。

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

如前所述，您可以用速记语法指定数字列表、字符串列表或非嵌套结构的列表。以下是用于 Amazon Elastic Compute Cloud（Amazon EC2）的 `stop-instances` 命令示例，其中，`--instance-ids` 选项的输入参数（字符串列表）采用速记语法指定。

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

该示例等同于以下 JSON 格式的示例。

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

下面的示例显示 Amazon EC2 `create-tags` 命令，该命令针对 `--tags` 选项使用非嵌套结构的列表。`--resources` 选项指定要添加标签的实例的 ID。

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

该示例等同于以下 JSON 格式的示例。JSON 参数分多行编写以便于阅读。

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