

• Amazon Systems Manager CloudWatch 控制面板在 2026 年 4 月 30 日之后将不再可用。客户可以像现在一样继续使用 Amazon CloudWatch 控制台来查看、创建和管理其 Amazon CloudWatch 控制面板。有关更多信息，请参阅 [Amazon CloudWatch 控制面板文档](https://docs.amazonaws.cn/AmazonCloudWatch/latest/monitoring/CloudWatch_Dashboards.html)。

# Amazon Systems Manager 文档
<a name="documents"></a>

Amazon Systems Manager 文档 (SSM document) 定义 Systems Manager 对您的托管实例执行的操作。Systems Manager 包括 100 个预先配置的文档，您可以在运行时通过指定参数进行使用。您可以在 Systems Manager 文档控制台中找到预配置的文档，方法是选择 **Owned by Amazon**（Amazon 所有）选项卡，或者通过在调用 `ListDocuments` API 操作时指定 Amazon `Owner` 筛选条件。文档使用 JavaScript 对象表示法 (JSON) 或 YAML，并包括您指定的步骤和参数。

为增强安全性，从 2025 年 7 月 14 日起，SSM 文档在处理参数时支持环境变量插值。此功能在 2.2 版架构和 3.3.2746.0 或更高版本的 SSM Agent 中可用，可帮助防范命令注入攻击。

要开始使用 SSM 文档，请打开 [Systems Manager 控制台](https://console.amazonaws.cn/systems-manager/documents)。在导航窗格中，选择**文档**。

**重要**  
在 Systems Manager 中，*Amazon 拥有的* SSM 文档是由 Amazon Web Services 自己创建和管理的文档。*Amazon 拥有的*文档在文档名称中包含 `AWS-*` 之类的前缀。文档的所有者被视为 Amazon，而不是 Amazon 内的特定用户账户。这些文档可供所有人公开使用。

## 我的组织如何从 Documents 工具获益？
<a name="ssm-docs-benefits"></a>

Documents（Amazon Systems Manager 中的一项工具）具有以下优点：
+ **文档类别**

  为了帮助您找到所需的文档，请根据要搜索的文档类型选择一个类别。要扩大搜索范围，您可以选择同一文档类型的多个类别。不支持选择不同文档类型的类别。分类仅支持 Amazon 拥有的文档。
+  **文档版本** 

  您可以创建并保存不同版本的文档。您可以为每个文档指定默认版本。文档的默认版本可以更新到较新版本或恢复到较旧版本。当您更改文档的内容时，Systems Manager 将自动递增文档的版本。您可以通过在控制台、Amazon Command Line Interface (Amazon CLI) 命令或 API 调用中指定文档版本来检索或使用任何版本的文档。
+  **根据您的需求自定义文档** 

  如果您要通过文档自定义步骤和操作，可以自行创建文档。系统将文档与您的 Amazon Web Services 账户 一起存储在创建其所在的 Amazon Web Services 区域 中。有关如何创建 SSM 文档的更多信息，请参阅 [创建 SSM 文档内容](documents-creating-content.md)。
+  **标记文档** 

  您可以标记文档，以便根据为其分配的标签快速识别一个或多个文档。例如，您可以为特定环境、部门、用户、组或时间段的文档添加标签。此外，您还可以通过创建一个指定用户或组可访问的标签的 Amazon Identity and Access Management (IAM) policy 来限制对文档的访问。
+  **共享文档** 

  您可以将文档公开，或者将它们与同一 Amazon Web Services 区域 区域中的特定 Amazon Web Services 账户 共享。在账户之间共享文档可能很有用，例如，如果您希望提供给客户或员工的所有 Amazon Elastic Compute Cloud (Amazon EC2) 实例都能够具有相同配置。除了保持实例上的应用程序或补丁的最新状态，您可能还希望限制客户实例执行某些活动。或者，您可能需要确保整个组织的员工账户使用的实例均被授予访问特定内部资源的访问权限。有关更多信息，请参阅 [共享 SSM 文档](documents-ssm-sharing.md)。

## 谁应该使用文档？
<a name="documents-who"></a>
+ 任何希望使用 Systems Manager 工具大规模提高其运营效率、减少与手动干预相关的错误以及缩短解决常见问题的时间的 Amazon 客户。
+ 希望自动执行部署和配置任务的基础设施专家。
+ 想要可靠地解决常见问题、提高故障排除效率和减少重复性操作的管理员。
+ 想要自动执行通常需要手动执行的任务的用户。

## SSM 文档有哪些类型？
<a name="what-are-document-types"></a>

下表介绍了不同类型的 SSM 文档及其使用。


****  

| Type | 一起使用 | Details | 
| --- | --- | --- | 
|  ApplicationConfiguration ApplicationConfigurationSchema  |   [Amazon AppConfig](https://docs.amazonaws.cn/appconfig/latest/userguide/what-is-appconfig.html)   |  Amazon AppConfig 是 Amazon Systems Manager 中的一项工具，可让您创建、管理以及快速部署应用程序配置。您可以通过创建使用 `ApplicationConfiguration` 文档类型的文档，从而将配置数据存储到 SSM 文档中。有关更多信息，请参阅《Amazon AppConfig 用户指南》**中的[自由度配置](https://docs.amazonaws.cn/appconfig/latest/userguide/appconfig-creating-configuration-and-profile.html#free-form-configurations)。 如果在 SSM 文档中创建配置，则必须指定对应的 JSON Schema。该 schema 使用 `ApplicationConfigurationSchema` 文档类型，并且与一组规则类似，它会定义每个应用程序配置设置允许的属性。有关更多信息，请参阅《Amazon AppConfig 用户指南》**中的[关于验证器](https://docs.amazonaws.cn/appconfig/latest/userguide/appconfig-creating-configuration-and-profile-validators.html)。  | 
|  自动化运行手册  |   [自动化](systems-manager-automation.md)   [State Manager](systems-manager-state.md)   [Maintenance Windows](maintenance-windows.md)   |  在执行常规维护和部署任务 – 如创建或更新 Amazon Machine Image (AMI)时使用自动化手册 - 使用自动化运行手册。State Manager 使用自动化运行手册应用配置。这些操作可以在实例生命周期内的任何时刻在一个或多个目标上运行。Maintenance Windows 使用自动化运行手册基于指定的计划执行常规维护和部署任务。 macOS 的 EC2 实例也支持基于 Linux 的操作系统支持的所有自动化运行手册。  | 
|  更改日历文档  |   [Change Calendar](systems-manager-change-calendar.md)   |  Change Calendar 是 Amazon Systems Manager 中的一项工具，使用 `ChangeCalendar` 文档类型。Change Calendar 文档存储日历条目和关联的事件，这些事件可以允许或阻止自动化操作更改您的环境。在 Change Calendar 中，文档以明文格式存储 [iCalendar 2.0](https://icalendar.org/) 数据。 Change Calendar 在 EC2 实例上不支持 macOS。  | 
|  Amazon CloudFormation 模板  |   [Amazon CloudFormation](https://docs.amazonaws.cn/AWSCloudFormation/latest/UserGuide/Welcome.html)   |  Amazon CloudFormation 模板描述您要在 CloudFormation 堆栈中调配的资源。通过将 CloudFormation 模板存储为 Systems Manager 文档，您可以受益于 Systems Manager 文档功能。其中包括创建和比较模板的多个版本，以及与同一 Amazon Web Services 区域 中的其它账号共享模板。 您可以使用 Application Manager（Systems Manager 中的一项工具）创建和编辑 CloudFormation 模板及堆栈。有关更多信息，请参阅 [在 Application Manager 中使用 Amazon CloudFormation 模板和堆栈](application-manager-working-stacks.md)。  | 
|  命令文档  |   [Run Command](run-command.md)   [State Manager](systems-manager-state.md)   [Maintenance Windows](maintenance-windows.md)   |  Run Command 是 Amazon Systems Manager 中的一项工具，使用命令文档运行命令。State Manager是 Amazon Systems Manager 中的一项工具，使用命令文档应用配置。这些操作可以在实例生命周期内的任何时刻在一个或多个目标上运行。Maintenance Windows 是 Amazon Systems Manager 中的一项工具，使用命令文档基于指定的计划应用配置。 大多数命令文档在所有 Linux 和 Systems Manager 所支持的 Windows Server 操作系统上受支持。macOS 的 EC2 实例支持以下命令文档： [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/systems-manager/latest/userguide/documents.html)  | 
|  Amazon Config 一致性包模板  |   [Amazon Config](https://docs.amazonaws.cn/config/latest/developerguide/WhatIsConfig.html)   |  Amazon Config 一致性包模板是 YAML 格式的文档，用于创建包含 Amazon Config 规则（托管或自定义）和修复操作列表的一致性包。 有关更多信息，请参阅[一致性包](https://docs.amazonaws.cn/config/latest/developerguide/conformance-packs.html)。  | 
|  软件包文档  |   [Distributor](distributor.md)   |  在 Distributor（Amazon Systems Manager 中的一项工具）中，软件包用 SSM 文档表示。软件包文档包括附加的 ZIP 存档文件，其中包含要在托管实例上安装的软件或资产。在 Distributor 中创建软件包会创建软件包文档。 Oracle Linux 和 macOS 托管实例上不受支持 Distributor。  | 
|  策略文档  |   [State Manager](systems-manager-state.md)   |  Inventory 是 Amazon Systems Manager 中的一项工具，使用 `AWS-GatherSoftwareInventory` 策略文档和State Manager关联从托管式实例中收集清单数据。在创建您自己的 SSM 文档时，自动化文档和命令文档是在托管实例上实施策略的首选方法。 Systems Manager 清单和 `AWS-GatherSoftwareInventory` 策略文档在 Systems Manager 所支持的所有操作系统上均受支持。  | 
|  事件后分析模板  |   [Incident Manager 事件后分析](https://docs.amazonaws.cn/incident-manager/latest/userguide/analysis.html)   |  Incident Manager 使用事件后分析模板基于 Amazon 运营管理最佳实践创建分析。 使用模板创建分析，您的团队可以使用该分析来了解如何改进事件响应。  | 
|  会话文档  |   [Session Manager](session-manager.md)   |  Session Manager 是 Amazon Systems Manager 中的一项工具，使用会话文档确定要启动哪些类型的会话，例如端口转发会话、运行交互式命令的会话或创建 SSH 隧道的会话。 Systems Manager 支持的所有 Linux 和 Windows Server 操作系统都支持会话文档。macOS 的 EC2 实例支持以下命令文档： [\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/systems-manager/latest/userguide/documents.html)  | 

**SSM 文档配额**  
有关 SSM 服务配额的更多信息，请参阅《Amazon Web Services 一般参考》**中的 [Systems Manager Service Quotas](https://docs.amazonaws.cn/general/latest/gr/ssm.html#limits_ssm)。

**Topics**
+ [

## 我的组织如何从 Documents 工具获益？
](#ssm-docs-benefits)
+ [

## 谁应该使用文档？
](#documents-who)
+ [

## SSM 文档有哪些类型？
](#what-are-document-types)
+ [

# 文档组件
](documents-components.md)
+ [

# 创建 SSM 文档内容
](documents-creating-content.md)
+ [

# 使用文档
](documents-using.md)
+ [

# 参数处理问题的疑难解答
](parameter-troubleshooting.md)

# 文档组件
<a name="documents-components"></a>

本部分包含有关构成 SSM 文档的组件的信息。

**Topics**
+ [

# 架构、功能和示例
](documents-schemas-features.md)
+ [

# 数据元素和参数
](documents-syntax-data-elements-parameters.md)
+ [

# 命令文档插件参考
](documents-command-ssm-plugin-reference.md)

# 架构、功能和示例
<a name="documents-schemas-features"></a>

Amazon Systems Manager (SSM) 文档当前使用以下架构版本。
+ `Command` 型文档可以使用 1.2、2.0 和 2.2 版架构。如果您使用架构 1.2 文档，我们建议您创建使用架构版本 2.2 的文件。
+ `Policy` 型文档必须使用 2.0 版或更高版本的架构。
+ `Automation` 型文档必须使用 0.3 版架构。
+ `Session` 型文档必须使用 1.0 版架构。
+ 您可以创建 JSON 或 YAML 格式的文档。

有关 `Session` 文档架构的更多信息，请参阅 [会话文档架构](session-manager-schema.md)。

通过为 `Command` 和 `Policy` 文档使用最新架构版本，您可以利用以下功能。


**2.2 版架构文档功能**  

| 功能 | Details | 
| --- | --- | 
|  编辑文档  |  文档现在可以更新。如果版本为 1.2，对文档的任何更新都需要另存为其他名称。  | 
|  自动版本控制  |  对文档的任何更新都会创建一个新版本。这不是架构版本，而是文档版本。  | 
|  默认版本  |  如果您拥有某个文档的多个版本，可以指定哪个版本是默认文档。  | 
|  顺序  |  文档中的插件或*步骤*按指定的顺序运行。  | 
|  跨平台支持  |  跨平台支持可让您为同一个 SSM 文档中的不同插件指定不同操作系统。跨平台支持在某个步骤中使用 `precondition` 参数。  | 
| 参数插值 | 插值是指将变量值插入或替换到字符串中。可以将其想象为在使用字符串之前用实际值填充空白。在 SSM 文档上下文中，参数插值允许在执行命令之前将字符串参数插值到环境变量中，从而更好地防范命令注入攻击。设置为 `ENV_VAR` 时，代理会创建一个包含参数值的环境变量 `SSM_parameter-name`。 | 

**注意**  
您必须将实例上的 Amazon Systems Manager SSM Agent 更新到最新版本才能使用新的 Systems Manager 功能和 SSM 文档功能。有关更多信息，请参阅 [使用 Run Command 更新 SSM Agent](run-command-tutorial-update-software.md#rc-console-agentexample)。

下表列出了主要架构版本之间的区别。


****  

| 版本 1.2 | 版本 2.2（最新版本） | Details | 
| --- | --- | --- | 
|  runtimeConfig  |  mainSteps  |  在版本 2.2 中，`mainSteps` 部分替换了 `runtimeConfig` 部分。这些区域有：`mainSteps` 部分允许 Systems Manager 按顺序运行步骤。  | 
|  属性  |  输入  |  在版本 2.2 中，`inputs` 部分替换了 `properties` 部分。`inputs` 部分接受步骤参数。  | 
|   命令  |  runCommand  |  在版本 2.2 中，`inputs` 部分接收 `runCommand` 参数，而不是 `commands` 参数。  | 
|  id  |  action  |  在版本 2.2 中，`Action` 替换了 `ID`。这只是更改了名称。  | 
|  不适用  |  名称  |  在版本 2.2 中，`name` 是用户定义的任意步骤名称。  | 

**使用前提条件参数**  
在 2.2 版或更高版本架构中，您可以使用 `precondition` 参数为每个插件指定目标操作系统验证您在 SSM 文档中定义的输入参数。`precondition` 参数支持引用 SSM 文档的输入参数，`platformType` 使用`Linux` 的值、`MacOS`,和 `Windows`。仅支持 `StringEquals` 运算符。

对于使用 2.2 版或更高版本架构的文档，如果未指定 `precondition`，每个插件将被运行或跳过，具体取决于插件与操作系统的兼容性。插件与操作系统的兼容性在 `precondition` 之前被评估。对于使用 2.0 版或更低版本架构的文档，不兼容的插件将会引发错误。

例如，在 2.2 版架构文档中，如果未指定 `precondition`，将会列出 `aws:runShellScript` 插件，该步骤在 Linux 实例上运行，但系统会在 Windows Server 实例上跳过该步骤，因为 `aws:runShellScript` 与 Windows Server 实例不兼容。但是，对于 2.0 版架构文档，如果您指定 `aws:runShellScript` 插件，然后在 Windows Server 实例上运行文档，执行将会失败。本节稍后将介绍在 SSM 文档中使用前提条件参数的示例。

## 架构版本 2.2
<a name="documents-schema-twox"></a>

**顶级元素**  
以下示例使用 2.2 版架构显示 SSM 文档的顶级元素。

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

```
---
schemaVersion: "2.2"
description: A description of the document.
parameters:
  parameter 1:
    property 1: "value"
    property 2: "value"
  parameter 2:
    property 1: "value"
    property 2: "value"
mainSteps:
  - action: Plugin name
    name: A name for the step.
    inputs:
      input 1: "value"
      input 2: "value"
      input 3: "{{ parameter 1 }}"
```

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

```
{
   "schemaVersion": "2.2",
   "description": "A description of the document.",
   "parameters": {
       "parameter 1": {
           "property 1": "value",
           "property 2": "value"
        },
        "parameter 2":{
           "property 1": "value",
           "property 2": "value"
        } 
    },
   "mainSteps": [
      {
         "action": "Plugin name",
         "name": "A name for the step.",
         "inputs": {
            "input 1": "value",
            "input 2": "value",
            "input 3": "{{ parameter 1 }}"
         }
      }
   ]
}
```

------

**2.2 版架构示例**  
以下示例使用 `aws:runPowerShellScript` 插件在目标实例上运行 PowerShell 命令。

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

```
---
schemaVersion: "2.2"
description: "Example document"
parameters:
  Message:
    type: "String"
    description: "Example parameter"
    default: "Hello World"
    allowedValues: 
    - "Hello World"
mainSteps:
  - action: "aws:runPowerShellScript"
    name: "example"
    inputs:
      timeoutSeconds: '60'
      runCommand:
      - "Write-Output {{Message}}"
```

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

```
{
   "schemaVersion": "2.2",
   "description": "Example document",
   "parameters": {
      "Message": {
         "type": "String",
         "description": "Example parameter",
         "default": "Hello World",
         "allowedValues": ["Hello World"]
      }
   },
   "mainSteps": [
      {
         "action": "aws:runPowerShellScript",
         "name": "example",
         "inputs": {
            "timeoutSeconds": "60",
            "runCommand": [
               "Write-Output {{Message}}"
            ]
         }
      }
   ]
}
```

------

**架构版本 2.2 前提条件参数示例**  
2.2 版架构提供跨平台支持。这意味着在一个 SSM 文档内，您可以为不同的插件指定不同的操作系统。跨平台支持在某个步骤中使用 `precondition` 参数，如下例所示。您也可以使用 `precondition` 参数来验证您在 SSM 文档中定义的输入参数。您可以在以下第二个示例中看到此内容。

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

```
---
schemaVersion: '2.2'
description: cross-platform sample
mainSteps:
- action: aws:runPowerShellScript
  name: PatchWindows
  precondition:
    StringEquals:
    - platformType
    - Windows
  inputs:
    runCommand:
    - cmds
- action: aws:runShellScript
  name: PatchLinux
  precondition:
    StringEquals:
    - platformType
    - Linux
  inputs:
    runCommand:
    - cmds
```

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

```
{
   "schemaVersion": "2.2",
   "description": "cross-platform sample",
   "mainSteps": [
      {
         "action": "aws:runPowerShellScript",
         "name": "PatchWindows",
         "precondition": {
            "StringEquals": [
               "platformType",
               "Windows"
            ]
         },
         "inputs": {
            "runCommand": [
               "cmds"
            ]
         }
      },
      {
         "action": "aws:runShellScript",
         "name": "PatchLinux",
         "precondition": {
            "StringEquals": [
               "platformType",
               "Linux"
            ]
         },
         "inputs": {
            "runCommand": [
               "cmds"
            ]
         }
      }
   ]
}
```

------

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

```
---
schemaVersion: '2.2'
parameters:
  action:
    type: String
    allowedValues:
    - Install
    - Uninstall
  confirmed:
    type: String
    allowedValues:
    - True
    - False
mainSteps:
- action: aws:runShellScript
  name: InstallAwsCLI
  precondition:
    StringEquals:
    - "{{ action }}"
    - "Install"
  inputs:
    runCommand:
    - sudo apt install aws-cli
- action: aws:runShellScript
  name: UninstallAwsCLI
  precondition:
    StringEquals:
    - "{{ action }} {{ confirmed }}"
    - "Uninstall True"
  inputs:
    runCommand:
    - sudo apt remove aws-cli
```

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

```
{
   "schemaVersion": "2.2",
   "parameters": {
      "action": {
         "type": "String",
         "allowedValues": [
            "Install",
            "Uninstall"
         ]
      },
      "confirmed": {
         "type": "String",
         "allowedValues": [
            true,
            false
         ]
      }
   },
   "mainSteps": [
      {
         "action": "aws:runShellScript",
         "name": "InstallAwsCLI",
         "precondition": {
            "StringEquals": [
               "{{ action }}",
               "Install"
            ]
         },
         "inputs": {
            "runCommand": [
               "sudo apt install aws-cli"
            ]
         }
      },
      {
         "action": "aws:runShellScript",
         "name": "UninstallAwsCLI",
         "precondition": {
            "StringEquals": [
               "{{ action }} {{ confirmed }}",
               "Uninstall True"
            ]
         },
         "inputs": {
            "runCommand": [
               "sudo apt remove aws-cli"
            ]
         }
      }
   ]
}
```

------

**2.2 版架构插值示例（3.3.2746.0 之前的 SSM Agent 版本）**  
在 3.3.2746.0 之前的 SSM Agent 版本中，代理会忽略 `interpolationType` 参数，转而执行原始字符串的替换。若要显式引用 `SSM_parameter-name`，则必须明确设置此项。以下 Linux 示例显式引用了环境变量 `SSM_Message`。

```
{
    "schemaVersion": "2.2",
    "description": "An example document",
    "parameters": {
        "Message": {
            "type": "String",
            "description": "Message to be printed",
            "default": "Hello",
            "interpolationType" : "ENV_VAR",
	     "allowedPattern: "^[^"]*$"

        }
    },
    "mainSteps": [{
        "action": "aws:runShellScript",
        "name": "printMessage",
        "inputs": {
            "runCommand": [
              "if [ -z "${SSM_Message+x}" ]; then",
              "    export SSM_Message=\"{{Message}}\"",
              "fi",
              "",
              "echo $SSM_Message"
            ]
        }
    }
}
```

**注意**  
如果 SSM 文档未使用以下双大括号，则 `allowedPattern` 在技术上是不必要的：`{{ }}`

**2.2 版架构 State Manager 示例**  
您可以将以下 SSM 文档用于State Manager（Systems Manager 中的一项工具）来下载并安装 ClamAV 防病毒软件。State Manager会强制实施特定配置，这意味着每次运行State Manager关联时，系统都会检查是否安装了 ClamAV 软件。如果未安装，State Manager 会重新运行本文档。

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

```
---
schemaVersion: '2.2'
description: State Manager Bootstrap Example
parameters: {}
mainSteps:
- action: aws:runShellScript
  name: configureServer
  inputs:
    runCommand:
    - sudo yum install -y httpd24
    - sudo yum --enablerepo=epel install -y clamav
```

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

```
{
   "schemaVersion": "2.2",
   "description": "State Manager Bootstrap Example",
   "parameters": {},
   "mainSteps": [
      {
         "action": "aws:runShellScript",
         "name": "configureServer",
         "inputs": {
            "runCommand": [
               "sudo yum install -y httpd24",
               "sudo yum --enablerepo=epel install -y clamav"
            ]
         }
      }
   ]
}
```

------

**2.2 版架构清单示例**  
您可以将以下 SSM 文档用于 State Manager,以收集关于实例的清单元数据。

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

```
---
schemaVersion: '2.2'
description: Software Inventory Policy Document.
parameters:
  applications:
    type: String
    default: Enabled
    description: "(Optional) Collect data for installed applications."
    allowedValues:
    - Enabled
    - Disabled
  awsComponents:
    type: String
    default: Enabled
    description: "(Optional) Collect data for Amazon Components like amazon-ssm-agent."
    allowedValues:
    - Enabled
    - Disabled
  networkConfig:
    type: String
    default: Enabled
    description: "(Optional) Collect data for Network configurations."
    allowedValues:
    - Enabled
    - Disabled
  windowsUpdates:
    type: String
    default: Enabled
    description: "(Optional) Collect data for all Windows Updates."
    allowedValues:
    - Enabled
    - Disabled
  instanceDetailedInformation:
    type: String
    default: Enabled
    description: "(Optional) Collect additional information about the instance, including
      the CPU model, speed, and the number of cores, to name a few."
    allowedValues:
    - Enabled
    - Disabled
  customInventory:
    type: String
    default: Enabled
    description: "(Optional) Collect data for custom inventory."
    allowedValues:
    - Enabled
    - Disabled
mainSteps:
- action: aws:softwareInventory
  name: collectSoftwareInventoryItems
  inputs:
    applications: "{{ applications }}"
    awsComponents: "{{ awsComponents }}"
    networkConfig: "{{ networkConfig }}"
    windowsUpdates: "{{ windowsUpdates }}"
    instanceDetailedInformation: "{{ instanceDetailedInformation }}"
    customInventory: "{{ customInventory }}"
```

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

```
{
   "schemaVersion": "2.2",
   "description": "Software Inventory Policy Document.",
   "parameters": {
      "applications": {
         "type": "String",
         "default": "Enabled",
         "description": "(Optional) Collect data for installed applications.",
         "allowedValues": [
            "Enabled",
            "Disabled"
         ]
      },
      "awsComponents": {
         "type": "String",
         "default": "Enabled",
         "description": "(Optional) Collect data for Amazon Components like amazon-ssm-agent.",
         "allowedValues": [
            "Enabled",
            "Disabled"
         ]
      },
      "networkConfig": {
         "type": "String",
         "default": "Enabled",
         "description": "(Optional) Collect data for Network configurations.",
         "allowedValues": [
            "Enabled",
            "Disabled"
         ]
      },
      "windowsUpdates": {
         "type": "String",
         "default": "Enabled",
         "description": "(Optional) Collect data for all Windows Updates.",
         "allowedValues": [
            "Enabled",
            "Disabled"
         ]
      },
      "instanceDetailedInformation": {
         "type": "String",
         "default": "Enabled",
         "description": "(Optional) Collect additional information about the instance, including\nthe CPU model, speed, and the number of cores, to name a few.",
         "allowedValues": [
            "Enabled",
            "Disabled"
         ]
      },
      "customInventory": {
         "type": "String",
         "default": "Enabled",
         "description": "(Optional) Collect data for custom inventory.",
         "allowedValues": [
            "Enabled",
            "Disabled"
         ]
      }
   },
   "mainSteps": [
      {
         "action": "aws:softwareInventory",
         "name": "collectSoftwareInventoryItems",
         "inputs": {
            "applications": "{{ applications }}",
            "awsComponents": "{{ awsComponents }}",
            "networkConfig": "{{ networkConfig }}",
            "windowsUpdates": "{{ windowsUpdates }}",
            "instanceDetailedInformation": "{{ instanceDetailedInformation }}",
            "customInventory": "{{ customInventory }}"
         }
      }
   ]
}
```

------

**2.2 版架构 `AWS-ConfigureAWSPackage` 示例**  
以下示例显示 `AWS-ConfigureAWSPackage` 文档。这些区域有：`mainSteps`部分包括`aws:configurePackage`插件`action`步骤。

**注意**  
在 Linux 操作系统上，仅支持 `AmazonCloudWatchAgent` 和 `AWSSupport-EC2Rescue` 软件包。

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

```
---
schemaVersion: '2.2'
description: 'Install or uninstall the latest version or specified version of an Amazon
  package. Available packages include the following: AWSPVDriver, AwsEnaNetworkDriver,
  AwsVssComponents, and AmazonCloudWatchAgent, and AWSSupport-EC2Rescue.'
parameters:
  action:
    description: "(Required) Specify whether or not to install or uninstall the package."
    type: String
    allowedValues:
    - Install
    - Uninstall
  name:
    description: "(Required) The package to install/uninstall."
    type: String
    allowedPattern: "^arn:[a-z0-9][-.a-z0-9]{0,62}:[a-z0-9][-.a-z0-9]{0,62}:([a-z0-9][-.a-z0-9]{0,62})?:([a-z0-9][-.a-z0-9]{0,62})?:package\\/[a-zA-Z][a-zA-Z0-9\\-_]{0,39}$|^[a-zA-Z][a-zA-Z0-9\\-_]{0,39}$"
  version:
    type: String
    description: "(Optional) A specific version of the package to install or uninstall."
mainSteps:
- action: aws:configurePackage
  name: configurePackage
  inputs:
    name: "{{ name }}"
    action: "{{ action }}"
    version: "{{ version }}"
```

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

```
{
   "schemaVersion": "2.2",
   "description": "Install or uninstall the latest version or specified version of an Amazon package. Available packages include the following: AWSPVDriver, AwsEnaNetworkDriver, AwsVssComponents, and AmazonCloudWatchAgent, and AWSSupport-EC2Rescue.",
   "parameters": {
      "action": {
         "description":"(Required) Specify whether or not to install or uninstall the package.",
         "type":"String",
         "allowedValues":[
            "Install",
            "Uninstall"
         ]
      },
      "name": {
         "description": "(Required) The package to install/uninstall.",
         "type": "String",
         "allowedPattern": "^arn:[a-z0-9][-.a-z0-9]{0,62}:[a-z0-9][-.a-z0-9]{0,62}:([a-z0-9][-.a-z0-9]{0,62})?:([a-z0-9][-.a-z0-9]{0,62})?:package\\/[a-zA-Z][a-zA-Z0-9\\-_]{0,39}$|^[a-zA-Z][a-zA-Z0-9\\-_]{0,39}$"
      },
      "version": {
         "type": "String",
         "description": "(Optional) A specific version of the package to install or uninstall."
      }
   },
   "mainSteps":[
      {
         "action": "aws:configurePackage",
         "name": "configurePackage",
         "inputs": {
            "name": "{{ name }}",
            "action": "{{ action }}",
            "version": "{{ version }}"
         }
      }
   ]
}
```

------

## 架构版本 1.2
<a name="documents-schema-onex"></a>

以下示例显示 1.2 版架构文档的顶级元素。

```
{
   "schemaVersion":"1.2",
   "description":"A description of the SSM document.",
   "parameters":{
      "parameter 1":{
         "one or more parameter properties"
      },
      "parameter 2":{
         "one or more parameter properties"
      },
      "parameter 3":{
         "one or more parameter properties"
      }
   },
   "runtimeConfig":{
      "plugin 1":{
         "properties":[
            {
               "one or more plugin properties"
            }
         ]
      }
   }
}
```

**1.2 版架构 `aws:runShellScript` 示例**  
以下示例显示 `AWS-RunShellScript` SSM 文档。**runtimeConfig** 部分包含 `aws:runShellScript` 插件。

```
{
    "schemaVersion":"1.2",
    "description":"Run a shell script or specify the commands to run.",
    "parameters":{
        "commands":{
            "type":"StringList",
            "description":"(Required) Specify a shell script or a command to run.",
            "minItems":1,
            "displayType":"textarea"
        },
        "workingDirectory":{
            "type":"String",
            "default":"",
            "description":"(Optional) The path to the working directory on your instance.",
            "maxChars":4096
        },
        "executionTimeout":{
            "type":"String",
            "default":"3600",
            "description":"(Optional) The time in seconds for a command to complete before it is considered to have failed. Default is 3600 (1 hour). Maximum is 172800 (48 hours).",
            "allowedPattern":"([1-9][0-9]{0,3})|(1[0-9]{1,4})|(2[0-7][0-9]{1,3})|(28[0-7][0-9]{1,2})|(28800)"
        }
    },
    "runtimeConfig":{
        "aws:runShellScript":{
            "properties":[
                {
                    "id":"0.aws:runShellScript",
                    "runCommand":"{{ commands }}",
                    "workingDirectory":"{{ workingDirectory }}",
                    "timeoutSeconds":"{{ executionTimeout }}"
                }
            ]
        }
    }
}
```

## 架构版本 0.3
<a name="automation-doc-syntax-examples"></a>

**顶级元素**  
以下示例显示 JSON 格式的架构 0.3 版自动化运行手册的顶级元素。

```
{
    "description": "document-description",
    "schemaVersion": "0.3",
    "assumeRole": "{{assumeRole}}",
    "parameters": {
        "parameter1": {
            "type": "String",
            "description": "parameter-1-description",
            "default": ""
        },
        "parameter2": {
            "type": "String",
            "description": "parameter-2-description",
            "default": ""
        }
    },
    "variables": {
        "variable1": {
            "type": "StringMap",
            "description": "variable-1-description",
            "default": {}
        },
        "variable2": {
            "type": "String",
            "description": "variable-2-description",
            "default": "default-value"
        }
    },
    "mainSteps": [
        {
            "name": "myStepName",
            "action": "action-name",
            "maxAttempts": 1,
            "inputs": {
                "Handler": "python-only-handler-name",
                "Runtime": "runtime-name",
                "Attachment": "script-or-zip-name"
            },
            "outputs": {
                "Name": "output-name",
                "Selector": "selector.value",
                "Type": "data-type"
            }
        }
    ],
    "files": {
        "script-or-zip-name": {
            "checksums": {
                "sha256": "checksum"
            },
            "size": 1234
        }
    }
}
```

**YAML 自动化运行手册示例**  
以下示例显示了 YAML 格式的自动化运行手册的内容。0.3 版文档架构的此工作示例还演示了如何使用 Markdown 格式化文档描述。

```
description: >-
  ##Title: LaunchInstanceAndCheckState

  -----

  **Purpose**: This Automation runbook first launches an EC2 instance
  using the AMI ID provided in the parameter ```imageId```. The second step of
  this document continuously checks the instance status check value for the
  launched instance until the status ```ok``` is returned.


  ##Parameters:

  -----

  Name | Type | Description | Default Value

  ------------- | ------------- | ------------- | -------------

  assumeRole | String | (Optional) The ARN of the role that allows Automation to
  perform the actions on your behalf. | -

  imageId  | String | (Optional) The AMI ID to use for launching the instance.
  The default value uses the latest Amazon Linux AMI ID available. | {{
  ssm:/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-6.1-x86_64 }}
schemaVersion: '0.3'
assumeRole: 'arn:aws:iam::111122223333::role/AutomationServiceRole'
parameters:
  imageId:
    type: String
    default: '{{ ssm:/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-6.1-x86_64 }}'
    description: >-
      (Optional) The AMI ID to use for launching the instance. The default value
      uses the latest released Amazon Linux AMI ID.
  tagValue:
    type: String
    default: ' LaunchedBySsmAutomation'
    description: >-
      (Optional) The tag value to add to the instance. The default value is
      LaunchedBySsmAutomation.
  instanceType:
    type: String
    default: t2.micro
    description: >-
      (Optional) The instance type to use for the instance. The default value is
      t2.micro.
mainSteps:
  - name: LaunchEc2Instance
    action: 'aws:executeScript'
    outputs:
      - Name: payload
        Selector: $.Payload
        Type: StringMap
    inputs:
      Runtime: python3.11
      Handler: launch_instance
      Script: ''
      InputPayload:
        image_id: '{{ imageId }}'
        tag_value: '{{ tagValue }}'
        instance_type: '{{ instanceType }}'
      Attachment: launch.py
    description: >-
      **About This Step**


      This step first launches an EC2 instance using the ```aws:executeScript```
      action and the provided python script.
  - name: WaitForInstanceStatusOk
    action: 'aws:executeScript'
    inputs:
      Runtime: python3.11
      Handler: poll_instance
      Script: |-
        def poll_instance(events, context):
          import boto3
          import time

          ec2 = boto3.client('ec2')

          instance_id = events['InstanceId']

          print('[INFO] Waiting for instance status check to report ok', instance_id)

          instance_status = "null"

          while True:
            res = ec2.describe_instance_status(InstanceIds=[instance_id])

            if len(res['InstanceStatuses']) == 0:
              print("Instance status information is not available yet")
              time.sleep(5)
              continue

            instance_status = res['InstanceStatuses'][0]['InstanceStatus']['Status']

            print('[INFO] Polling to get status of the instance', instance_status)

            if instance_status == 'ok':
              break

            time.sleep(10)

          return {'Status': instance_status, 'InstanceId': instance_id}
      InputPayload: '{{ LaunchEc2Instance.payload }}'
    description: >-
      **About This Step**


      The python script continuously polls the instance status check value for
      the instance launched in Step 1 until the ```ok``` status is returned.
files:
  launch.py:
    checksums:
      sha256: 18871b1311b295c43d0f...[truncated]...772da97b67e99d84d342ef4aEXAMPLE
```

## 安全处理参数示例
<a name="secure-parameter-examples"></a>

以下示例演示使用环境变量 `interpolationType` 安全处理参数。

### 基本安全命令执行
<a name="basic-secure-command"></a>

本示例说明如何安全处理命令参数：

**注意**  
在不使用以下双大括号的 SSM 文档中，`allowedPattern` 在技术上是不必要的：`{{ }}`

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

```
---

schemaVersion: '2.2'
description: An example document.
parameters:
  Message:
    type: String
    description: "Message to be printed"
    default: Hello
    interpolationType: ENV_VAR
    allowedPattern: "^[^"]*$"
mainSteps:
  - action: aws:runShellScript
    name: printMessage
    precondition:
      StringEquals:
        - platformType
        - Linux
    inputs:
      runCommand:
        - echo {{Message}}
```

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

```
{
    "schemaVersion": "2.2",
    "description": "An example document.",
    "parameters": {
        "Message": {
            "type": "String",
            "description": "Message to be printed",
            "default": "Hello",
            "interpolationType": "ENV_VAR",
            "allowedPattern": "^[^"]*$"
        }
    },
    "mainSteps": [{
        "action": "aws:runShellScript",
        "name": "printMessage",
        "precondition": {
           "StringEquals": ["platformType", "Linux"]
        },
        "inputs": {
            "runCommand": [
              "echo {{Message}}"
            ]
        }
    }]
}
```

------

### 在解释性语言中使用参数
<a name="interpreted-language-example"></a>

本示例演示在 Python 中安全处理参数：

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

```
---
schemaVersion: '2.2'
description: 'Secure Python script execution'
parameters:
  inputData:
    type: String
    description: 'Input data for processing'
    interpolationType: 'ENV_VAR'
mainSteps:
  - action: aws:runPowerShellScript
    name: runPython
    inputs:
      runCommand:
        - |
          python3 -c '
          import os
          import json
          
          # Safely access parameter through environment variable
          input_data = os.environ.get("SSM_inputData", "")
          
          # Process the data
          try:
              processed_data = json.loads(input_data)
              print(f"Successfully processed: {processed_data}")
          except json.JSONDecodeError:
              print("Invalid JSON input")
          '
```

------

### 向后兼容性示例
<a name="backwards-compatibility-example"></a>

本示例展示如何安全处理参数，同时保持向后兼容性：

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

```
---
schemaVersion: '2.2'
description: 'Backwards compatible secure parameter handling'
parameters:
  userInput:
    type: String
    description: 'User input to process'
    interpolationType: 'ENV_VAR'
    allowedPattern: '^[^"]*$'

mainSteps:
  - action: aws:runShellScript
    name: processInput
    inputs:
      runCommand:
        - |
          # Handle both modern and legacy agent versions
          if [ -z "${SSM_userInput+x}" ]; then
              # Legacy agent - fall back to direct parameter reference
              export SSM_userInput="{{userInput}}"
          fi
          
          # Process the input securely
          echo "Processing input: $SSM_userInput"
```

------

**注意**  
在不使用以下双大括号的 SSM 文档中，`allowedPattern` 在技术上是不必要的：`{{ }}`

## 参数安全的最佳实践
<a name="parameter-security-best-practices"></a>

在处理 SSM 文档中的参数时，请遵循以下最佳实践：
+ **使用环境变量插值**：即将用于命令执行的字符串参数始终使用 `interpolationType: "ENV_VAR"`。
+ **实现输入验证**：使用 `allowedPattern` 将参数值限制为安全模式。
+ **处理遗留系统**：为不支持环境变量插值的旧版 SSM Agent 添加回退逻辑。
+ **转义特殊字符**：在命令中使用参数值时，请对特殊字符进行恰当转义以防止被 shell 解释。
+ **限制参数范围**：为用例使用尽可能严格的参数模式。

# 数据元素和参数
<a name="documents-syntax-data-elements-parameters"></a>

本主题介绍 SSM 文档中使用的数据元素。用于创建文档的架构版本定义了文档接受的语法和数据元素。我们建议您对命令文档使用架构版本 2.2 或更高版本。自动化运行手册使用架构版本 0.3。此外，自动化运行手册还支持使用 Markdown（一种标记语言），它允许您为文档和文档中的各个步骤添加 Wiki 样式的描述。有关使用 Markdown 的详细信息，请参阅*《Amazon Web Services 管理控制台 入门指南》*中的[在控制台中使用 Markdown](https://docs.amazonaws.cn/general/latest/gr/aws-markdown.html)。

以下部分介绍了 SSM 文档中可以包含的数据元素。

## 顶级数据元素
<a name="top-level"></a>

**schemaVersion**  
要使用的架构版本。  
类型：版本  
是否必需：是

**描述**  
您提供的描述文档目的的信息。您还可以使用此字段来指定参数是否需要一个值才能运行文档，或者为参数提供值是否为可选项。可在本主题的所有示例中查看必需参数和可选参数。  
类型：字符串  
必需：否

**参数**  
定义文档接受的参数的结构。  
为增强处理字符串参数的安全性，可通过指定 `interpolationType` 属性来使用环境变量插值。设置为 `ENV_VAR` 时，系统会创建一个包含参数值的环境变量 `SSM_parameter-name`。  
下面是一个使用环境变量 `interpolationType` 的参数的示例：  

```
{
    "schemaVersion": "2.2",
    "description": "An example document.",
    "parameters": {
        "Message": {
            "type": "String",
            "description": "Message to be printed",
            "default": "Hello",
            "interpolationType" : "ENV_VAR",
            "allowedPattern": "^[^"]*$"

        }
    },
    "mainSteps": [{
        "action": "aws:runShellScript",
        "name": "printMessage",
        "precondition" : {
           "StringEquals" : ["platformType", "Linux"]
        },
        "inputs": {
            "runCommand": [
              "echo {{Message}}"
            ]
        }
    }
}
```
在不使用以下双大括号的 SSM 文档中，`allowedPattern` 在技术上是不必要的：`{{ }}`
对于经常使用的参数，建议将这些参数存储在 Parameter Store（Amazon Systems Manager 中的一项工具）中。然后，可以在文档中定义参数，并引用 Parameter Store 参数作为默认值。要引用 Parameter Store 参数，请使用以下语法。  

```
{{ssm:parameter-name}}
```
可以使用参数通过与任何其他文档参数相同的方式引用 Parameter Store 参数。在以下示例中，`commands` 参数的默认值是 Parameter Store 参数 `myShellCommands`。如果将 `commands` 参数指定为 `runCommand` 字符串，文档将运行存储在 `myShellCommands` 参数中的命令。  

```
---
schemaVersion: '2.2'
description: runShellScript with command strings stored as Parameter Store parameter
parameters:
  commands:
    type: StringList
    description: "(Required) The commands to run on the instance."
    default: ["{{ ssm:myShellCommands }}"],
            interpolationType : 'ENV_VAR'
            allowedPattern: '^[^"]*$'

mainSteps:
- action: aws:runShellScript
  name: runShellScriptDefaultParams
  inputs:
    runCommand:"{{ commands }}"
```

```
{
    "schemaVersion": "2.2",
    "description": "runShellScript with command strings stored as Parameter Store parameter",
    "parameters": {
      "commands": {
        "type": "StringList",
        "description": "(Required) The commands to run on the instance.",
        "default": ["{{ ssm:myShellCommands }}"],
        "interpolationType" : "ENV_VAR"
      }
    },
    "mainSteps": [
      {
        "action": "aws:runShellScript",
        "name": "runShellScriptDefaultParams",
        "inputs": {
            "runCommand": [
              "{{ commands }}"
          ]
        }
      }
    ]
  }
```
您可以在文档的 `parameters` 部分引用 `String` 和 `StringList` Parameter Store 参数。您不能引用 `SecureString` Parameter Store 参数。
有关 Parameter Store 的更多信息，请参阅 [Amazon Systems Manager Parameter Store](systems-manager-parameter-store.md)。  
类型：结构  
`parameters` 结构接受以下字段和值：  
+ `type`：(必需) 允许的值包括：`String`、`StringList`、`Integer`、`Boolean`、`MapList` 和 `StringMap`。要查看每种类型的示例，请参阅下一节中的 [文档参数 `type` 示例](#top-level-properties-type)。
**注意**  
命令类型文档仅支持 `String` 和 `StringList` 参数类型。
+ `description`：(可选) 关于参数的描述。
+ `default`：（可选）参数的默认值或对 Parameter Store 中参数的引用。
+ `allowedValues`：（可选）参数允许的值数组。定义参数的允许值将验证用户输入。如果用户输入了不允许的值，则执行将无法启动。

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

  ```
  DirectoryType:
    type: String
    description: "(Required) The directory type to launch."
    default: AwsMad
    allowedValues:
    - AdConnector
    - AwsMad
    - SimpleAd
  ```

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

  ```
  "DirectoryType": {
    "type": "String",
    "description": "(Required) The directory type to launch.",
    "default": "AwsMad",
    "allowedValues": [
      "AdConnector",
      "AwsMad",
      "SimpleAd"
    ]
  }
  ```

------
+ `allowedPattern`：（可选）验证用户输入是否与参数的定义模式匹配的正则表达式。如果用户输入与允许的模式不匹配，则执行无法启动。
**注意**  
Systems Manager 会执行两次 `allowedPattern` 验证。第一次验证是在您使用文档时利用 [Java 正则表达式库](https://docs.oracle.com/javase/8/docs/api/java/util/regex/package-summary.html)在 API 级别进行。第二次验证是在处理文档之前通过使用 [GO 正则表达式库](https://pkg.go.dev/regexp)在 SSM Agent 上进行。

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

  ```
  InstanceId:
    type: String
    description: "(Required) The instance ID to target."
    allowedPattern: "^i-(?:[a-f0-9]{8}|[a-f0-9]{17})$"
    default: ''
  ```

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

  ```
  "InstanceId": {
    "type": "String",
    "description": "(Required) The instance ID to target.",
    "allowedPattern": "^i-(?:[a-f0-9]{8}|[a-f0-9]{17})$",
    "default": ""
  }
  ```

------
+ `displayType`：（可选）用于在 Amazon Web Services 管理控制台 中显示 `textfield` 或 `textarea`。`textfield` 是单行文本框。`textarea` 是多行文本区域。
+ `minItems`：(可选) 允许的最小项目数。
+ `maxItems`：(可选) 允许的最大项目数。
+ `minChars`：(可选) 允许的最小参数字符数。
+ `maxChars`：(可选) 允许的最大参数字符数。
+ `interpolationType`：（可选）定义在执行命令之前如何处理参数值。如果设置为 `ENV_VAR`，则可以将参数值用作名为 `SSM_parameter-name` 的环境变量。此功能通过将参数值视为文字字符串，从而帮助防范命令注入攻击。

  类型：字符串

  有效值：`ENV_VAR`
必需：否

**变量**  
（仅限架构版本 0.3）您可以在自动化运行手册的整个步骤中引用或更新的值。变量与参数类似，但在重要方面有所区别。参数值在运行手册的上下文中是静态的，但是变量的值可以在运行手册的上下文中更改。更新变量的值时，数据类型必须与定义的数据类型相匹配。有关更新自动化中的变量值的信息，请参阅 [`aws:updateVariable` – 更新运行手册变量的值](automation-action-update-variable.md)  
类型：Boolean \$1 Integer \$1 MapList \$1 String \$1 StringList \$1 StringMap  
必需：否  

```
variables:
    payload:
        type: StringMap
        default: "{}"
```

```
{
    "variables": [
        "payload": {
            "type": "StringMap",
            "default": "{}"
        }
    ]
}
```

**runtimeConfig**  
(仅限 1.2 版架构) 由一个或多个 Systems Manager 插件应用的实例的配置。不保证插件按顺序运行。  
类型：Dictionary<string,PluginConfiguration>  
必需：否

**mainSteps**  
（仅架构版本 0.3、2.0 和 2.2）可以包含多个步骤（插件）的对象。插件在步骤内定义。步骤按文档中列出的先后顺序运行。  
类型：Dictionary<string,PluginConfiguration>  
是否必需：是

**输出**  
（仅架构版本 0.3）通过执行本文档而生成的可用于其他进程的数据。例如，如果文档创建新的 AMI，您可以指定 “CreateImage.ImageId” 作为输出值，然后使用该输出以在后续自动化执行中创建新的实例。有关输出的更多信息，请参阅 [使用操作输出作为输入](automation-action-outputs-inputs.md)。  
类型：Dictionary<string,OutputConfiguration>  
必需：否

**文件**  
（仅架构版本 0.3）附加到文档并在自动化执行期间运行的脚本文件（及其校验和）。仅适用于包含 `aws:executeScript` 操作且已在一个或多个步骤中指定附件的文档。  
要了解自动化运行手册支持的运行时，请参阅 [`aws:executeScript` - 运行脚本](automation-action-executeScript.md)。有关在自动化运行手册中包含脚本的更多信息，请参阅 [在运行手册中使用脚本](automation-document-script-considerations.md) 和 [自动化运行手册的视觉对象设计体验](automation-visual-designer.md)。  
使用附件创建自动化运行手册时，可以使用 `--attachments` 选项（对于 Amazon CLI）或 `Attachments`（对于 API 和开发工具包）指定附件文件。您可以为存储在 Amazon Simple Storage Service（Amazon S3）存储桶中的 SSM 文档和文件指定文件位置。有关更多信息，请参阅 Amazon Systems Manager API 参考中的[附件](https://docs.amazonaws.cn/systems-manager/latest/APIReference/API_CreateDocument.html#systemsmanager-CreateDocument-request-Attachments)。  

```
---
files:
  launch.py:
    checksums:
      sha256: 18871b1311b295c43d0f...[truncated]...772da97b67e99d84d342ef4aEXAMPLE
```

```
"files": {
    "launch.py": {
        "checksums": {
            "sha256": "18871b1311b295c43d0f...[truncated]...772da97b67e99d84d342ef4aEXAMPLE"
        }
    }
}
```
类型：Dictionary<string,FilesConfiguration>  
必需：否

## 文档参数 `type` 示例
<a name="top-level-properties-type"></a>

SSM 文档中的参数类型是静态的。这意味着参数类型在定义后无法更改。将参数用于 SSM 文档插件时，不能在插件的输入中动态更改参数的类型。例如，您不能在 `aws:runShellScript` 插件的 `runCommand` 输入中引用 `Integer` 参数，因为此输入接受字符串或字符串列表。要将参数用于插件输入，参数类型必须与接受的类型匹配。例如，您必须为`aws:updateSsmAgent` 插件的 `allowDowngrade` 输入指定 `Boolean` 类型参数。如果参数类型与插件的输入类型不匹配，则 SSM 文档无法验证，并且系统不会创建文档。在其他插件或 Amazon Systems Manager 自动化操作的输入中使用下游参数时也是如此。例如，您不能引用 `aws:runDocument` 插件的 `documentParameters` 输入内的 `StringList` 参数。`documentParameters` 输入接受字符串映射，即使下游 SSM 文档参数类型是 `StringList` 参数并与您要引用的参数匹配。

将参数用于自动化操作时，大多数情况下创建 SSM 文档时不会验证参数类型。只有在使用 `aws:runCommand` 操作的情况下，才会在创建 SSM 文档时验证参数类型。在所有其他情况下，在运行操作之前验证该操作的输入时，会在自动化执行期间进行参数验证。例如，如果输入参数为 `String` 并将其引用为 `aws:runInstances` 操作 `MaxInstanceCount` 输入的值，则会创建 SSM 文档。但是，在运行该文档期间，验证 `aws:runInstances` 操作时自动化将失败，因为 `MaxInstanceCount` 输入需要 `Integer`。

下面是每个参数的示例 `type`。

字符串  
使用引号括起来的零个或多个 Unicode 字符序列。例如，"i-1234567890abcdef0"。使用反斜杠转义。  
字符串参数可包括一个值为 `ENV_VAR` 的可选 `interpolationType` 字段，以启用环境变量插值增强安全性。  

```
---
InstanceId:
  type: String
  description: "(Optional) The target EC2 instance ID."
  interpolationType: ENV_VAR
```

```
"InstanceId":{
  "type":"String",
  "description":"(Optional) The target EC2 instance ID.",
  "interpolationType": "ENV_VAR"
}
```

StringList  
以逗号分隔的字符串项目列表。例如，["cd \$1", "pwd"]。  

```
---
commands:
  type: StringList
  description: "(Required) Specify a shell script or a command to run."
  default: ""
  minItems: 1
  displayType: textarea
```

```
"commands":{
  "type":"StringList",
  "description":"(Required) Specify a shell script or a command to run.",
  "minItems":1,
  "displayType":"textarea"
}
```

布尔值  
仅接受 `true` 或 `false`。不接受 "true" 或 0。  

```
---
canRun:
  type: Boolean
  description: ''
  default: true
```

```
"canRun": {
  "type": "Boolean",
  "description": "",
  "default": true
}
```

整数  
整数。不接受小数（例如 3.14159）或使用引号的数字（例如 "3"）。  

```
---
timeout:
  type: Integer
  description: The type of action to perform.
  default: 100
```

```
"timeout": {
  "type": "Integer",
  "description": "The type of action to perform.",
  "default": 100    
}
```

StringMap  
键到值的映射。密钥和值必须是字符串。例如，\$1"Env": "Prod"\$1。  

```
---
notificationConfig:
  type: StringMap
  description: The configuration for events to be notified about
  default:
    NotificationType: 'Command'
    NotificationEvents:
    - 'Failed'
    NotificationArn: "$dependency.topicArn"
  maxChars: 150
```

```
"notificationConfig" : {
  "type" : "StringMap",
  "description" : "The configuration for events to be notified about",
  "default" : {
    "NotificationType" : "Command",
    "NotificationEvents" : ["Failed"],
    "NotificationArn" : "$dependency.topicArn"
  },
  "maxChars" : 150
}
```

MapList  
StringMap 对象的列表。  

```
blockDeviceMappings:
  type: MapList
  description: The mappings for the create image inputs
  default:
  - DeviceName: "/dev/sda1"
    Ebs:
      VolumeSize: "50"
  - DeviceName: "/dev/sdm"
    Ebs:
      VolumeSize: "100"
  maxItems: 2
```

```
"blockDeviceMappings":{
  "type":"MapList",
  "description":"The mappings for the create image inputs",
  "default":[
    {
      "DeviceName":"/dev/sda1",
      "Ebs":{
        "VolumeSize":"50"
      }
    },
    {
      "DeviceName":"/dev/sdm",
      "Ebs":{
        "VolumeSize":"100"
      }
    }
  ],
  "maxItems":2
}
```

## 查看 SSM 命令文档内容
<a name="viewing-ssm-document-content"></a>

要预览需要的和可选参数 Amazon Systems Manager(SSM) 命令文档，除了文档运行的操作外，您还可以在 Systems Manager 控制台中查看此文档的内容。

**查看 SSM 命令文档内容**

1. 访问 [https://console.aws.amazon.com/systems-manager/](https://console.amazonaws.cn/systems-manager/)，打开 Amazon Systems Manager 控制台。

1. 在导航窗格中，选择**文档**。

1. 在搜索框中，选择**文档类型**，然后选择**命令**。

1. 选择文档的名称，然后选择**内容**选项卡。

1. 在内容字段中，查看文档的可用参数和操作步骤。

# 命令文档插件参考
<a name="documents-command-ssm-plugin-reference"></a>

此参考介绍可在 Amazon Systems Manager (SSM) 命令类型文档中指定的插件。这些插件不能在使自动化操作的 SSM 自动化运行手册中使用。有关 Amazon Systems Manager 自动化操作的信息，请参阅 [Systems Manager 自动化操作参考](automation-actions.md)。

Systems Manager 通过读取 SSM 文档的内容确定在托管实例上执行的操作。每个文档都包含代码执行部分。根据文档的架构版本，此代码执行部分可能包含一个或多个插件或步骤。为了便于理解本帮助主题，我们将这些插件和步骤都称为*插件*。本部分包含有关每个 Systems Manager 插件的信息。有关文档的详细信息（包括有关创建文档和架构版本之间的差异的信息），请参阅 [Amazon Systems Manager 文档](documents.md)。

对于接受字符串参数（例如 `aws:runShellScript` 和 `aws:runPowerShellScript`）的插件，可以使用 `interpolationType` 参数增强安全性，方法是将参数输入视为字符串文本值，而非可能的可执行命令。例如：

```
{
    "schemaVersion": "2.2",
    "description": "runShellScript with command strings stored as Parameter Store parameter",
    "parameters": {
      "commands": {
        "type": "StringList",
        "description": "(Required) The commands to run on the instance.",
        "default": ["{{ ssm:myShellCommands }}"],
        "interpolationType" : "ENV_VAR"
      }
    },
    //truncated
 }
```

**注意**  
此处介绍的部分插件仅在 Windows Server 实例或 Linux 实例上运行。每个插件都记录了平台依赖关系。  
macOS 的 Amazon Elastic Compute Cloud (Amazon EC2) 实例支持以下文档插件：  
`aws:refreshAssociation`
`aws:runShellScript`
`aws:runPowerShellScript`
`aws:softwareInventory`
`aws:updateSsmAgent`

**Topics**
+ [

## 共享输入
](#shared-inputs)
+ [

## `aws:applications`
](#aws-applications)
+ [

## `aws:cloudWatch`
](#aws-cloudWatch)
+ [

## `aws:configureDocker`
](#aws-configuredocker)
+ [

## `aws:configurePackage`
](#aws-configurepackage)
+ [

## `aws:domainJoin`
](#aws-domainJoin)
+ [

## `aws:downloadContent`
](#aws-downloadContent)
+ [

## `aws:psModule`
](#aws-psModule)
+ [

## `aws:refreshAssociation`
](#aws-refreshassociation)
+ [

## `aws:runDockerAction`
](#aws-rundockeraction)
+ [

## `aws:runDocument`
](#aws-rundocument)
+ [

## `aws:runPowerShellScript`
](#aws-runPowerShellScript)
+ [

## `aws:runShellScript`
](#aws-runShellScript)
+ [

## `aws:softwareInventory`
](#aws-softwareinventory)
+ [

## `aws:updateAgent`
](#aws-updateagent)
+ [

## `aws:updateSsmAgent`
](#aws-updatessmagent)

## 共享输入
<a name="shared-inputs"></a>

仅在版本 3.0.502 和更高版本的 SSM Agent 中，所有插件都可以使用以下输入：

**最终步骤**  
您希望文档运行的最后一步。如果此输入是为某个步骤定义的，则它优先于 `onFailure` 或 `onSuccess` 输入中指定的 `exit` 值。为了使具有此输入的步骤按预期运行，该步骤必须是文档 `mainSteps` 中定义的最后一个步骤。  
类型：布尔值  
有效值：`true` \$1 `false`  
必需：否

**onFailure**  
如果您为插件指定此输入的 `exit` 值并且步骤失败，则步骤状态会显示失败，并且文档不会运行任何剩余步骤，除非 `finallyStep` 已定义。如果您为插件指定此输入的 `successAndExit` 值并且步骤失败，则步骤状态会显示成功，并且文档不会运行任何剩余的步骤，除非 `finallyStep` 已定义。  
类型：字符串  
有效值：`exit` \$1 `successAndExit`  
必需：否

**onSuccess**  
如果您为插件指定此输入并且步骤成功运行，则文档不会运行任何剩余的步骤，除非 `finallyStep` 已定义。  
类型：字符串  
有效值：`exit`  
必需：否

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

```
---
schemaVersion: '2.2'
description: Shared inputs example
parameters:
  customDocumentParameter:
    type: String
    description: Example parameter for a custom Command-type document.
mainSteps:
- action: aws:runDocument
  name: runCustomConfiguration
  inputs:
    documentType: SSMDocument
    documentPath: "yourCustomDocument"
    documentParameters: '"documentParameter":{{customDocumentParameter}}'
    onSuccess: exit
- action: aws:runDocument
  name: ifConfigurationFailure
  inputs:
    documentType: SSMDocument
    documentPath: "yourCustomRepairDocument"
    onFailure: exit
- action: aws:runDocument
  name: finalConfiguration
  inputs:
    documentType: SSMDocument
    documentPath: "yourCustomFinalDocument"
    finallyStep: true
```

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

```
{
   "schemaVersion": "2.2",
   "description": "Shared inputs example",
   "parameters": {
      "customDocumentParameter": {
         "type": "String",
         "description": "Example parameter for a custom Command-type document."
      }
   },
   "mainSteps":[
      {
         "action": "aws:runDocument",
         "name": "runCustomConfiguration",
         "inputs": {
            "documentType": "SSMDocument",
            "documentPath": "yourCustomDocument",
            "documentParameters": "\"documentParameter\":{{customDocumentParameter}}",
            "onSuccess": "exit"
         }
      },
      {
         "action": "aws:runDocument",
         "name": "ifConfigurationFailure",
         "inputs": {
            "documentType": "SSMDocument",
            "documentPath": "yourCustomRepairDocument",
            "onFailure": "exit"
         }
      },
      {
         "action": "aws:runDocument",
         "name":"finalConfiguration",
         "inputs": {
            "documentType": "SSMDocument",
            "documentPath": "yourCustomFinalDocument",
            "finallyStep": true
         }
      }
   ]
}
```

------

## `aws:applications`
<a name="aws-applications"></a>

在 EC2 实例上安装、修复或卸载应用程序。此插件仅在 Windows Server 操作系统中运行。

### 语法
<a name="applications-syntax"></a>

#### Schema 2.2
<a name="applications-syntax-2.2"></a>

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

```
---
schemaVersion: '2.2'
description: aws:applications plugin
parameters:
  source:
    description: "(Required) Source of msi."
    type: String
mainSteps:
- action: aws:applications
  name: example
  inputs:
    action: Install
    source: "{{ source }}"
```

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

```
{
  "schemaVersion":"2.2",
  "description":"aws:applications",
  "parameters":{
    "source":{
    "description":"(Required) Source of msi.",
    "type":"String"
    }
  },
  "mainSteps":[
    {
      "action":"aws:applications",
      "name":"example",
      "inputs":{
        "action":"Install",
        "source":"{{ source }}"
      }
    }
  ]
}
```

------

#### Schema 1.2
<a name="applications-syntax-1.2"></a>

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

```
---
runtimeConfig:
  aws:applications:
    properties:
    - id: 0.aws:applications
      action: "{{ action }}"
      parameters: "{{ parameters }}"
      source: "{{ source }}"
      sourceHash: "{{ sourceHash }}"
```

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

```
{
   "runtimeConfig":{
      "aws:applications":{
         "properties":[
            {
               "id":"0.aws:applications",
               "action":"{{ action }}",
               "parameters":"{{ parameters }}",
               "source":"{{ source }}",
               "sourceHash":"{{ sourceHash }}"
            }
         ]
      }
   }
}
```

------

### 属性
<a name="applications-properties"></a>

**action**  
要执行的操作。  
类型：Enum  
有效值：`Install` \$1`Repair` \$1`Uninstall`  
是否必需：是

**参数**  
安装程序的参数。  
类型：字符串  
必需：否

**source**  
应用程序的 `.msi` 文件的 URL。  
类型：字符串  
是否必需：是

**sourceHash**  
`.msi` 文件的 SHA256 哈希值。  
类型：字符串  
必需：否

## `aws:cloudWatch`
<a name="aws-cloudWatch"></a>

从中导出数据 Windows Server 添加到 Amazon CloudWatch 视台或 Amazon CloudWatch Logs 中，并使用云监控指标监控数据。此插件仅在 Windows Server 操作系统中运行。要详细了解如何配置 CloudWatch 与 Amazon Elastic Compute Cloud（Amazon EC2）的集成，请参阅《Amazon CloudWatch 用户指南》**中的[使用 CloudWatch 代理收集指标、日志和跟踪信息](https://docs.amazonaws.cn/AmazonCloudWatch/latest/monitoring/Install-CloudWatch-Agent.html)。

**重要**  
统一的 CloudWatch 代理已取代 SSM Agent，作为将日志数据发送到 Amazon CloudWatch Logs 的工具。不支持 SSM Agent aws:cloudWatch 插件。我们建议仅将统一的 CloudWatch 代理用于您的日志收集过程。有关更多信息，请参阅以下主题：  
[将节点日志发送到统一的 CloudWatch Logs（CloudWatch 代理）](monitoring-cloudwatch-agent.md)
[将 Windows Server 节点日志收集迁移到 CloudWatch 代理](monitoring-cloudwatch-agent.md#monitoring-cloudwatch-agent-migrate)
《Amazon CloudWatch 用户指南》**中的[使用 CloudWatch 代理收集指标、日志和跟踪信息](https://docs.amazonaws.cn/AmazonCloudWatch/latest/monitoring/Install-CloudWatch-Agent.html)。

您可以导出和监视以下数据类型：

**ApplicationEventLog**  
将应用程序事件日志数据发送到 CloudWatch Logs。

**CustomLogs**  
将任何基于文本的日志文件发送到 Amazon CloudWatch Logs。CloudWatch 插件会为日志文件创建指纹。系统随后将数据偏移与每个指纹进行关联。该插件会在出现更改时上传文件，记录偏移，然后将该偏移与指纹关联。此方法用于避免出现这种情况：用户启用插件后，将服务与包含大量文件的目录关联，然后系统会上传所有文件。  
请注意，如果应用程序在轮询期间截断或尝试清除日志，为 `LogDirectoryPath` 指定的任何日志都可能丢失条目。例如，如果您要限制日志文件大小，请在达到此限制时创建新的日志文件，然后继续将数据写入新文件。

**ETW**  
将 Windows (ETW) 事件跟踪数据发送到 CloudWatch Logs。

**IIS**  
将 IIS 日志数据发送到 CloudWatch Logs

**PerformanceCounter**  
将 Windows 性能计数器发送到 CloudWatch。您可以选择不同类别作为指标上传到 CloudWatch。对于要上传的每个性能计数器，创建具有唯一 ID 的 **PerformanceCounter** 部分 (例如“PerformanceCounter2”、“PerformanceCounter3”等)，然后配置其属性。  
如果 Amazon Systems Manager SSM Agent 或 CloudWatch 插件已停止，则性能计数器数据不再记录到 CloudWatch 中。此行为不同于自定义日志或 Windows 事件日志。自定义日志和 Windows 事件日志会保留性能计数器数据，并在 SSM Agent 后或 CloudWatch 插件可用时将其上传到 CloudWatch。

**SecurityEventLog**  
将安全日志数据发送到 CloudWatch Logs。

**SystemEventLog**  
将系统事件日志数据发送到 CloudWatch Logs。

可为数据定义以下目标：

**CloudWatch**  
发送性能计数器指标数据时所在的目标。可添加具有唯一 ID 的更多部分 (例如，“CloudWatch2”和“CloudWatch3”等)，并为每个新 ID 指定一个不同的区域，将相同数据发送到不同位置。

**CloudWatchLogs**  
发送日志数据时所在的目标。可添加具有唯一 ID 的更多部分 (例如，“CloudWatchLogs2”和“CloudWatchLogs3”等)，并为每个新 ID 指定一个不同的区域，将相同数据发送到不同位置。

### 语法
<a name="cloudWatch-syntax"></a>

```
"runtimeConfig":{
        "aws:cloudWatch":{
            "settings":{
                "startType":"{{ status }}"
            },
            "properties":"{{ properties }}"
        }
    }
```

### 设置和属性
<a name="cloudWatch-properties"></a>

**AccessKey**  
您的访问密钥 ID。如果未使用 IAM 角色启动实例，则必须指定此属性。此属性不能与 SSM 一起使用。  
类型：字符串  
必需：否

**CategoryName**  
性能监视器提供的性能计数器类别。  
类型：字符串  
是否必需：是

**CounterName**  
性能监视器提供的性能计数器名称。  
类型：字符串  
是否必需：是

**CultureName**  
记录时间戳的区域设置。如果 **CultureName** 为空，则它默认为您的 Windows Server 实例所使用的相同区域位置。  
类型：字符串  
有效值：有关支持的值的列表，请参阅 Microsoft 网站上的[国家语言支持 (NLS)](https://msdn.microsoft.com/en-us/library/cc233982.aspx)。不支持 **div**、**div-MV**、**hu** 和 **hu-HU** 值。  
必需：否

**DimensionName**  
Amazon CloudWatch 指标的维度。如果您要指定 `DimensionName`，则必须指定 `DimensionValue`。这些参数在列出指标时提供另一个视图。您可以对多个指标使用同一个维度，以便查看属于特定维度的所有指标。  
类型：字符串  
必需：否

**DimensionValue**  
Amazon CloudWatch 指标的维度值。  
类型：字符串  
必需：否

**编码**  
要使用的文件编码 (例如 UTF-8)。使用编码名称，而不是显示名称。  
类型：字符串  
有效值：有关支持的值的列表，请参阅 Microsoft Learn 库中的 [Encoding Class](https://learn.microsoft.com/en-us/dotnet/api/system.text.encoding?view=net-7.0)。  
是否必需：是

**筛选条件**  
日志名称的前缀。将此参数保留空白以监控所有文件。  
类型：字符串  
有效值：有关支持的值的列表，请参阅 MSDN 库中的 [FileSystemWatcherFilter 属性](http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.filter.aspx)主题。  
必需：否

**流**  
要上传的每个数据类型以及数据的目标（CloudWatch 或 CloudWatch Logs ）。例如，要将在 `"Id": "PerformanceCounter"` 下定义的性能计数器发送到在 `"Id": "CloudWatch"` 下定义的 CloudWatch 目标，请输入 **“PerformanceCounter,CloudWatch”**。同样，要将自定义日志、ETW 日志和系统日志发送到 `"Id": "ETW"` 下定义的 CloudWatch Logs 目标，请输入 **“(ETW),CloudWatchLogs”**。此外，还可以将相同性能计数器或日志文件发送到多个目标。例如，要将应用程序日志发送到在 `"Id": "CloudWatchLogs"` 和 `"Id": "CloudWatchLogs2"` 下定义的两个不同目标，请输入 **"ApplicationEventLog,(CloudWatchLogs, CloudWatchLogs2)"**。  
类型：字符串  
有效值 (源)：`ApplicationEventLog` \$1 `CustomLogs` \$1 `ETW` \$1 `PerformanceCounter` \$1 `SystemEventLog` \$1 `SecurityEventLog`   
有效值 (目标)：`CloudWatch` \$1 `CloudWatchLogs` \$1 `CloudWatch`*n* \$1 `CloudWatchLogs`*n*   
是否必需：是

**FullName**  
组件的完整名称。  
类型：字符串  
是否必需：是

**Id**  
标识数据源或目标。此标识符在配置文件中必须是唯一的。  
类型：字符串  
是否必需：是

**InstanceName**  
性能计数器实例的名称。请勿使用星号 (\$1) 标识所有实例，因为每个性能计数器组件仅支持一个指标。不过可以使用 **\$1Total**。  
类型：字符串  
是否必需：是

**级别**  
发送到 Amazon CloudWatch 的消息类型。  
类型：字符串  
有效值：  
+ **1** – 仅上传错误消息。
+ **2** – 仅上传警告消息。
+ **4** – 仅上传信息消息。
您可以将这些值加在一起以包含多种类型的消息。例如，**3** 表示将包含错误消息 (**1**) 和警告消息 (**2**)。值 **7** 表示将包含错误消息 (**1**)、警告消息 (**2**) 和说明性消息 (**4**)。  
是否必需：是  
应将 Windows 安全日志的级别设置为 7。

**LineCount**  
标识日志文件的标头中的行数。例如，IIS 日志文件拥有几乎相同的标头。您可以输入 **3**，系统会读取日志文件标头的前三行以进行识别。在 IIS 日志文件中，第三行是日期和时间戳，各日志文件的日期和时间戳互不相同。  
类型：整数  
必需：否

**LogDirectoryPath**  
对于 CustomLogs，这是日志在 EC2 实例上的存储路径。对于 IIS 日志，这是为单个站点存储 IIS 日志的文件夹 (例如 **C:\$1\$1inetpub\$1\$1logs\$1\$1LogFiles\$1\$1W3SVC*n***)。对于 IIS 日志，仅支持 W3C 日志格式。不支持 IIS、NCSA 和自定义格式。  
类型：字符串  
是否必需：是

**LogGroup**  
日志组的名称。此名称显示在 CloudWatch 控制台的 **Log Groups（日志组）**屏幕上。  
类型：字符串  
是否必需：是

**LogName**  
日志文件的名称。  

1. 要查找日志的名称，请在事件查看器的导航窗格中，选择 **Applications and Services Logs (应用程序和服务日志)**。

1. 在日志列表中，右键单击要上传的日志（例如 `Microsoft` > `Windows` > `Backup` > `Operational`），然后选择**创建自定义视图**。

1. 在 **Create Custom View (创建自定义视图)** 对话框中，选择 **XML** 选项卡。**LogName** 位于 <Select Path=> 标签中（例如 `Microsoft-Windows-Backup`）。将此文本复制到 **LogName** 参数。
类型：字符串  
有效值：`Application` \$1 `Security` \$1 `System` \$1 `Microsoft-Windows-WinINet/Analytic`  
是否必需：是

**LogStream**  
目标日志流。如果使用默认值 **\$1instance\$1id\$1**，则将该实例的实例 ID 用作日志流名称。  
类型：字符串  
有效值：`{instance_id}` \$1 `{hostname}` \$1 `{ip_address}` *<log\$1stream\$1name>*  
如果输入的日志流名称不存在，则 CloudWatch Logs 会自动创建该名称。可以使用文字字符串或预定义的变量（**\$1instance\$1id\$1**、**\$1hostname\$1**、**\$1ip\$1address\$1**），或所有这三个变量的组合来定义日志流名称。  
此参数中指定的日志流名称将在 CloudWatch 控制台中的 **Log Groups > Streams for *<YourLogStream>***（日志组 > <YourLogStream> 的流）屏幕上显示。  
是否必需：是

**MetricName**  
您希望性能数据包含在其下的 CloudWatch 指标。  
不要在名称中使用特殊字符。如果您这样做，指标和相关警报可能无法正常工作。
类型：字符串  
是否必需：是

**NameSpace**  
您希望将写入性能计数器数据的指标命名空间。  
类型：字符串  
是否必需：是

**PollInterval**  
必须在多少秒之后才能上传新性能计数器和日志数据。  
类型：整数  
有效值：将其设置为 5 秒或 5 秒以上。建议设置为十五秒 (00:00:15)。  
是否必需：是

**区域**  
要发送日志数据的 Amazon Web Services 区域。虽然可以将性能计数器发送到与日志数据发送目标不同的区域，但是我们建议您将此参数设置为运行实例的区域。  
类型：字符串  
有效值：Systems Manager 和 CloudWatch Logs 都支持的 Amazon Web Services 区域 区域ID，例如 `us-east-2`、`eu-west-1`, 和 `ap-southeast-1`。对于每个服务支持的 Amazon Web Services 区域 的列表，请参阅**《Amazon Web Services 一般参考》中的 [Amazon CloudWatch Logs Service Endpoints](https://docs.amazonaws.cn/general/latest/gr/cwl_region.html#cwl_region) 和 [Systems Manager service endpoints](https://docs.amazonaws.cn/general/latest/gr/ssm.html#ssm_region)。  
是否必需：是

**SecretKey**  
您的秘密访问密钥。如果未使用 IAM 角色启动实例，则必须指定此属性。  
类型：字符串  
必需：否

**startType**  
打开或关闭实例上的 CloudWatch 功能。  
类型：字符串  
有效值：`Enabled` \$1 `Disabled`  
是否必需：是

**TimestampFormat**  
要使用的时间戳格式。有关支持的值的列表，请参阅 MSDN 库中的[自定义日期和时间格式字符串](http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx)。  
类型：字符串  
是否必需：是

**TimeZoneKind**  
在日志时间戳中不包含时区信息时提供时区信息。如果此参数留空且时间戳不包括时区信息，则 CloudWatch Logs 默认为本地时区。如果时间戳已包含时区信息，则忽略此参数。  
类型：字符串  
有效值：`Local` \$1 `UTC`  
必需：否

**单位**  
适当的指标计量单位。  
类型：字符串  
有效值：秒 \$1 微秒 \$1 毫秒 \$1 字节 \$1 千字节 \$1 兆字节 \$1 千兆字节 \$1 太兆字节 \$1 位 \$1 千位 \$1 兆位 \$1 千兆位 \$1 太兆位 \$1 百分比 \$1 计数 \$1 字节/秒 \$1 千字节/秒 \$1 兆字节/秒 \$1 千兆字节/秒 \$1 太兆字节/秒 \$1 位/秒 \$1 千位/秒 \$1 兆位/秒 \$1 千兆位/秒 \$1 太兆位/秒 \$1 计数/秒 \$1 无  
是否必需：是

## `aws:configureDocker`
<a name="aws-configuredocker"></a>

(2.0 版或更高版本架构) 将实例配置为使用容器和 Docker。此插件在大多数 Linux 变体和 Windows Server 操作系统中受支持。

### 语法
<a name="configuredocker-syntax"></a>

#### Schema 2.2
<a name="configuredocker-syntax-2.2"></a>

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

```
---
schemaVersion: '2.2'
description: aws:configureDocker
parameters:
  action:
    description: "(Required) The type of action to perform."
    type: String
    default: Install
    allowedValues:
    - Install
    - Uninstall
mainSteps:
- action: aws:configureDocker
  name: configureDocker
  inputs:
    action: "{{ action }}"
```

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

```
{
  "schemaVersion": "2.2",
  "description": "aws:configureDocker plugin",
  "parameters": {
    "action": {
      "description": "(Required) The type of action to perform.",
      "type": "String",
      "default": "Install",
      "allowedValues": [
        "Install",
        "Uninstall"
      ]
    }
  },
  "mainSteps": [
    {
      "action": "aws:configureDocker",
      "name": "configureDocker",
      "inputs": {
        "action": "{{ action }}"
      }
    }
  ]
}
```

------

### 输入
<a name="configuredocker-properties"></a>

**action**  
要执行的操作类型。  
类型：Enum  
有效值：`Install` \$1 `Uninstall`  
是否必需：是

## `aws:configurePackage`
<a name="aws-configurepackage"></a>

（2.0 版或更高版本架构）安装或卸载 Amazon Systems Manager Distributor 程序包。您可以安装所指定软件包的最新版本、默认版本或其中一个版本。Amazon 提供的软件包也受支持。此插件可在 Windows Server 和 Linux 操作系统上运行，但 Linux 操作系统不支持所有可用的软件包。

Windows Server 的可用 Amazon 程序包包括：`AWSPVDriver`、`AWSNVMe`、`AwsEnaNetworkDriver`、`AwsVssComponents`、`AmazonCloudWatchAgent`、`CodeDeployAgent`，和 `AWSSupport-EC2Rescue.`

适用于 Linux 操作系统的可用 Amazon 软件包包括：`AmazonCloudWatchAgent`、`CodeDeployAgent`,和 `AWSSupport-EC2Rescue`。

### 语法
<a name="configurepackage-syntax"></a>

#### Schema 2.2
<a name="configurepackage-syntax-2.2"></a>

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

```
---
schemaVersion: '2.2'
description: aws:configurePackage
parameters:
  name:
    description: "(Required) The name of the AWS package to install or uninstall."
    type: String
  action:
    description: "(Required) The type of action to perform."
    type: String
    default: Install
    allowedValues:
    - Install
    - Uninstall
  ssmParameter:
    description: "(Required) Argument stored in Parameter Store."
    type: String
    default: "{{ ssm:parameter_store_arg }}"
mainSteps:
- action: aws:configurePackage
  name: configurePackage
  inputs:
    name: "{{ name }}"
    action: "{{ action }}"
    additionalArguments: 
      "{\"SSM_parameter_store_arg\": \"{{ ssmParameter }}\", \"SSM_custom_arg\": \"myValue\"}"
```

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

```
{
   "schemaVersion": "2.2",
   "description": "aws:configurePackage",
   "parameters": {
      "name": {
         "description": "(Required) The name of the AWS package to install or uninstall.",
         "type": "String"
      },
      "action": {
         "description": "(Required) The type of action to perform.",
         "type": "String",
         "default": "Install",
         "allowedValues": [
            "Install",
            "Uninstall"
         ]
      },
      "ssmParameter": {
         "description": "(Required) Argument stored in Parameter Store.",
         "type": "String",
         "default": "{{ ssm:parameter_store_arg }}"
      }
   },
   "mainSteps": [
      {
         "action": "aws:configurePackage",
         "name": "configurePackage",
         "inputs": {
            "name": "{{ name }}",
            "action": "{{ action }}",
            "additionalArguments": "{\"SSM_parameter_store_arg\": \"{{ ssmParameter }}\", \"SSM_custom_arg\": \"myValue\"}"
         }
      }
   ]
}
```

------

### 输入
<a name="configurepackage-properties"></a>

**name**  
要安装或卸载的 Amazon 软件包名称。可用的软件包如下所述：`AWSPVDriver`、`AwsEnaNetworkDriver`、`AwsVssComponents`，和 `AmazonCloudWatchAgent`。  
类型：字符串  
是否必需：是

**action**  
安装或卸载软件包。  
类型：Enum  
有效值：`Install` \$1 `Uninstall`  
是否必需：是

**安装类型**  
要执行的安装类型。如果指定 `Uninstall and reinstall`，该软件包将完全卸载，然后重新安装。在重新安装完成之前，应用程序不可用。如果指定 `In-place update`，将根据您在更新脚本中提供的指令，仅将新文件或更改的文件添加到现有的安装中。应用程序在整个更新过程中保持可用。这些区域有:已发布的软件包 Amazon 不支持 `In-place update` 选项。`Uninstall and reinstall` 为默认值。  
类型：Enum  
有效值：`Uninstall and reinstall` \$1 `In-place update`  
必需：否

**附加参数**  
为安装、卸载或更新脚本提供的其他参数的 JSON 字符串。每个参数的前缀必须为 `SSM_`。可以使用约定 `{{ssm:parameter-name}}` 在附加参数中引用 Parameter Store 参数。要在安装、卸载或更新脚本过程中使用附加参数，必须使用适合操作系统的语法将参数作为环境变量引用。例如，在 PowerShell 中，您引用 `SSM_arg` 参数为 `$Env:SSM_arg`。您定义的参数数量没有限制，但附加参数输入有 4096 个字符限制。此限制包括您定义的所有秘钥和值。  
类型：StringMap  
必需：否

**版本**  
要卸载或安装的特定版本的软件包。如果要安装，系统默认安装最新发布的版本。如果要卸载，系统默认卸载当前安装的版本。如果没有找到已安装的版本，则会下载最新发布的版本，然后运行卸载操作。  
类型：字符串  
必需：否

## `aws:domainJoin`
<a name="aws-domainJoin"></a>

将 EC2 实例加入域。此插件在 Linux 和 Windows Server 操作系统上运行。该插件会将 Linux 实例的主机名更改为 EC2AMAZ-*XXXXXXX* 格式。有关加入 EC2 实例的更多信息，请参阅* Amazon Directory Service 管理指南*中的[将 EC2 实例加入到 Amazon 托管 Microsoft AD 目录](https://docs.amazonaws.cn/directoryservice/latest/admin-guide/ms_ad_join_instance.html)。

### 语法
<a name="domainJoin-syntax"></a>

#### Schema 2.2
<a name="domainJoin-syntax-2.2"></a>

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

```
---
schemaVersion: '2.2'
description: aws:domainJoin
parameters:
  directoryId:
    description: "(Required) The ID of the directory."
    type: String
  directoryName:
    description: "(Required) The name of the domain."
    type: String
  directoryOU:
    description: "(Optional) The organizational unit to assign the computer object to."
    type: String
  dnsIpAddresses:
    description: "(Required) The IP addresses of the DNS servers for your directory."
    type: StringList
  hostname:
    description: "(Optional) The hostname you want to assign to the node."
    type: String
mainSteps:
- action: aws:domainJoin
  name: domainJoin
  inputs:
    directoryId: "{{ directoryId }}"
    directoryName: "{{ directoryName }}"
    directoryOU: "{{ directoryOU }}"
    dnsIpAddresses: "{{ dnsIpAddresses }}"
    hostname: "{{ hostname }}"
```

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

```
{
  "schemaVersion": "2.2",
  "description": "aws:domainJoin",
  "parameters": {
    "directoryId": {
      "description": "(Required) The ID of the directory.",
      "type": "String"
    },
    "directoryName": {
      "description": "(Required) The name of the domain.",
      "type": "String"
    },
    "directoryOU": {
        "description": "(Optional) The organizational unit to assign the computer object to.",
        "type": "String"
      },
    "dnsIpAddresses": {
      "description": "(Required) The IP addresses of the DNS servers for your directory.",
      "type": "StringList"
    },
    "hostname": {
        "description": "(Optional) The hostname you want to assign to the node.",
        "type": "String"
      }
  },
  "mainSteps": [
    {
      "action": "aws:domainJoin",
      "name": "domainJoin",
      "inputs": {
        "directoryId": "{{ directoryId }}",
        "directoryName": "{{ directoryName }}",
        "directoryOU":"{{ directoryOU }}",
        "dnsIpAddresses":"{{ dnsIpAddresses }}",
        "hostname":"{{ hostname }}"
      }
    }
  ]
}
```

------

#### Schema 1.2
<a name="domainJoin-syntax-1.2"></a>

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

```
---
runtimeConfig:
  aws:domainJoin:
    properties:
      directoryId: "{{ directoryId }}"
      directoryName: "{{ directoryName }}"
      directoryOU: "{{ directoryOU }}"
      dnsIpAddresses: "{{ dnsIpAddresses }}"
```

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

```
{
   "runtimeConfig":{
      "aws:domainJoin":{
         "properties":{
            "directoryId":"{{ directoryId }}",
            "directoryName":"{{ directoryName }}",
            "directoryOU":"{{ directoryOU }}",
            "dnsIpAddresses":"{{ dnsIpAddresses }}"
         }
      }
   }
}
```

------

### 属性
<a name="domainJoin-properties"></a>

**directoryId**  
目录的 ID。  
类型：字符串  
是否必需：是  
示例："directoryId": "d-1234567890"

**directoryName**  
域的名称。  
类型：字符串  
是否必需：是  
示例："directoryName": "example.com"

**directoryOU**  
组织部门 (OU)。  
类型：字符串  
必需：否  
示例："directoryOU": "OU=test,DC=example,DC=com"

**dnsIpAddresses**  
DNS 服务器的 IP 地址。  
类型：StringList  
是否必需：是  
示例："dnsIpAddresses": ["198.51.100.1","198.51.100.2"]

**hostname**  
要分配给节点的主机名。如果未提供，则 Windows Server 实例的名称不会更改，而 Linux 实例将使用默认的命名模式。如果提供，Windows Server 实例将使用所提供的确切值，而 Linux 实例将以此为前缀（除非将 `keepHostName` 设置为“true”）。  
类型：字符串  
必需：否

**keepHostName**  
确定 Linux 实例在加入域时是否更改主机名。此参数仅适用于 Linux。默认情况下（`hostname`、`hostnameNumAppendDigits` 无输入，且 `keepHostName` 设置为“false”），Linux 主机将重命名为 EC2AMAZ-XXXXXX 模式。设置为“true”时，将会保留原始主机名并忽略 `hostname` 和 `hostnameNumAppendDigits` 的输入。  
类型：布尔值  
必需：否

**hostnameNumAppendDigits**  
定义要在主机名值之后附加的随机数值位数。此参数仅适用于 Linux，并且应与 `hostname` 参数结合使用。如果未提供 `hostname`，则会忽略此参数。  
类型：字符串  
允许的值：1 至 5  
必需：否

### 示例
<a name="domainJoin-examples"></a>

有关示例，请参阅《Amazon Directory Service 管理指南》**中的[将 Amazon EC2 实例加入您的 Amazon Managed Microsoft AD](https://docs.amazonaws.cn/directoryservice/latest/admin-guide/ec2-join-aws-domain.html)。

## `aws:downloadContent`
<a name="aws-downloadContent"></a>

（2.0 版或更高版本架构）从远程位置下载 SSM 文档和脚本。不支持 GitHub Enterprise 存储库。此插件在 Linux 和 Windows Server 操作系统中受支持。

### 语法
<a name="downloadContent-syntax"></a>

#### Schema 2.2
<a name="downloadContent-syntax-2.2"></a>

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

```
---
schemaVersion: '2.2'
description: aws:downloadContent
parameters:
  sourceType:
    description: "(Required) The download source."
    type: String
  sourceInfo:
    description: "(Required) The information required to retrieve the content from
      the required source."
    type: StringMap
mainSteps:
- action: aws:downloadContent
  name: downloadContent
  inputs:
    sourceType: "{{ sourceType }}"
    sourceInfo: "{{ sourceInfo }}"
```

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

```
{
  "schemaVersion": "2.2",
  "description": "aws:downloadContent",
  "parameters": {
    "sourceType": {
    "description": "(Required) The download source.",
    "type": "String"
  },
  "sourceInfo": {
    "description": "(Required) The information required to retrieve the content from the required source.",
    "type": "StringMap"
    }
  },
  "mainSteps": [
    {
      "action": "aws:downloadContent",
      "name": "downloadContent",
      "inputs": {
        "sourceType":"{{ sourceType }}",
        "sourceInfo":"{{ sourceInfo }}"
      }
    }
  ]
}
```

------

### 输入
<a name="downloadContent-inputs"></a>

**sourceType**  
下载源 Systems Manager 支持以下下载脚本和 SSM 文档的源类型：`GitHub`、`Git`、`HTTP`、`S3`，和`SSMDocument`。  
类型：字符串  
是否必需：是

**sourceInfo**  
从所需源检索内容所需的信息。  
类型：StringMap  
是否必需：是  
 **对于 sourceType `GitHub,`，请指定以下内容：**  
+ owner：存储库所有者。
+ repository：存储库的名称。
+ path：您要下载的文件或目录所在的路径。
+ getOptions：用于从分支（而非主分支）或存储库中的特定提交中检索内容的额外选项。如果您在主分支中使用最新提交，则可以省略 getOptions。如果您的存储库是在 2020 年 10 月 1 日之后创建的，则默认分支可能被命名为 main 而不是 master。在这种情况下，需要为 getOptions 参数指定值。

  此参数采用以下格式：
  + branch:refs/heads/*branch\$1name*

    默认值为 `master`。

    要指定非默认分支，请使用以下格式：

    branch:refs/heads/*branch\$1name*
  + commitID：*commitID*

    默认值为 `head`。

    要在最新提交以外的提交中使用 SSM 文档的版本，请指定完整的提交 ID。例如：

    ```
    "getOptions": "commitID:bbc1ddb94...b76d3bEXAMPLE",
    ```
+ tokenInfo：以 `{{ssm-secure:secure-string-token-name}}` 格式存储 GitHub 访问令牌信息的 Systems Manager 参数（SecureString 参数）。
**注意**  
该 `tokenInfo` 字段是唯一支持 SecureString 参数的 SSM 文档插件字段。任何其他字段和任何其他 SSM 文档插件都不支持 SecureString 参数。

```
{
    "owner":"TestUser",
    "repository":"GitHubTest",
    "path":"scripts/python/test-script",
    "getOptions":"branch:master",
    "tokenInfo":"{{ssm-secure:secure-string-token}}"
}
```
 **对于 sourceType `Git`，必须指定以下内容：**  
+ repository

  path：要下载的文件或目录的 Git repository URL。

  类型：字符串
此外，您可以指定以下任何可选参数：  
+ getOptions

  用于从分支（而非主分支）或存储库中的特定提交中检索内容的额外选项。如果您在主分支中使用最新提交，则可以省略 getOptions。

  类型：字符串

  此参数采用以下格式：
  + branch:refs/heads/*branch\$1name*

    默认值为 `master`。

    仅当您的 SSM 文档存储在 `master` 以外的分支中时， `"branch"` 才是必需的。例如：

    ```
    "getOptions": "branch:refs/heads/main"
    ```
  + commitID：*commitID*

    默认值为 `head`。

    要在最新提交以外的提交中使用 SSM 文档的版本，请指定完整的提交 ID。例如：

    ```
    "getOptions": "commitID:bbc1ddb94...b76d3bEXAMPLE",
    ```
+ privateSSHKey

  连接指定的`repository` 时要使用的 SSH 秘钥。可以使用以下格式为引用 SSH 密钥值 `SecureString` 参数：`{{ssm-secure:your-secure-string-parameter}}`。

  类型：字符串
+ 跳过主机键检查

  确定连接到您指定的 `repository` 时 StrictHostKeyChecking 选项的值。默认值为 `false`。

  类型：布尔值
+ username

  连接到使用 HTTP 指定的 `repository` 时使用的用户名。可以使用以下格式引用用户名值的 `SecureString` 参数：`{{ssm-secure:your-secure-string-parameter}}`。

  类型：字符串
+ password

  连接到使用 HTTP 指定的 `repository` 时使用的密码。可以使用以下格式为引用密码值 `SecureString` 参数：`{{ssm-secure:your-secure-string-parameter}}`。

  类型：字符串
 对于 **sourceType`HTTP`，必须指定以下内容：**  
+ url

  要下载的文件或目录的 URL。

  类型：字符串
此外，您可以指定以下任何可选参数：  
+ allowInsecureDownload

  确定是否可以通过未使用安全套接字层 (SSL) 或传输层安全 (TLS) 加密的连接执行下载。默认值为 `false`。我们建议您不要在未加密的情况下执行下载。如果您选择这样做，您将承担所有相关风险。安全性是 Amazon 和您的共同责任。这被描述为责任共担共担模式。要了解更多信息，请参阅[责任共担模式](https://www.amazonaws.cn/compliance/shared-responsibility-model/)。

  类型：布尔值
+ authMethod

  确定在连接到指定的 `url` 时是否要使用用户名和密码。如果指定 `Basic` 或者 `Digest` 时，您必须为 `username` 和 `password` 参数提供值。使用 `Digest` 方法，3.0.1181.0 版本或更高版本的 SSM Agent 必须安装在实例上。`Digest` 方法支持 MD5 和 SHA256 加密。

  类型：字符串

  有效值：`None` \$1`Basic` \$1`Digest`
+ username

  连接到 `url` 您指定使用 `Basic` 身份验证。可以使用以下格式引用用户名值的 `SecureString` 参数：`{{ssm-secure:your-secure-string-parameter}}`。

  类型：字符串
+ password

  连接到您使用 `Basic` 身份验证指定的 `url` 时使用的密码。可以使用以下格式为引用密码值 `SecureString` 参数：`{{ssm-secure:your-secure-string-parameter}}`。

  类型：字符串
 **对于 sourceType `S3`，请指定以下内容：**  
+ 路径：要从 Amazon S3 下载的文件或目录的 URL。
从 S3 存储桶下载文件时，会在下载目录中生成 .etag 文件。

```
{
    "path": "https://s3.amazonaws.com/amzn-s3-demo-bucket/powershell/helloPowershell.ps1" 
}
```
 **对于 SourceType `SSMDocument`，请指定以下其中*一* 项：**  
+ 名称：采用以下格式的文档的名称和版本：`name:version`。版本为可选项。

  ```
  {
      "name": "Example-RunPowerShellScript:3" 
  }
  ```
+ name：采用以下格式的文档 ARN：`arn:aws:ssm:region:account_id:document/document_name`

  ```
  {
     "name":"arn:aws:ssm:us-east-2:3344556677:document/MySharedDoc"
  }
  ```

**destinationPath**  
实例上的可选本地路径，用于下载文件。如果不指定路径，内容将下载到命令 ID 的相对路径。  
类型：字符串  
必需：否

## `aws:psModule`
<a name="aws-psModule"></a>

在 Amazon EC2 实例上安装 PowerShell 模块。此插件仅在 Windows Server 操作系统中运行。

### 语法
<a name="psModule-syntax"></a>

#### Schema 2.2
<a name="psModule-syntax-2.2"></a>

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

```
---
schemaVersion: '2.2'
description: aws:psModule
parameters:
  source:
    description: "(Required) The URL or local path on the instance to the application
      .zip file."
    type: String
mainSteps:
- action: aws:psModule
  name: psModule
  inputs:
    source: "{{ source }}"
```

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

```
{
  "schemaVersion": "2.2",
  "description": "aws:psModule",
  "parameters": {
    "source": {
      "description": "(Required) The URL or local path on the instance to the application .zip file.",
      "type": "String"
    }
  },
  "mainSteps": [
    {
      "action": "aws:psModule",
      "name": "psModule",
      "inputs": {
        "source": "{{ source }}"
      }
    }
  ]
}
```

------

#### Schema 1.2
<a name="domainJoin-syntax-1.2"></a>

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

```
---
runtimeConfig:
  aws:psModule:
    properties:
    - runCommand: "{{ commands }}"
      source: "{{ source }}"
      sourceHash: "{{ sourceHash }}"
      workingDirectory: "{{ workingDirectory }}"
      timeoutSeconds: "{{ executionTimeout }}"
```

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

```
{
   "runtimeConfig":{
      "aws:psModule":{
         "properties":[
            {
               "runCommand":"{{ commands }}",
               "source":"{{ source }}",
               "sourceHash":"{{ sourceHash }}",
               "workingDirectory":"{{ workingDirectory }}",
               "timeoutSeconds":"{{ executionTimeout }}"
            }
         ]
      }
   }
}
```

------

### 属性
<a name="psModule-properties"></a>

**runCommand**  
安装模块后要运行的 PowerShell 命令。  
类型：StringList  
必需：否

**source**  
访问实例上应用程序 `.zip` 文件的 URL 或本地路径。  
类型：字符串  
是否必需：是

**sourceHash**  
`.zip` 文件的 SHA256 哈希值。  
类型：字符串  
必需：否

**timeoutSeconds**  
在被视为已失败前命令将运行的时间 (以秒为单位)。  
类型：字符串  
必需：否

**workingDirectory**  
实例上工作目录的路径。  
类型：字符串  
必需：否

## `aws:refreshAssociation`
<a name="aws-refreshassociation"></a>

(2.0 版或更高版本架构) 按需刷新 (强制应用) 关联。此操作将根据所选关联或绑定到目标的所有关联中定义的内容来更改系统状态。此插件仅在 Linux 和 Windows Server 操作系统上运行。

### 语法
<a name="refreshassociation-syntax"></a>

#### Schema 2.2
<a name="refreshassociation-syntax-2.2"></a>

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

```
---
schemaVersion: '2.2'
description: aws:refreshAssociation
parameters:
  associationIds:
    description: "(Optional) List of association IDs. If empty, all associations bound
      to the specified target are applied."
    type: StringList
mainSteps:
- action: aws:refreshAssociation
  name: refreshAssociation
  inputs:
    associationIds:
    - "{{ associationIds }}"
```

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

```
{
  "schemaVersion": "2.2",
  "description": "aws:refreshAssociation",
  "parameters": {
    "associationIds": {
      "description": "(Optional) List of association IDs. If empty, all associations bound to the specified target are applied.",
      "type": "StringList"
    }
  },
  "mainSteps": [
    {
      "action": "aws:refreshAssociation",
      "name": "refreshAssociation",
      "inputs": {
        "associationIds": [
          "{{ associationIds }}"
        ]
      }
    }
  ]
}
```

------

### 输入
<a name="refreshassociation-properties"></a>

**associationIds**  
关联 ID 的列表。如果为空，则应用与指定目标绑定的所有关联。  
类型：StringList  
必需：否

## `aws:runDockerAction`
<a name="aws-rundockeraction"></a>

（2.0 版或更高版本架构）在容器上运行 Docker 操作。此插件仅在 Linux 和 Windows Server 操作系统上运行。

### 语法
<a name="rundockeraction-syntax"></a>

#### Schema 2.2
<a name="rundockeraction-syntax-2.2"></a>

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

```
---
mainSteps:
- action: aws:runDockerAction
  name: RunDockerAction
  inputs:
    action: "{{ action }}"
    container: "{{ container }}"
    image: "{{ image }}"
    memory: "{{ memory }}"
    cpuShares: "{{ cpuShares }}"
    volume: "{{ volume }}"
    cmd: "{{ cmd }}"
    env: "{{ env }}"
    user: "{{ user }}"
    publish: "{{ publish }}"
    workingDirectory: "{{ workingDirectory }}"
    timeoutSeconds: "{{ timeoutSeconds }}"
```

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

```
{
   "mainSteps":[
      {
         "action":"aws:runDockerAction",
         "name":"RunDockerAction",
         "inputs":{
            "action":"{{ action }}",
            "container":"{{ container }}",
            "image":"{{ image }}",
            "memory":"{{ memory }}",
            "cpuShares":"{{ cpuShares }}",
            "volume":"{{ volume }}",
            "cmd":"{{ cmd }}",
            "env":"{{ env }}",
            "user":"{{ user }}",
            "publish":"{{ publish }}",
            "workingDirectory": "{{ workingDirectory }}",
            "timeoutSeconds": "{{ timeoutSeconds }}"
         }
      }
   ]
}
```

------

### 输入
<a name="rundockeraction-properties"></a>

**action**  
要执行的操作类型。  
类型：字符串  
是否必需：是

**容器**  
Docker 容器 ID。  
类型：字符串  
必需：否

**image**  
Docker 映像名称。  
类型：字符串  
必需：否

**cmd**  
容器命令。  
类型：字符串  
必需：否

**memory**  
容器内存限制。  
类型：字符串  
必需：否

**cpuShares**  
容器 CPU 份额 (相对权重)。  
类型：字符串  
必需：否

**volume**  
容器卷挂载。  
类型：StringList  
必需：否

**env**  
容器的环境变量。  
类型：字符串  
必需：否

**用户**  
容器的用户名。  
类型：字符串  
必需：否

**发布**  
容器已发布端口。  
类型：字符串  
必需：否

**workingDirectory**  
您的托管节点上的工作目录的路径。  
类型：字符串  
必需：否

**timeoutSeconds**  
在被视为已失败前命令将运行的时间 (以秒为单位)。  
类型：字符串  
必需：否

## `aws:runDocument`
<a name="aws-rundocument"></a>

（2.0 版或更高版本架构）运行存储在 Systems Manager 或本地共享存储中的 SSM 文档。您可以将此插件与 [`aws:downloadContent`](#aws-downloadContent) 插件配合使用，以将远程位置的 SSM 文档下载到本地共享存储，然后运行该文档。此插件在 Linux 和 Windows Server 操作系统中受支持。此插件不支持运行 `AWS-UpdateSSMAgent` 文档或使用 `aws:updateSsmAgent` 插件的任何文档。

### 语法
<a name="rundocument-syntax"></a>

#### Schema 2.2
<a name="aws-rundocument-syntax-2.2"></a>

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

```
---
schemaVersion: '2.2'
description: aws:runDocument
parameters:
  documentType:
    description: "(Required) The document type to run."
    type: String
    allowedValues:
    - LocalPath
    - SSMDocument
mainSteps:
- action: aws:runDocument
  name: runDocument
  inputs:
    documentType: "{{ documentType }}"
```

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

```
{
  "schemaVersion": "2.2",
  "description": "aws:runDocument",
  "parameters": {
    "documentType": {
      "description": "(Required) The document type to run.",
      "type": "String",
      "allowedValues": [
        "LocalPath",
        "SSMDocument"
      ]
    }
  },
  "mainSteps": [
    {
      "action": "aws:runDocument",
      "name": "runDocument",
      "inputs": {
        "documentType": "{{ documentType }}"
      }
    }
  ]
}
```

------

### 输入
<a name="rundocument-properties"></a>

**documentType**  
要运行的文档类型。您可以运行本地文档 (`LocalPath`) 或存储在 Systems Manager (`SSMDocument`) 中的文档。  
类型：字符串  
是否必需：是

**documentPath**  
文档的路径。如果 `documentType` 是 `LocalPath`，则指定本地共享存储上文档的路径。如果 `documentType` 是 `SSMDocument`，则指定文档的名称。  
类型：字符串  
必需：否

**documentParameters**  
文档的参数。  
类型：StringMap  
必需：否

## `aws:runPowerShellScript`
<a name="aws-runPowerShellScript"></a>

运行 PowerShell 脚本或者指定要运行的脚本的路径。此插件在 Microsoft Windows Server 和 Linux 操作系统上运行。

### 语法
<a name="runPowerShellScript-syntax"></a>

#### Schema 2.2
<a name="runPowerShellScript-syntax-2.2"></a>

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

```
---
schemaVersion: '2.2'
description: aws:runPowerShellScript
parameters:
  commands:
    type: String
    description: "(Required) The commands to run or the path to an existing script
      on the instance."
    default: Write-Host "Hello World"
mainSteps:
- action: aws:runPowerShellScript
  name: runPowerShellScript
  inputs:
    timeoutSeconds: '60'
    runCommand:
    - "{{ commands }}"
```

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

```
{
  "schemaVersion": "2.2",
  "description": "aws:runPowerShellScript",
  "parameters": {
    "commands": {
      "type": "String",
      "description": "(Required) The commands to run or the path to an existing script on the instance.",
      "default": "Write-Host \"Hello World\""
    }
  },
  "mainSteps": [
    {
      "action": "aws:runPowerShellScript",
      "name": "runPowerShellScript",
      "inputs": {
        "timeoutSeconds": "60",
        "runCommand": [
          "{{ commands }}"
        ]
      }
    }
  ]
}
```

------

#### Schema 1.2
<a name="runPowerShellScript-syntax-1.2"></a>

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

```
---
runtimeConfig:
  aws:runPowerShellScript:
    properties:
    - id: 0.aws:runPowerShellScript
      runCommand: "{{ commands }}"
      workingDirectory: "{{ workingDirectory }}"
      timeoutSeconds: "{{ executionTimeout }}"
```

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

```
{
   "runtimeConfig":{
      "aws:runPowerShellScript":{
         "properties":[
            {
               "id":"0.aws:runPowerShellScript",
               "runCommand":"{{ commands }}",
               "workingDirectory":"{{ workingDirectory }}",
               "timeoutSeconds":"{{ executionTimeout }}"
            }
         ]
      }
   }
}
```

------

### 属性
<a name="runPowerShellScript-properties"></a>

**runCommand**  
指定要运行的命令或实例上现有脚本的路径。  
类型：StringList  
是否必需：是

**timeoutSeconds**  
在被视为已失败前命令将运行的时间（以秒为单位）。如果达到超时，Systems Manager 停止命令执行。  
类型：字符串  
必需：否

**workingDirectory**  
实例上工作目录的路径。  
类型：字符串  
必需：否

## `aws:runShellScript`
<a name="aws-runShellScript"></a>

运行 Linux shell 脚本或者指定要运行的脚本的路径。此插件仅在 Linux 操作系统中运行。

### 语法
<a name="runShellScript-syntax"></a>

#### Schema 2.2
<a name="runShellScript-syntax-2.2"></a>

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

```
---
schemaVersion: '2.2'
description: aws:runShellScript
parameters:
  commands:
    type: String
    description: "(Required) The commands to run or the path to an existing script
      on the instance."
    default: echo Hello World
mainSteps:
- action: aws:runShellScript
  name: runShellScript
  inputs:
    timeoutSeconds: '60'
    runCommand:
    - "{{ commands }}"
```

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

```
{
  "schemaVersion": "2.2",
  "description": "aws:runShellScript",
  "parameters": {
    "commands": {
      "type": "String",
      "description": "(Required) The commands to run or the path to an existing script on the instance.",
      "default": "echo Hello World"
    }
  },
  "mainSteps": [
    {
      "action": "aws:runShellScript",
      "name": "runShellScript",
      "inputs": {
        "timeoutSeconds": "60",
        "runCommand": [
          "{{ commands }}"
        ]
      }
    }
  ]
}
```

------

#### Schema 1.2
<a name="runShellScript-syntax-1.2"></a>

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

```
---
runtimeConfig:
  aws:runShellScript:
    properties:
    - runCommand: "{{ commands }}"
      workingDirectory: "{{ workingDirectory }}"
      timeoutSeconds: "{{ executionTimeout }}"
```

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

```
{
   "runtimeConfig":{
      "aws:runShellScript":{
         "properties":[
            {
               "runCommand":"{{ commands }}",
               "workingDirectory":"{{ workingDirectory }}",
               "timeoutSeconds":"{{ executionTimeout }}"
            }
         ]
      }
   }
}
```

------

### 属性
<a name="runShellScript-properties"></a>

**runCommand**  
指定要运行的命令或实例上现有脚本的路径。  
类型：StringList  
是否必需：是

**timeoutSeconds**  
在被视为已失败前命令将运行的时间（以秒为单位）。如果达到超时，Systems Manager 停止命令执行。  
类型：字符串  
必需：否

**workingDirectory**  
实例上工作目录的路径。  
类型：字符串  
必需：否

## `aws:softwareInventory`
<a name="aws-softwareinventory"></a>

（2.0 版或更高版本架构）收集有关托管实例上应用程序、文件和配置的元数据。此插件仅在 Linux 和 Windows Server 操作系统上运行。在配置清单收集时，应该首先创建 Amazon Systems Manager State Manager 关联。Systems Manager 会在关联运行时收集清单数据。如果您不先创建关联，并试图调用 `aws:softwareInventory` 插件，则系统会返回以下错误：

```
The aws:softwareInventory plugin can only be invoked via ssm-associate.
```

一个实例一次只能配置一个清单关联。如果您为一个实例配置了两个或更多关联，则清单关联不会运行，而且系统不会收集清单数据。有关收集文件清单的更多信息，请参阅 [Amazon Systems Manager 清单](systems-manager-inventory.md)。

### 语法
<a name="softwareinventory-syntax"></a>

#### Schema 2.2
<a name="softwareinventory-syntax-2.2"></a>

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

```
---
mainSteps:
- action: aws:softwareInventory
  name: collectSoftwareInventoryItems
  inputs:
    applications: "{{ applications }}"
    awsComponents: "{{ awsComponents }}"
    networkConfig: "{{ networkConfig }}"
    files: "{{ files }}"
    services: "{{ services }}"
    windowsRoles: "{{ windowsRoles }}"
    windowsRegistry: "{{ windowsRegistry}}"
    windowsUpdates: "{{ windowsUpdates }}"
    instanceDetailedInformation: "{{ instanceDetailedInformation }}"
    customInventory: "{{ customInventory }}"
```

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

```
{
   "mainSteps":[
      {
         "action":"aws:softwareInventory",
         "name":"collectSoftwareInventoryItems",
         "inputs":{
            "applications":"{{ applications }}",
            "awsComponents":"{{ awsComponents }}",
            "networkConfig":"{{ networkConfig }}",
            "files":"{{ files }}",
            "services":"{{ services }}",
            "windowsRoles":"{{ windowsRoles }}",
            "windowsRegistry":"{{ windowsRegistry}}",
            "windowsUpdates":"{{ windowsUpdates }}",
            "instanceDetailedInformation":"{{ instanceDetailedInformation }}",
            "customInventory":"{{ customInventory }}"
         }
      }
   ]
}
```

------

### 输入
<a name="softwareinventory-properties"></a>

**应用程序**  
（可选）收集已安装应用程序的元数据。  
类型：字符串  
必需：否

**awsComponents**  
（可选）收集Amazon 组件（例如 amazon-ssm-agent）的元数据。  
类型：字符串  
必需：否

**文件**  
（可选，需要 2.2.64.0 版本或更高版本的 SSM Agent ）收集文件的元数据，包括文件名称、文件创建时间、文件上次修改和访问时间以及文件大小等等。有关收集文件清单的更多信息，请参阅 [使用文件和 Windows 注册表清单](inventory-file-and-registry.md)。  
类型：字符串  
必需：否

**networkConfig**  
（可选）收集网络配置的元数据。  
类型：字符串  
必需：否

**billingInfo**  
（可选）收集与 AMI 账单代码关联的平台详细信息的元数据。  
类型：字符串  
必需：否

**windowsUpdates**  
（可选）收集所有 Windows 更新的元数据。  
类型：字符串  
必需：否

**instanceDetailedInformation**  
（可选）收集多于默认清单插件 （`aws:instanceInformation`）提供的信息的实例信息，包括 CPU 型号、速度和核心数量，等等。  
类型：字符串  
必需：否

**务**  
（可选，仅限 Windows 操作系统，需要 2.2.64.0 版本或更高版本的SSM Agent ）收集服务配置的元数据。  
类型：字符串  
必需：否

**windowsRegistry**  
（可选，仅限 Windows 操作系统，需要 2.2.64.0 版本或更高版本的SSM Agent）收集 Windows 注册表项和值。您可以选择一个键路径并以递归方式收集所有键和值。您还可以收集特定路径的特定注册表项及其值。清单会收集键路径、名称、类型和值。有关收集 Windows 注册表清单的更多信息，请参阅 [使用文件和 Windows 注册表清单](inventory-file-and-registry.md)。  
类型：字符串  
必需：否

**windowsRoles**  
（可选，仅限 Windows 操作系统，需要 2.2.64.0 版本或更高版本的 SSM Agent ）收集 Microsoft Windows 角色配置的元数据。  
类型：字符串  
必需：否

**customInventory**  
（可选）收集自定义清单数据。有关自定义清单的更多信息，请参阅 [使用自定义清单](inventory-custom.md)  
类型：字符串  
必需：否

**customInventoryDirectory**  
（可选）从指定目录收集自定义清单数据。有关自定义清单的更多信息，请参阅 [使用自定义清单](inventory-custom.md)  
类型：字符串  
必需：否

## `aws:updateAgent`
<a name="aws-updateagent"></a>

此命令可将 EC2Config 服务更新为最新版本或指定较旧版本。此插件仅在 Microsoft Windows Server 操作系统上运行。有关 EC2Config 服务的更多信息，请参阅《Amazon EC2 用户指南》**中的[使用 EC2Config 服务配置 Windows 实例（旧版）](https://docs.amazonaws.cn/AWSEC2/latest/UserGuide/ec2config-service.html)。

### 语法
<a name="updateagent-syntax"></a>

#### Schema 2.2
<a name="updateagent-syntax-2.2"></a>

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

```
---
schemaVersion: '2.2'
description: aws:updateAgent
mainSteps:
- action: aws:updateAgent
  name: updateAgent
  inputs:
    agentName: Ec2Config
    source: https://s3.{Region}.amazonaws.com/aws-ssm-{Region}/manifest.json
```

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

```
{
  "schemaVersion": "2.2",
  "description": "aws:updateAgent",
  "mainSteps": [
    {
      "action": "aws:updateAgent",
      "name": "updateAgent",
      "inputs": {
        "agentName": "Ec2Config",
        "source": "https://s3.{Region}.amazonaws.com/aws-ssm-{Region}/manifest.json"
      }
    }
  ]
}
```

------

#### Schema 1.2
<a name="updateagent-syntax-1.2"></a>

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

```
---
runtimeConfig:
  aws:updateAgent:
    properties:
      agentName: Ec2Config
      source: https://s3.{Region}.amazonaws.com/aws-ssm-{Region}/manifest.json
      allowDowngrade: "{{ allowDowngrade }}"
      targetVersion: "{{ version }}"
```

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

```
{
   "runtimeConfig":{
      "aws:updateAgent":{
         "properties":{
            "agentName":"Ec2Config",
            "source":"https://s3.{Region}.amazonaws.com/aws-ssm-{Region}/manifest.json",
            "allowDowngrade":"{{ allowDowngrade }}",
            "targetVersion":"{{ version }}"
         }
      }
   }
}
```

------

### 属性
<a name="updateagent-properties"></a>

**agentName**  
EC2Config。这是运行 EC2Config 服务的代理的名称。  
类型：字符串  
是否必需：是

**allowDowngrade**  
允许将 EC2Config 服务降级为早期版本。如果设置为 False，则只能将该服务升级为更新的版本 (默认)。如果设置为 True，则指定早期版本。  
类型：布尔值  
必需：否

**source**  
Systems Manager 复制要安装的 EC2Config 版本的位置。您无法更改此位置。  
类型：字符串  
是否必需：是

**targetVersion**  
要安装的特定版本的 EC2Config 服务。如果未指定，服务将更新到最新版本。  
类型：字符串  
必需：否

## `aws:updateSsmAgent`
<a name="aws-updatessmagent"></a>

将 SSM Agent 更新到最新版本或指定较旧版本。此插件在 Linux 和 Windows Server 操作系统上运行。有关更多信息，请参阅 [使用 SSM Agent](ssm-agent.md)。

### 语法
<a name="updateSSMagent-syntax"></a>

#### Schema 2.2
<a name="updateaSSMgent-syntax-2.2"></a>

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

```
---
schemaVersion: '2.2'
description: aws:updateSsmAgent
parameters:
  allowDowngrade:
    default: 'false'
    description: "(Optional) Allow the Amazon SSM Agent service to be downgraded to
      an earlier version. If set to false, the service can be upgraded to newer versions
      only (default). If set to true, specify the earlier version."
    type: String
    allowedValues:
    - 'true'
    - 'false'
mainSteps:
- action: aws:updateSsmAgent
  name: updateSSMAgent
  inputs:
    agentName: amazon-ssm-agent
    source: https://s3.{Region}.amazonaws.com/amazon-ssm-{Region}/ssm-agent-manifest.json
    allowDowngrade: "{{ allowDowngrade }}"
```

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

```
{
  "schemaVersion": "2.2",
  "description": "aws:updateSsmAgent",
  "parameters": {
    "allowDowngrade": {
      "default": "false",
      "description": "(Required) Allow the Amazon SSM Agent service to be downgraded to an earlier version. If set to false, the service can be upgraded to newer versions only (default). If set to true, specify the earlier version.",
      "type": "String",
      "allowedValues": [
        "true",
        "false"
      ]
    }
  },
  "mainSteps": [
    {
      "action": "aws:updateSsmAgent",
      "name": "awsupdateSsmAgent",
      "inputs": {
        "agentName": "amazon-ssm-agent",
        "source": "https://s3.{Region}.amazonaws.com/amazon-ssm-{Region}/ssm-agent-manifest.json",
        "allowDowngrade": "{{ allowDowngrade }}"
      }
    }
  ]
}
```

------

#### Schema 1.2
<a name="updateaSSMgent-syntax-1.2"></a>

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

```
---
runtimeConfig:
  aws:updateSsmAgent:
    properties:
    - agentName: amazon-ssm-agent
      source: https://s3.{Region}.amazonaws.com/aws-ssm-{Region}/manifest.json
      allowDowngrade: "{{ allowDowngrade }}"
```

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

```
{
   "runtimeConfig":{
      "aws:updateSsmAgent":{
         "properties":[
            {
               "agentName":"amazon-ssm-agent",
               "source":"https://s3.{Region}.amazonaws.com/aws-ssm-{Region}/manifest.json",
               "allowDowngrade":"{{ allowDowngrade }}"
            }
         ]
      }
   }
}
```

------

### 属性
<a name="updateSSMagent-properties"></a>

**agentName**  
amazon-ssm-agent。这是在实例上处理请求并运行命令的 Systems Manager agent 的名称。  
类型：字符串  
是否必需：是

**allowDowngrade**  
允许将 SSM Agent 降级为早期版本。如果设置为 False，则只能将该代理升级为更新的版本 (默认)。如果设置为 True，则指定早期版本。  
类型：布尔值  
是否必需：是

**source**  
复制 Systems Manager 要安装的 SSM Agent 版本的位置。您无法更改此位置。  
类型：字符串  
是否必需：是

**targetVersion**  
要安装的特定版本的 SSM Agent。如果未指定，代理将更新到最新版本。  
类型：字符串  
必需：否

# 创建 SSM 文档内容
<a name="documents-creating-content"></a>

如果 Amazon Systems Manager 公有文档不执行要对 Amazon 资源执行的所有操作，您可以创建自己的 SSM 文档。您还可以使用控制台克隆 SSM 文档。克隆文档将内容从现有文档复制到可以修改的新文档。创建或克隆文档时，文档的内容不得超过 64KB。此配额还包括在运行时指定的输入参数内容。创建新的 `Command` 或 `Policy` 文档时，我们建议您使用版本 2.2 或更高版本的架构，以便利用最新功能，例如文档编辑、自动版本控制、排序等。

## 编写 SSM 文档内容
<a name="writing-ssm-doc-content"></a>

要创建您自己的 SSM 文档内容，请务必了解可用于 SSM 文档的不同架构、功能、插件和语法。我们建议您熟悉以下资源。
+  [编写您自己的 Amazon Systems Manager 文档](https://www.amazonaws.cn/blogs//mt/writing-your-own-aws-systems-manager-documents/) 
+  [数据元素和参数](documents-syntax-data-elements-parameters.md) 
+  [架构、功能和示例](documents-schemas-features.md) 
+  [命令文档插件参考](documents-command-ssm-plugin-reference.md) 
+  [Systems Manager 自动化操作参考](automation-actions.md) 
+  [自动化系统变量](automation-variables.md) 
+  [其他运行手册示例](automation-document-examples.md) 
+  使用Amazon Toolkit for Visual Studio Code [处理 Systems Manager 自动化运行手册](https://docs.amazonaws.cn/toolkit-for-vscode/latest/userguide/systems-manager-automation-docs.html) 
+  [自动化运行手册的视觉对象设计体验](automation-visual-designer.md) 
+  [在运行手册中使用脚本](automation-document-script-considerations.md) 

Amazon 预定义的 SSM 文档可能会执行您所需的一些操作。您可以通过在自定义 SSM 文档中使用 `aws:runDocument`、`aws:runCommand` 或 `aws:executeAutomation` 插件来调用这些文档，具体取决于文档类型。您还可以将这些文档的某些部分复制到自定义的 SSM 文档中，并编辑内容以满足您的要求。

**提示**  
创建 SSM 文档内容时，您可能会在测试时多次更改内容并更新 SSM 文档。以下命令使用最新内容更新 SSM 文档，并将文档的默认版本更新为文档的最新版本。  
Linux 和 Windows 命令使用 `jq` 命令行工具筛选 JSON 响应数据。

```
latestDocVersion=$(aws ssm update-document \
    --content file://path/to/file/documentContent.json \
    --name "ExampleDocument" \
    --document-format JSON \
    --document-version '$LATEST' \
    | jq -r '.DocumentDescription.LatestVersion')

aws ssm update-document-default-version \
    --name "ExampleDocument" \
    --document-version $latestDocVersion
```

```
latestDocVersion=$(aws ssm update-document ^
    --content file://C:\path\to\file\documentContent.json ^
    --name "ExampleDocument" ^
    --document-format JSON ^
    --document-version "$LATEST" ^
    | jq -r '.DocumentDescription.LatestVersion')

aws ssm update-document-default-version ^
    --name "ExampleDocument" ^
    --document-version $latestDocVersion
```

```
$content = Get-Content -Path "C:\path\to\file\documentContent.json" | Out-String
$latestDocVersion = Update-SSMDocument `
    -Content $content `
    -Name "ExampleDocument" `
    -DocumentFormat "JSON" `
    -DocumentVersion '$LATEST' `
    | Select-Object -ExpandProperty LatestVersion

Update-SSMDocumentDefaultVersion `
    -Name "ExampleDocument" `
    -DocumentVersion $latestDocVersion
```

### SSM 文档的安全最佳实践
<a name="ssm-document-security-practices"></a>

创建 SSM 文档时，请遵循以下安全最佳实践，以帮助防范命令注入攻击并确保安全处理参数：
+ 对将用于命令或脚本的字符串参数使用环境变量插值。为字符串参数添加值为 `ENV_VAR` 的 `interpolationType` 属性：

  ```
  {
      "command": {
          "type": "String",
          "description": "Command to execute",
          "interpolationType": "ENV_VAR"
      }
  }
  ```

  您可以指定插值生成的值不接受双引号，从而进一步增强 SSM 文档的安全性：

  ```
  {
      "command": {
          "type": "String",
          "description": "Command to execute",
          "interpolationType": "ENV_VAR",
              "allowedPattern": "^[^"]*$"
      }
  }
  ```
+ 在使用 Python、Ruby 或 Node.js 等解释性语言时，请使用恰当的环境变量语法来引用参数：

  ```
  # Python example
  import os
  command = os.environ['SSM_Message']
  ```
+ 为了向后兼容旧版 SSM Agent（3.3.2746.0 版之前），请为环境变量添加回退逻辑：

  ```
  if [ -z "${SSM_command+x}" ]; then
      export SSM_command="{{command}}"
  fi
  ```
+ 将环境变量插值与 `allowedPattern` 相结合，提供额外的输入验证。在以下示例中，`allowedPattern` 的值 `^[^"]*$` 专门用于防止在字符串值中使用双引号：

  ```
  {
      "command": {
          "type": "String",
          "interpolationType": "ENV_VAR",
          "allowedPattern": "^[a-zA-Z0-9_-]+$"
      }
  }
  ```
+ 在实现 SSM 文档之前，请确认以下安全注意事项：
  + 适用时，所有接受用户输入的字符串参数均使用环境变量插值。
  + 尽可能使用 `allowedPattern` 来实现输入验证。
  + 该文档包含了处理参数的恰当错误处理方法。
  + 对使用旧版 SSM Agent 的环境保持了向后兼容性。

有关 Systems Manager 访问的 Amazon 服务自有资源以及如何配置数据边界策略的信息，请参阅 [Amazon Systems Manager 中的数据边界](data-perimeters.md)。

## 克隆 SSM 文档
<a name="cloning-ssm-document"></a>

您可以克隆 Amazon Systems Manager 文档，使用 Systems Manager 文档控制台创建 SSM 文档。克隆 SSM 文档将内容从现有文档复制到可以修改的新文档中。无法克隆大于 64KB 的文档。

**克隆 SSM 文档**

1. 访问 [https://console.aws.amazon.com/systems-manager/](https://console.amazonaws.cn/systems-manager/)，打开 Amazon Systems Manager 控制台。

1. 在导航窗格中，选择**文档**。

1. 在搜索框中，输入要克隆的文档的名称。

1. 选择要克隆的文档的名称，然后选择**操作**下拉菜单中的**克隆文档**。

1. 根据需要修改文档，然后选择**创建文档**保存文档。

编写 SSM 文档内容后，您可以通过以下方法之一使用您的内容创建 SSM 文档。

**Topics**
+ [

## 编写 SSM 文档内容
](#writing-ssm-doc-content)
+ [

## 克隆 SSM 文档
](#cloning-ssm-document)
+ [

## 创建复合文档
](#documents-creating-composite)

## 创建复合文档
<a name="documents-creating-composite"></a>

*复合* Amazon Systems Manager (SSM) 文档是自定义文档，可通过运行一个或多个次要 SSM 文档执行一系列操作。复合文档允许您为常见任务（例如引导软件或域加入实例）创建一组标准 SSM 文档，从而升级*基础设施代码*。您随后可以在同一个 Amazon Web Services 区域 中跨 Amazon Web Services 账户 共享这些文档，从而减少 SSM 文档的维护工作并确保文档一致性。

例如，您可以创建执行以下操作的复合文档：

1. 安装允许列表中的所有修补程序。

1. 安装防病毒软件。

1. 从 GitHub 下载脚本并运行这些脚本。

在本例中，您的自定义 SSM 文档包含执行下面这些操作的以下插件：

1. 用于运行 `AWS-RunPatchBaseline` 文档的 `aws:runDocument` 插件，它将安装所有允许列出的补丁。

1. 可运行 `AWS-InstallApplication` 文档的 `aws:runDocument` 插件，这会安装防病毒软件。

1. 可从 GitHub 下载脚本并运行这些脚本的 `aws:downloadContent` 插件。

复合和次要文档可存储在 Systems Manager、GitHub（公有和私有存储库）或 Amazon S3 中。可创建 JSON 或 YAML 格式的复合文档和次要文档。

**注意**  
复合文档只能运行三个文档的最大文档深度。这意味着复合文档可以调用子文档；该子文档可调用最后一个文档。

要创建复合文档，请在自定义 SSM 文档中添加 [`aws:runDocument`](documents-command-ssm-plugin-reference.md#aws-rundocument) 插件并指定必需的输入。下面是可执行以下操作的复合文档示例：

1. 运行 [`aws:downloadContent`](documents-command-ssm-plugin-reference.md#aws-downloadContent) 插件，可从 GitHub 公有存储库将 SSM 文档下载到名为 bootstrap 的本地目录。SSM 文档称为 StateManagerBootstrap.yml (YAML 文档)。

1. 运行 `aws:runDocument` 插件可运行 StateManagerBootstrap.yml 文档。未指定任何参数。

1. 运行 `aws:runDocument` 插件以运行 `AWS-ConfigureDocker pre-defined` SSM 文档。指定的参数会在实例上安装 Docker。

```
{
  "schemaVersion": "2.2",
  "description": "My composite document for bootstrapping software and installing Docker.",
  "parameters": {
  },
  "mainSteps": [
    {
      "action": "aws:downloadContent",
      "name": "downloadContent",
      "inputs": {
        "sourceType": "GitHub",
        "sourceInfo": "{\"owner\":\"TestUser1\",\"repository\":\"TestPublic\", \"path\":\"documents/bootstrap/StateManagerBootstrap.yml\"}",
        "destinationPath": "bootstrap"
      }
    },
    {
      "action": "aws:runDocument",
      "name": "runDocument",
      "inputs": {
        "documentType": "LocalPath",
        "documentPath": "bootstrap",
        "documentParameters": "{}"
      }
    },
    {
      "action": "aws:runDocument",
      "name": "configureDocker",
      "inputs": {
        "documentType": "SSMDocument",
        "documentPath": "AWS-ConfigureDocker",
        "documentParameters": "{\"action\":\"Install\"}"
      }
    }
  ]
}
```

**更多信息**  
+ 有关在使用 Run Command 调用脚本时重启服务器和实例的信息，请参阅 [运行命令时处理重启问题](send-commands-reboot.md)。
+ 有关可添加到自定义 SSM 文档的插件的更多信息，请参阅 [命令文档插件参考](documents-command-ssm-plugin-reference.md)。
+ 如果只想从远程位置运行文档 (无需创建复合文档)，请参阅 [从远程位置运行文档](documents-running-remote-github-s3.md)。

# 使用文档
<a name="documents-using"></a>

本节包含有关如何使用 SSM 文档的信息。

**Topics**
+ [

# 比较 SSM 文档版本
](comparing-versions.md)
+ [

# 创建 SSM 文档
](create-ssm-console.md)
+ [

# 删除自定义 SSM 文档
](deleting-documents.md)
+ [

# 从远程位置运行文档
](documents-running-remote-github-s3.md)
+ [

# 共享 SSM 文档
](documents-ssm-sharing.md)
+ [

# 搜索 SSM 文档
](ssm-documents-searching.md)

# 比较 SSM 文档版本
<a name="comparing-versions"></a>

您可以在 Systems Manager 文档控制台中比较 Amazon Systems Manager (SSM) 文档版本之间的内容差异。比较 SSM 文档的版本时，会突出显示版本内容之间的差异。

**比较 SSM 文档内容（控制台）**

1. 访问 [https://console.aws.amazon.com/systems-manager/](https://console.amazonaws.cn/systems-manager/)，打开 Amazon Systems Manager 控制台。

1. 在导航窗格中，选择**文档**。

1. 在文档列表中，选择要比较其内容的文档。

1. 在存储库的**内容**选项卡上，选择**比较版本**，然后选择要将内容与其进行比较的文档版本。

# 创建 SSM 文档
<a name="create-ssm-console"></a>

如 [编写 SSM 文档内容](documents-creating-content.md#writing-ssm-doc-content) 中所述，为自定义 SSM 文档创建内容后，您可以通过 Systems Manager 控制台使用您的内容创建 SSM 文档。

**要创建 SSM 文档**

1. 访问 [https://console.aws.amazon.com/systems-manager/](https://console.amazonaws.cn/systems-manager/)，打开 Amazon Systems Manager 控制台。

1. 在导航窗格中，选择**文档**。

1. 选择 **Create command or session (创建命令或会话)**。

1. 输入文档的描述性名称。

1. （可选）对于 **Target type (目标类型)**，指定可以运行文档的资源类型。

1. 在**文档类型**列表中，选择您要创建的文档类型。

1. 删除 **Content (内容)** 字段中的方括号，然后将您之前创建的文档内容粘贴到这里。

1. （可选）在 **Document tags (文档标签)** 部分，将一个或多个标签键名称/值对应用于文档。

   标签是您分配给资源的可选元数据。标签可让您按各种标准（如用途、所有者或环境）对资源进行分类。例如，您可能希望标记文档以标识它运行的任务类型、它指向的操作系统的类型以及它在其中运行的环境。在这种情况下，您可以指定以下键名/键值对：
   + `Key=TaskType,Value=MyConfigurationUpdate`
   + `Key=OS,Value=AMAZON_LINUX_2`
   + `Key=Environment,Value=Production`

1. 选择**创建文档**以保存文档。

# 删除自定义 SSM 文档
<a name="deleting-documents"></a>

如果您不再想使用自定义 SSM 文档，则可以使用 Amazon Systems Manager 控制台来删除它。

**要删除 SSM 文档**

1. 访问 [https://console.aws.amazon.com/systems-manager/](https://console.amazonaws.cn/systems-manager/)，打开 Amazon Systems Manager 控制台。

1. 在导航窗格中，选择**文档**。

1. 选择要删除的角色。

1. 选择**删除**。在提示删除文档时，选择**删除**。

有关使用命令行工具或 SDK 删除 SSM 文档的示例，请参阅 [将 `DeleteDocument` 与 Amazon SDK 或 CLI 配合使用](example_ssm_DeleteDocument_section.md)。

# 从远程位置运行文档
<a name="documents-running-remote-github-s3"></a>

您可以使用 `AWS-RunDocument` 预定义的 SSM 文档从远程位置运行 Amazon Systems Manager (SSM) 文档。此文档支持运行存储在以下位置的 SSM 文档：
+ 公共和私有 GitHub 存储库（不支持 GitHub Enterprise）
+ Amazon S3 存储桶
+ Systems Manager

虽然您也可以使用State Manager或 Automation（都是 Amazon Systems Manager 中的工具）运行远程文档，下面的过程仅介绍了如何在 Systems Manager 控制台中使用 Amazon Systems Manager Run Command 运行远程 SSM 文档。

**注意**  
`AWS-RunDocument` 仅可用于运行命令类型的 SSM 文档，而不是其他类型（如自动化运行手册）。`AWS-RunDocument` 使用 `aws:downloadContent` 插件。有关 `aws:downloadContent` 插件的更多信息，请参阅 [`aws:downloadContent`](documents-command-ssm-plugin-reference.md#aws-downloadContent)。

**警告**  
`AWS-RunDocument` 可以执行来自各种来源（SSM 文档、GitHub、S3、URL）的文档内容。执行远程文档时，评估的 IAM 权限适用于远程文档中的 `ssm:GetDocument` 和 `AWS-RunDocument` 中的 `ssm:SendCommand`。如果您的 IAM 策略拒绝访问特定 SSM 文档，则拥有 `AWS-RunDocument` 权限的用户仍然可以通过将文档内容作为参数传递来执行这些被拒绝的文档，这些参数可能不受相同的特定于文档的 IAM 限制的约束。  
要正确限制文档执行，请使用以下方法之一：  
**允许名单批准的来源**：如果您需要使用嵌套文档执行，请使用对每种来源类型的适当控制来限制仅允许访问已批准的来源：用于控制 SSM 文档来源的 `ssm:GetDocument` 的 IAM 策略、Amazon S3 来源的 IAM 和 Amazon S3 存储桶策略以及公共互联网来源的网络设置（例如 VPC 端点或安全组）。
**限制访问 AWS-RunDocument**：拒绝 `AWS-RunDocument` 中的 `ssm:SendCommand` 以及在您的 IAM 策略中使用 `aws:runDocument` 插件的任何其他文档，进而防止嵌套文档执行。
**使用权限边界**：实施 IAM 权限边界为用户设置最大权限，防止他们执行未经授权的文档，无论执行方法如何。
有关 IAM 最佳实践和权限边界的更多信息，请参阅《Amazon Identity and Access Management 用户指南》**中的 [IAM 身份的权限边界](https://docs.amazonaws.cn/IAM/latest/UserGuide/access_policies_boundaries.html)。

**开始前的准备工作**  
必须先完成以下任务才能运行远程文档。
+ 创建 SSM 命令文档并在远程位置保存该文档。有关更多信息，请参阅 [创建 SSM 文档内容](documents-creating-content.md)。
+ 如果打算运行存储在私有 GitHub 存储库中的远程文档，则必须为 GitHub 安全访问令牌创建 Systems Manager `SecureString` 参数。通过 SSH 手动传递令牌无法访问私有 GitHub 存储库中的远程文档。该访问令牌必须作为 Systems Manager `SecureString` 参数传递。有关创建 `SecureString` 参数的更多信息，请参阅 [在 Systems Manager 中创建 Parameter Store 参数](sysman-paramstore-su-create.md)。

## 运行远程文档（控制台）
<a name="documents-running-remote-github-s3-console"></a>

**运行远程文档**

1. 访问 [https://console.aws.amazon.com/systems-manager/](https://console.amazonaws.cn/systems-manager/)，打开 Amazon Systems Manager 控制台。

1. 在导航窗格中，请选择 **Run Command**。

1. 选择 **Run command（运行命令）**。

1. 在 **文档**列表中，选择 **`AWS-RunDocument`**。

1. 在 **命令参数** 中，对于 **源类型**，请选择一个选项。
   + 如果选择 **GitHub**，则采用以下格式指定**源信息**信息：

     ```
     {
         "owner": "owner_name",
         "repository": "repository_name",
         "path": "path_to_document",
         "getOptions":"branch:branch_name",
         "tokenInfo": "{{ssm-secure:secure-string-token}}"
     }
     ```

     例如：

     ```
     {
         "owner":"TestUser",
         "repository":"GitHubTestExamples",
         "path":"scripts/python/test-script",
         "getOptions":"branch:exampleBranch",
         "tokenInfo":"{{ssm-secure:my-secure-string-token}}"
     }
     ```
**注意**  
`getOptions` 是用于从分支（而非主分支）或存储库中的特定提交中检索内容的额外选项。如果您在主分支中使用最新提交，则可以省略 `getOptions`。仅当您的 SSM 文档存储在 `master` 以外的分支中时，`branch` 参数才是必需的。  
要使用存储库中特定*提交* 中的 SSM 文档版本，请使用 `commitID` 和 `getOptions`，而不是 `branch`。例如：  

     ```
     "getOptions": "commitID:bbc1ddb94...b76d3bEXAMPLE",
     ```
   + 如果选择 **S3**，则采用以下格式指定**源信息**信息：

     ```
     {"path":"URL_to_document_in_S3"}
     ```

     例如：

     ```
     {"path":"https://s3.amazonaws.com/amzn-s3-demo-bucket/scripts/ruby/mySSMdoc.json"}
     ```
   + 如果选择 **SSMDocument**，则采用以下格式指定**源信息**信息：

     ```
     {"name": "document_name"}
     ```

     例如：

     ```
     {"name": "mySSMdoc"}
     ```

1. 在 **文档参数** 字段中，输入远程 SSM 文档的参数。例如，如果运行 `AWS-RunPowerShell` 文档，则可指定：

   ```
   {"commands": ["date", "echo \"Hello World\""]}
   ```

   如果运行 `AWS-ConfigureAWSPack` 文档中，则可指定：

   ```
   {
      "action":"Install",
      "name":"AWSPVDriver"
   }
   ```

1. 在 **Targets**（目标）部分中，通过指定标签、手动选择实例或边缘设备或指定资源组，选择要在其上运行此操作的托管式节点。
**提示**  
如果未列出您希望看到的托管式节点，请参阅 [排除托管式节点可用性的问题](fleet-manager-troubleshooting-managed-nodes.md) 以获取故障排除技巧。

1. 对于 **Other parameters（其他参数）**：
   + 对于 **Comment（注释）**，请输入有关此命令的信息。
   + 对于 **Timeout (seconds) (超时 (秒))**，请指定在整个命令执行失败之前系统等待的秒数。

1. 对于 **Rate control（速率控制）**：
   + 对于 **Concurrency**（并发），请指定要同时运行该命令的托管式节点的数量或百分比。
**注意**  
如果您通过指定应用于托管式节点的标签或指定 Amazon Resource Groups 来选择目标，但不确定有多少个托管式节点已被设为目标，则可通过指定百分比来限制可同时运行该文档的目标的数量。
   + 对于 **Error threshold**（错误阈值），请指定当命令在一定数量或百分比的节点上失败后，何时在其他托管式节点上停止运行该命令。例如，如果您指定三个错误，Systems Manager 将在收到第四个错误时停止发送该命令。仍在处理该命令的托管式节点也可能发送错误。

1. （可选）对于 **输出选项**，要将命令输出保存到文件，请选中 **将命令输出写入 S3 存储桶** 框。在输入框中输入存储桶和前缀（文件夹）名称。
**注意**  
授予将数据写入 S3 存储桶的能力的 S3 权限，是分配给实例的实例配置文件（适用于 EC2 实例）或 IAM 服务角色（混合激活的计算机）的权限，而不是执行此任务的 IAM 用户的权限。有关更多信息，请参阅[配置 Systems Manager 所需的实例权限](setup-instance-permissions.md)或[为混合环境创建 IAM 服务角色](hybrid-multicloud-service-role.md)。此外，如果指定的 S3 存储桶位于不同的 Amazon Web Services 账户 中，请确保与该托管式节点关联的实例配置文件或 IAM 服务角色具有写入该存储桶的所需权限。

1. 在 **SNS 通知**部分，如果需要发送有关命令执行状态的通知，请选中 **Enable SNS notifications（启用 SNS 通知）**复选框。

   有关为 Run Command 配置 Amazon SNS 通知的更多信息，请参阅 [使用 Amazon SNS 通知监控 Systems Manager 状态更改](monitoring-sns-notifications.md)。

1. 选择 **Run（运行）**。

**注意**  
有关在使用 Run Command 调用脚本时重启服务器和实例的信息，请参阅 [运行命令时处理重启问题](send-commands-reboot.md)。

# 共享 SSM 文档
<a name="documents-ssm-sharing"></a>

您可以与同一个 Amazon Web Services 区域 中的账户私下或公开共享 Amazon Systems Manager (SSM) 文档。要私下共享文档，请修改文档权限并允许特定个人根据其 Amazon Web Services 账户 ID 访问文档。要公开共享 SSM 文档，请修改文档权限并指定 `All` 。不能同时公开和私下共享文档。

**警告**  
请仅使用从可信来源获取的共享 SSM 文档。使用任何共享文档时，请务必在使用前仔细查看文件内容，了解它会如何更改您的实例配置。有关共享文档最佳实践的更多信息，请参阅 [共享 SSM 文档的最佳做法](#best-practices-shared)。

**限制**  
在开始使用 SSM 文档时，请注意下列限制。
+ 仅所有者可共享文档。
+ 您必须先停止共享文档，然后才能删除它。有关更多信息，请参阅 [修改共享 SSM 文档的权限](#modify-permissions-shared)。
+ 您最多可与 1000 个 Amazon Web Services 账户 共享一个文档。您可以在 [Amazon Web Services 支持 中心](https://console.amazonaws.cn/support/home#/case/create?issueType=service-limit-increase)中请求提高该限制。对于**限制类型**，选择 *EC2 Systems Manager * 并描述您的请求理由。
+ 您可公开共享最多 5 个 SSM 文档。您可以在 [Amazon Web Services 支持支持中心](https://console.amazonaws.cn/support/home#/case/create?issueType=service-limit-increase)中请求提高该限制。对于**限制类型**，选择 *EC2 Systems Manager* 并描述您的请求理由。
+ 文档只能与同一个 Amazon Web Services 区域 中的其他账户共享。不支持跨区域共享。

**重要**  
在 Systems Manager 中，*Amazon 拥有的* SSM 文档是由 Amazon Web Services 自己创建和管理的文档。*Amazon 拥有的*文档在文档名称中包含 `AWS-*` 之类的前缀。文档的所有者被视为 Amazon，而不是 Amazon 内的特定用户账户。这些文档可供所有人公开使用。

有关 Systems Manager Service Quotas 的更多信息，请参阅 [Amazon Systems ManagerService Quotas ](https://docs.amazonaws.cn/general/latest/gr/ssm.html#limits_ssm)。

**Topics**
+ [

## 共享 SSM 文档的最佳做法
](#best-practices-shared)
+ [

## 阻止 SSM 文档的公开共享
](#block-public-access)
+ [

## 共享 SSM 文档
](#ssm-how-to-share)
+ [

## 修改共享 SSM 文档的权限
](#modify-permissions-shared)
+ [

## 使用共享 SSM 文档
](#using-shared-documents)

## 共享 SSM 文档的最佳做法
<a name="best-practices-shared"></a>

在共享或使用共享文档之前，请阅读以下指南。

**删除敏感信息**  
请仔细审查您的 Amazon Systems Manager (SSM) 文档并删除任何敏感信息。例如，请确保文档不包含您的 Amazon 凭证。如果您与特定个人共享文档，这些用户可查看文档中的信息。如果您公开共享文档，则任何人都可查看文档中的信息。

**阻止文档的公开共享**  
查看您账户中所有公开共享的 SSM 文档，并确认是否要继续共享这些文档。要停止与公众共享文档，必须按照本主题 [修改共享 SSM 文档的权限](#modify-permissions-shared) 部分所述来修改文档权限设置。启用“阻止公开共享”设置不会影响您当前与公众共享的任何文档。除非您的应用场景需要您与公众共享文档，否则建议在 Systems Manager 文档控制台的**首选项**部分，为您的 SSM 文档开启阻止公开共享设置。启用此设置可防止对 SSM 文档进行不需要的访问。阻止公开共享设置是一个帐户级别设置，每个 Amazon Web Services 区域 的设置可能不同。

**使用 IAM 信任策略限制 Run Command 操作**  
为将有权访问该文档的用户创建限制性 Amazon Identity and Access Management（IAM）policy。IAM policy 确定用户可在 Amazon Elastic Compute Cloud（Amazon EC2）控制台中或通过使用 Amazon Command Line Interface（Amazon CLI）或 Amazon Tools for Windows PowerShell 调用 `ListDocuments` 查看哪些 SSM 文档。该策略还限制用户可使用 SSM 文档执行的操作。您可创建限制性策略，以便用户只能使用特定文档。有关更多信息，请参阅 [客户管理型策略示例](security_iam_id-based-policy-examples.md#customer-managed-policies)。

**使用共享 SSM 文档时要小心**  
审查与您共享的每个文档（特别是公开文档）的内容，以了解将在您的实例上运行的命令。一个文档在运行后可能会有意或无意具有负面影响。如果文档引用外部网络，请在使用文档前审查外部源。

**使用文档哈希发送命令**  
在共享文档时，系统将创建 Sha-256 哈希并将其分配给文档。系统还将保存文档内容的快照。使用共享文档发送命令时，您可在命令中指定哈希以确保下列条件为 true：  
+ 您正在从正确的 Systems Manager 文档运行命令
+ 在与您共享之后文档内容未更改。
如果哈希与指定文档不匹配，或者共享文档的内容已更改，则命令将返回 `InvalidDocument` 异常。哈希无法验证来自外部位置的文档内容。

**使用插值参数来增强安全性**  
对于 SSM 文档中的 `String` 类型参数，可使用参数和值 `interpolationType": "ENV_VAR` 增强对命令注入攻击的防御能力，方法是将参数输入视为字符串文本值，而非可能的可执行命令。在这种情况下，代理会创建一个包含参数值的环境变量 `SSM_parameter-name`。我们建议对现有所有包含 `String` 类型参数的 SSM 文档进行更新，以纳入 `"interpolationType": "ENV_VAR"`。有关更多信息，请参阅 [编写 SSM 文档内容](documents-creating-content.md#writing-ssm-doc-content)。

## 阻止 SSM 文档的公开共享
<a name="block-public-access"></a>

开始前，请查看您 Amazon Web Services 账户 中所有公开共享的 SSM 文档，并确认是否要继续共享它们。要停止与公众共享 SSM 文档，必须按照本主题 [修改共享 SSM 文档的权限](#modify-permissions-shared) 部分所述修改文档权限设置。启用“阻止公开共享”设置不会影响您当前与公众共享的任何 SSM 文档。启用“阻止公开共享”设置后，您将无法与公众共享任何其他 SSM 文档。

除非您的应用场景需要您与公众共享文档，否则我们建议为您的 SSM 文档开启阻止公开共享设置。启用此设置可防止对 SSM 文档进行不需要的访问。阻止公开共享设置是一个帐户级别设置，每个 Amazon Web Services 区域 的设置可能不同。完成以下任务以阻止您目前正在共享的任何 SSM 文档的公开共享。

### 阻止公开共享（控制台）
<a name="block-public-access-console"></a>

**要阻止 SSM 文档的公开共享**

1. 访问 [https://console.aws.amazon.com/systems-manager/](https://console.amazonaws.cn/systems-manager/)，打开 Amazon Systems Manager 控制台。

1. 在导航窗格中，选择**文档**。

1. 选择**首选项**，然后在**阻止公开共享**部分中选择**编辑**。

1. 选择**阻止公开共享**复选框，然后选择**保存**。

### 阻止公开共享（命令行）
<a name="block-public-access-cli"></a>

打开 Amazon Command Line Interface (Amazon CLI）或 Amazon Tools for Windows PowerShell 并运行以下命令以阻止 SSM 文档的公开共享。

------
#### [ Linux & macOS ]

```
aws ssm update-service-setting  \
    --setting-id /ssm/documents/console/public-sharing-permission \
    --setting-value Disable \
    --region 'The Amazon Web Services 区域 you want to block public sharing in'
```

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

```
aws ssm update-service-setting ^
    --setting-id /ssm/documents/console/public-sharing-permission ^
    --setting-value Disable ^
    --region "The Amazon Web Services 区域 you want to block public sharing in"
```

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

```
Update-SSMServiceSetting `
    -SettingId /ssm/documents/console/public-sharing-permission `
    -SettingValue Disable `
    –Region The Amazon Web Services 区域 you want to block public sharing in
```

------

使用以下命令确认设置值已更新。

------
#### [ Linux & macOS ]

```
aws ssm get-service-setting   \
    --setting-id /ssm/documents/console/public-sharing-permission \
    --region The Amazon Web Services 区域 you blocked public sharing in
```

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

```
aws ssm get-service-setting  ^
    --setting-id /ssm/documents/console/public-sharing-permission ^
    --region "The Amazon Web Services 区域 you blocked public sharing in"
```

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

```
Get-SSMServiceSetting `
    -SettingId /ssm/documents/console/public-sharing-permission `
    -Region The Amazon Web Services 区域 you blocked public sharing in
```

------

### 使用 IAM 限制访问阻止公开共享
<a name="block-public-access-changes-iam"></a>

您可以创建 Amazon Identity and Access Management (IAM) 策略，这些策略限制用户修改阻止公开共享设置。这可以防止用户允许对 SSM 文档进行不需要的访问。

以下是一个 IAM policy 示例，该策略阻止用户更新阻止公开共享设置。要使用此示例，您必须将示例 Amazon Web Services 账户 ID 替换为您自己的账户 ID。

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Deny",
            "Action": "ssm:UpdateServiceSetting",
            "Resource": "arn:aws:ssm:*:444455556666:servicesetting/ssm/documents/console/public-sharing-permission"
        }
    ]
}
```

------

## 共享 SSM 文档
<a name="ssm-how-to-share"></a>

您可以通过 Systems Manager 控制台共享 Amazon Systems Manager (SSM) 文档。从控制台共享文档时，只能共享文档的默认版本。您还可以通过使用 Amazon Command Line Interface (Amazon CLI)、 Amazon Tools for Windows PowerShell 或 Amazon SDK 调用 `ModifyDocumentPermission` API 操作，以编程方式共享 SSM 文档。在共享文档之前，获取要与之共享文档的人的 Amazon Web Services 账户 账户 ID。您将在共享文档时指定这些账户 ID。

### 共享文档（控制台）
<a name="share-using-console"></a>

1. 访问 [https://console.aws.amazon.com/systems-manager/](https://console.amazonaws.cn/systems-manager/)，打开 Amazon Systems Manager 控制台。

1. 在导航窗格中，选择**文档**。

1. 在文档列表中，选择要共享的文档，然后选择**查看详细信息**。在**权限**选项卡中，确保您是文档所有者。只有文档所有者才可共享文档。

1. 选择**编辑**。

1. 要公开共享命令，请选择**公开**，然后选择**保存**。要私下共享命令，请选择**私有**，输入 Amazon Web Services 账户 ID，选**择添加权限**，然后选择**保存**。

### 共享文档（命令行）
<a name="share-using-cli"></a>

以下过程要求您为命令行会话指定 Amazon Web Services 区域。

1. 在本地计算机上打开 Amazon CLI 或 Amazon Tools for Windows PowerShell 并运行以下命令来指定凭证。

   在下面的命令中，将 *region* 替换为您自己的信息。有关支持的 *region* 值的列表，请参阅《Amazon Web Services 一般参考》**中的 [Systems Manager service endpoints](https://docs.amazonaws.cn/general/latest/gr/ssm.html#ssm_region) 的 **Region** 列。

------
#### [ Linux & macOS ]

   ```
   aws config
   
   AWS Access Key ID: [your key]
   AWS Secret Access Key: [your key]
   Default region name: region
   Default output format [None]:
   ```

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

   ```
   aws config
   
   AWS Access Key ID: [your key]
   AWS Secret Access Key: [your key]
   Default region name: region
   Default output format [None]:
   ```

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

   ```
   Set-AWSCredentials –AccessKey your key –SecretKey your key
   Set-DefaultAWSRegion -Region region
   ```

------

1. 使用以下命令列出可供您使用的所有 SSM 文档。此列表包括您已创建的文档和与您共享的文档。

------
#### [ Linux & macOS ]

   ```
   aws ssm list-documents
   ```

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

   ```
   aws ssm list-documents
   ```

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

   ```
   Get-SSMDocumentList
   ```

------

1. 使用以下命令获取特定文档。

------
#### [ Linux & macOS ]

   ```
   aws ssm get-document \
       --name document name
   ```

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

   ```
   aws ssm get-document ^
       --name document name
   ```

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

   ```
   Get-SSMDocument `
       –Name document name
   ```

------

1. 使用以下命令获取文档的描述。

------
#### [ Linux & macOS ]

   ```
   aws ssm describe-document \
       --name document name
   ```

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

   ```
   aws ssm describe-document ^
       --name document name
   ```

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

   ```
   Get-SSMDocumentDescription `
       –Name document name
   ```

------

1. 使用以下命令查看文档的权限。

------
#### [ Linux & macOS ]

   ```
   aws ssm describe-document-permission \
       --name document name \
       --permission-type Share
   ```

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

   ```
   aws ssm describe-document-permission ^
       --name document name ^
       --permission-type Share
   ```

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

   ```
   Get-SSMDocumentPermission `
       –Name document name `
       -PermissionType Share
   ```

------

1. 使用以下命令修改文档的权限并共享文档。您必须是文档的所有者才能编辑权限。或者，对于与特定 Amazon Web Services 账户 ID 共享的文档，您可以使用 `--shared-document-version` 参数指定要共享的文档的版本。如果您不指定版本，系统将共享文档的`Default`版本。如果您公开（与 `all`）共享文档，则默认共享指定文档的所有版本。以下示例命令根据特定个人的 Amazon Web Services 账户 ID 与该个人私下共享文档。

------
#### [ Linux & macOS ]

   ```
   aws ssm modify-document-permission \
       --name document name \
       --permission-type Share \
       --account-ids-to-add Amazon Web Services 账户 ID
   ```

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

   ```
   aws ssm modify-document-permission ^
       --name document name ^
       --permission-type Share ^
       --account-ids-to-add Amazon Web Services 账户 ID
   ```

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

   ```
   Edit-SSMDocumentPermission `
       –Name document name `
       -PermissionType Share `
       -AccountIdsToAdd Amazon Web Services 账户 ID
   ```

------

1. 使用以下命令公开共享文档。
**注意**  
如果您公开（与 `all`）共享文档，则默认共享指定文档的所有版本。

------
#### [ Linux & macOS ]

   ```
   aws ssm modify-document-permission \
       --name document name \
       --permission-type Share \
       --account-ids-to-add 'all'
   ```

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

   ```
   aws ssm modify-document-permission ^
       --name document name ^
       --permission-type Share ^
       --account-ids-to-add "all"
   ```

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

   ```
   Edit-SSMDocumentPermission `
       -Name document name `
       -PermissionType Share `
       -AccountIdsToAdd ('all')
   ```

------

## 修改共享 SSM 文档的权限
<a name="modify-permissions-shared"></a>

如果您共享一条命令，则在您删除对 Amazon Systems Manager (SSM) 文档的访问权限或删除 SSM 文档之前，用户可查看和使用该命令。但是，只要文档已共享，您就无法删除它。您必须先停止共享，然后再删除它。

### 停止共享文档（控制台）
<a name="unshare-using-console"></a>

**停止共享文档**

1. 访问 [https://console.aws.amazon.com/systems-manager/](https://console.amazonaws.cn/systems-manager/)，打开 Amazon Systems Manager 控制台。

1. 在导航窗格中，选择**文档**。

1. 在文档列表中，选择要停止共享的文档，然后选择**详细信息**。在**权限**部分中，确认自己是文档所有者。只有文档所有者才可停止共享文档。

1. 选择**编辑**。

1. 选择 **X** 以删除不应再具有此命令的访问权限的 Amazon Web Services 账户 ID，然后选择**保存**。

### 停止共享文档（命令行）
<a name="unshare-using-cli"></a>

在本地计算机上打开 Amazon CLI 或 Amazon Tools for Windows PowerShell，然后运行以下命令停止共享命令。

------
#### [ Linux & macOS ]

```
aws ssm modify-document-permission \
    --name document name \
    --permission-type Share \
    --account-ids-to-remove 'Amazon Web Services 账户 ID'
```

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

```
aws ssm modify-document-permission ^
    --name document name ^
    --permission-type Share ^
    --account-ids-to-remove "Amazon Web Services 账户 ID"
```

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

```
Edit-SSMDocumentPermission `
    -Name document name `
    -PermissionType Share `
    –AccountIdsToRemove Amazon Web Services 账户 ID
```

------

## 使用共享 SSM 文档
<a name="using-shared-documents"></a>

共享 Amazon Systems Manager (SSM) 文档时，系统将生成一个 Amazon Resource Name (ARN) 并将其分配给命令。如果您从 Systems Manager 控制台选择并运行某个共享文档，则不会看到此 ARN。但如果您要使用 Systems Manager 控制台以外的方法运行共享 SSM 文档，则必须在 `DocumentName` 请求参数中指定文档的完整 ARN。当您运行列出文档的命令时，将为您显示 SSM 文档的完整 ARN。

**注意**  
您无需为 Amazon 公有文档（以 `AWS-*` 开头的文档）或您拥有的文档指定 ARN。

### 使用共享 SSM 文档（命令行）
<a name="using-shared-documents-cli"></a>

 **列出所有公有 SSM 文档** 

------
#### [ Linux & macOS ]

```
aws ssm list-documents \
    --filters Key=Owner,Values=Public
```

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

```
aws ssm list-documents ^
    --filters Key=Owner,Values=Public
```

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

```
$filter = New-Object Amazon.SimpleSystemsManagement.Model.DocumentKeyValuesFilter
$filter.Key = "Owner"
$filter.Values = "Public"

Get-SSMDocumentList `
    -Filters @($filter)
```

------

 **列出已与您共享的私有 SSM 文档** 

------
#### [ Linux & macOS ]

```
aws ssm list-documents \
    --filters Key=Owner,Values=Private
```

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

```
aws ssm list-documents ^
    --filters Key=Owner,Values=Private
```

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

```
$filter = New-Object Amazon.SimpleSystemsManagement.Model.DocumentKeyValuesFilter
$filter.Key = "Owner"
$filter.Values = "Private"

Get-SSMDocumentList `
    -Filters @($filter)
```

------

 **列出可供您使用的所有 SSM 文档** 

------
#### [ Linux & macOS ]

```
aws ssm list-documents
```

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

```
aws ssm list-documents
```

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

```
Get-SSMDocumentList
```

------

 **获取有关已与您共享的 SSM 文档的信息** 

------
#### [ Linux & macOS ]

```
aws ssm describe-document \
    --name arn:aws:ssm:us-east-2:12345678912:document/documentName
```

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

```
aws ssm describe-document ^
    --name arn:aws:ssm:us-east-2:12345678912:document/documentName
```

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

```
Get-SSMDocumentDescription `
    –Name arn:aws:ssm:us-east-2:12345678912:document/documentName
```

------

 **运行共享的 SSM 文档** 

------
#### [ Linux & macOS ]

```
aws ssm send-command \
    --document-name arn:aws:ssm:us-east-2:12345678912:document/documentName \
    --instance-ids ID
```

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

```
aws ssm send-command ^
    --document-name arn:aws:ssm:us-east-2:12345678912:document/documentName ^
    --instance-ids ID
```

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

```
Send-SSMCommand `
    –DocumentName arn:aws:ssm:us-east-2:12345678912:document/documentName `
    –InstanceIds ID
```

------

# 搜索 SSM 文档
<a name="ssm-documents-searching"></a>

您可以使用自由文本搜索或基于筛选器的搜索在 Amazon Systems Manager (SSM) 文档存储中搜索 SSM 文档。您还可以收藏文档，以帮助您查找常用 SSM 文档。以下部分介绍如何使用这些功能。

## 使用自由文本搜索
<a name="ssm-documents-searching-free-text"></a>

Systems Manager **文档**页面上的搜索框支持自由文本搜索。自由文本搜索会将您输入的一个或多个搜索词与每个 SSM 文档中的文档名称进行比较。如果输入单个搜索词，例如 **ansible**，然后 Systems Manager 返回发现此术语的所有 SSM 文档。如果输入多个搜索词，Systems Manager 将使用 `OR` 网页。例如，如果指定 **ansible** 和 **linux**，然后搜索将返回名称中包含*任一*关键字的所有文档。

如果输入自由文本搜索词并选择搜索选项（例如**平台类型**），则搜索将使用 `AND` 语句，并返回所有名称中包含关键字和指定平台类型的文档。

**注意**  
请注意以下有关自由文本搜索的详细信息。  
搜索*不*区分大小写。
搜索词至少需要三个字符，且最多包含 20 个字符。
自由文本搜索最多可接受五个搜索词。
如果在搜索词之间输入空格，系统会在搜索时包含空格。
您可以将自由文本搜索与其他搜索选项，如：**文档类型**或者**平台类型**结合使用。
**文档名称前缀**过滤器和自由文本搜索不能一起使用，它们是相互排斥的。

**搜索 SSM 文档**

1. 访问 [https://console.aws.amazon.com/systems-manager/](https://console.amazonaws.cn/systems-manager/)，打开 Amazon Systems Manager 控制台。

1. 在导航窗格中，选择**文档**。

1. 在搜索框中输入搜索词，然后按输入。

### 使用 Amazon CLI 执行自由文本文档搜索
<a name="ssm-documents-searching-free-text-cli"></a>

**使用 CLI 执行自由文本文档搜索**

1. 安装并配置 Amazon Command Line Interface（Amazon CLI）（如果尚未执行该操作）。

   有关信息，请参阅[安装或更新 Amazon CLI 的最新版本](https://docs.amazonaws.cn/cli/latest/userguide/getting-started-install.html)。

1. 要使用单个术语执行自由文本文档搜索，请运行以下命令。在此命令中，用自己的信息替换*搜索术语*。

   ```
   aws ssm list-documents --filters Key="SearchKeyword",Values="search_term"
   ```

   以下为示例。

   ```
   aws ssm list-documents --filters Key="SearchKeyword",Values="aws-asg" --region us-east-2
   ```

   要使用多个术语进行搜索，可创建 `AND` 语句，运行以下命令。在此命令中，用自己的信息替换*搜索术语 1* 和*搜索术语 2*。

   ```
   aws ssm list-documents --filters Key="SearchKeyword",Values="search_term_1","search_term_2","search_term_3" --region us-east-2
   ```

   以下为示例。

   ```
   aws ssm list-documents --filters Key="SearchKeyword",Values="aws-asg","aws-ec2","restart" --region us-east-2
   ```

## 使用筛选条件
<a name="ssm-documents-searching-filters"></a>

Systems Manager **文档**页面会在您选择搜索框时自动显示以下筛选条件。
+ 文档名称前缀
+ 平台类型
+ 文档类型
+ 标签键

![\[“SSM 文档”页面上的筛选选项。\]](http://docs.amazonaws.cn/systems-manager/latest/userguide/images/ssm-documents-filters-1.png)


您可以使用单个筛选条件搜索 SSM 文档。如果要返回一组更具体的 SSM 文档，可以应用多个筛选条件。下面是一个搜索示例，使用**平台类型**和**文档名称前缀**筛选条件。

![\[在 “SSM 文档” 页面上应用多个筛选器选项。\]](http://docs.amazonaws.cn/systems-manager/latest/userguide/images/ssm-documents-filters-2.png)


如果应用多个筛选条件，Systems Manager 会根据您选择的筛选条件创建不同的搜索语句：
+ 如果您多次应用*相同*的筛选条件，例如**文档名称前缀**，然后 Systems Manager 将使用 `OR` 语句进行搜索。例如，如果您指定一个**文档名称前缀**=**AWS** 和第二个筛选条件**文档名称前缀**=**Lambda**，然后搜索将返回带有前缀 “`AWS`” 的所有文档以及带有前缀 “`Lambda`” 的所有文档。
+ 如果您应用*其他*筛选条件，例如 **Document name prefix**（文档名称前缀）和 **Platform types**（平台类型），则 Systems Manager 将使用 `AND` 语句进行搜索。例如，如果指定 **Document name prefix**（文档名称前缀）=**AWS** 筛选条件和 **Platform types**（平台类型）=**Linux** 筛选条件，则搜索会返回特定于 Linux 平台的带有前缀“`AWS`”的所有文档。

**注意**  
使用筛选条件区分大小写。

## 将文档添加到您的收藏夹
<a name="favorite-documents"></a>

为帮助您查找常用 SSM 文档，可将文档添加到您的收藏夹。每种文档类型、每种 Amazon Web Services 账户 和 Amazon Web Services 区域 最多可以收藏 20 份文档。您可以从文档 Amazon Web Services 管理控制台 中选择、修改和查看您的收藏夹。以下过程介绍如何选择、修改和查看您的收藏夹。

**收藏 SSM 文档**

1. 访问 [https://console.aws.amazon.com/systems-manager/](https://console.amazonaws.cn/systems-manager/)，打开 Amazon Systems Manager 控制台。

1. 在导航窗格中，选择**文档**。

1. 选择您要收藏的文档名称旁边的星形图标。

**从您的收藏夹中移除 SSM 文档**

1. 访问 [https://console.aws.amazon.com/systems-manager/](https://console.amazonaws.cn/systems-manager/)，打开 Amazon Systems Manager 控制台。

1. 在导航窗格中，选择**文档**。

1. 取消选择要从您的收藏中移除的文档名称旁边的星形图标。

**从文档 Amazon Web Services 管理控制台 中查看您的收藏夹**

1. 访问 [https://console.aws.amazon.com/systems-manager/](https://console.amazonaws.cn/systems-manager/)，打开 Amazon Systems Manager 控制台。

1. 在导航窗格中，选择**文档**。

1. 选择**收藏夹**选项卡。

# 参数处理问题的疑难解答
<a name="parameter-troubleshooting"></a>

## 常见参数处理问题
<a name="common-parameter-issues"></a>

**执行期间环境变量不可用**  
**问题：**找不到环境变量 (`SSM_parameter-name`)，命令失败。  
**可能的原因：**  
+ SSM Agent 版本不支持环境变量插值
+ `interpolationType` 未设置为 `ENV_VAR`
+ 参数名称与预期的环境变量名称不匹配
**解决方案：**  
+ 验证 SSM Agent 版本是否为 3.3.2746.0 或更高
+ 为旧版代理添加回退逻辑：

  ```
  if [ -z "${SSM_parameterName+x}" ]; then
      export SSM_parameterName="{{parameterName}}"
  fi
  ```

**参数值包含特殊字符**  
**问题：**参数值包含空格、引号或其他特殊字符时会导致命令失败。  
**解决方案：**  
+ 引用环境变量时，请使用正确的引号：

  ```
  # Correct
  echo "$SSM_parameter-name"
  
  # Incorrect
  echo $SSM_parameter-name
  ```
+ 添加输入验证，使用 `allowedPattern` 来限制特殊字符

**跨平台行为不一致**  
**问题：**在 Linux 和 Windows Server 系统中，参数处理方式有所不同。  
**解决方案：**  
+ 请使用特定平台的环境变量语法：

  ```
  # PowerShell
  $env:SSM_parameter-name
  
  # Bash
  $SSM_parameter-name
  ```
+ 在文档中使用特定平台的前提条件检查

**参数值未正确转义**  
**问题：**尽管使用了环境变量插值，但仍存在命令注入的漏洞。  
**解决方案：**  
+ 在命令中包含参数值时，务必使用正确的转义：

  ```
  # Correct
  mysql_command="mysql -u \"$SSM_username\" -p\"$SSM_password\""
  
  # Incorrect
  mysql_command="mysql -u $SSM_username -p$SSM_password"
  ```

## 参数验证提示
<a name="parameter-validation"></a>

使用这些方法验证参数处理：

1. 测试环境变量的可用性：

   ```
   #!/bin/bash
   # Print all SSM_ environment variables
   env | grep ^SSM_
   
   # Test specific parameter
   if [ -n "$SSM_parameter" ]; then
       echo "Parameter is available"
   else
       echo "Parameter is not available"
   fi
   ```

1. 验证参数模式：

   ```
   parameters:
     myParameter:
       type: String
       allowedPattern: "^[a-zA-Z0-9_-]+$"
       description: "Test this pattern with sample inputs"
   ```

1. 包含错误处理：

   ```
   if [[ ! "$SSM_parameter" =~ ^[a-zA-Z0-9_-]+$ ]]; then
       echo "Parameter validation failed"
       exit 1
   fi
   ```