

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

# 教程：使用 AWS CLI 创建和管理维护时段
<a name="maintenance-window-tutorial-cli"></a>

此部分包含的教程可帮助您了解如何使用 AWS Command Line Interface (AWS CLI) 来执行以下操作：
+ 创建和配置维护时段
+ 查看有关维护时段的信息
+ 查看有关维护时段任务和任务执行的信息
+ 更新维护时段
+ 删除维护时段

**跟踪资源 ID**  
在您完成这些 AWS CLI 教程中的任务之后，跟踪您运行的命令生成的资源 ID。您可以将其用作后续命令的输入。例如，当您创建维护时段时，系统会向您提供以下格式的维护时段 ID。

```
{
   "WindowId":"mw-0c50858d01EXAMPLE"
}
```

记下以下系统生成的 ID，因为本节中的教程会使用它们：
+ `WindowId`
+ `WindowTargetId`
+ `WindowTaskId`
+ `WindowExecutionId`
+ `TaskExecutionId`
+ `InvocationId`
+ `ExecutionId`

您还需要计划在这些教程中使用的 EC2 实例的 ID。例如：`i-02573cafcfEXAMPLE`

**Topics**
+ [教程：使用 AWS CLI 创建和配置维护时段](maintenance-windows-cli-tutorials-create.md)
+ [教程：使用 AWS CLI 查看有关维护时段的信息](maintenance-windows-cli-tutorials-describe.md)
+ [教程：查看有关任务和使用 AWS CLI 执行任务的信息](mw-cli-tutorial-task-info.md)
+ [教程：使用 AWS CLI 更新维护时段](maintenance-windows-cli-tutorials-update.md)
+ [教程：使用 AWS CLI 删除维护时段](mw-cli-tutorial-delete-mw.md)

# 教程：使用 AWS CLI 创建和配置维护时段
<a name="maintenance-windows-cli-tutorials-create"></a>

本教程演示如何使用 AWS Command Line Interface (AWS CLI) 创建和配置维护时段、其目标和任务。完成教程的主要路径由几个简单步骤组成。您可以创建单个维护时段，确定单个目标，并为要运行的维护时段建立一个简单任务。在此过程中，我们提供了您可用于尝试更为复杂场景的信息。

在按照本教程中的步骤操作时，请将以斜体*红色*文本显示的值替换为您自己的选项和 ID。例如，请将维护时段 ID *mw-0c50858d01EXAMPLE* 和实例 ID *i-02573cafcfEXAMPLE* 替换为您创建的资源的 ID。

**Topics**
+ [步骤 1：使用 AWS CLI 创建维护时段](mw-cli-tutorial-create-mw.md)
+ [步骤 2：使用 AWS CLI 将目标节点注册到维护时段](mw-cli-tutorial-targets.md)
+ [步骤 3：使用 AWS CLI 向维护时段注册任务](mw-cli-tutorial-tasks.md)

# 步骤 1：使用 AWS CLI 创建维护时段
<a name="mw-cli-tutorial-create-mw"></a>

在此步骤中，您将创建维护时段并指定其基本选项，如名称、计划和持续时间。在后面的步骤中，您选择它将更新的实例和运行的任务。

在我们的示例中，您将创建一个每 5 分钟运行的维护时段。通常您不会如此频繁地运行维护时段。不过，此速率可让您快速看到教程的结果。在任务成功运行之后，我们将向您展示如何改为较低频率的速率。

**注意**  
有关维护时段的各种计划相关选项如何相互关联的说明，请参阅 [维护时段计划和活动期间选项](maintenance-windows-schedule-options.md)。  
有关使用 `--schedule` 选项的更多信息，请参阅 [参考：适用于 Systems Manager 的 Cron 和 Rate 表达式](reference-cron-and-rate-expressions.md)。

**要使用 AWS CLI 创建维护时段**

1. 在您的本地计算机上打开 AWS Command Line Interface (AWS CLI) 并运行以下命令，创建执行以下任务的维护时段：
   + 每五分钟运行一次，持续时间最长两小时（根据需要）。
   + 在维护时段运行结束后的一小时内，阻止新任务启动。
   + 允许无关联的目标（您未注册到维护时段的实例）。
   + 通过使用自定义标签指示其创建方计划在本教程中使用它。

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

   ```
   aws ssm create-maintenance-window \
       --name "My-First-Maintenance-Window" \
       --schedule "rate(5 minutes)" \
       --duration 2 \
       --cutoff 1 \
       --allow-unassociated-targets \
       --tags "Key=Purpose,Value=Tutorial"
   ```

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

   ```
   aws ssm create-maintenance-window ^
       --name "My-First-Maintenance-Window" ^
       --schedule "rate(5 minutes)" ^
       --duration 2 ^
       --cutoff 1 ^
       --allow-unassociated-targets ^
       --tags "Key"="Purpose","Value"="Tutorial"
   ```

------

   系统返回类似于以下内容的信息。

   ```
   {
      "WindowId":"mw-0c50858d01EXAMPLE"
   }
   ```

1. 现在，运行以下命令来查看有关此维护时段以及您的账户中已有的任何其他维护时段的详细信息。

   ```
   aws ssm describe-maintenance-windows
   ```

   系统返回类似于以下内容的信息。

   ```
   {
      "WindowIdentities":[
         {
               "WindowId": "mw-0c50858d01EXAMPLE",
               "Name": "My-First-Maintenance-Window",
               "Enabled": true,
               "Duration": 2,
               "Cutoff": 1,
               "NextExecutionTime": "2019-05-11T16:46:16.991Z"
         }
      ]
   }
   ```

继续[步骤 2：使用 AWS CLI 将目标节点注册到维护时段](mw-cli-tutorial-targets.md)。

# 步骤 2：使用 AWS CLI 将目标节点注册到维护时段
<a name="mw-cli-tutorial-targets"></a>

在此步骤中，您使用新的维护时段注册目标。在这种情况下，您需指定维护时段运行时要更新的节点。

有关使用节点 ID 一次注册多个节点的示例、使用标签来标识多个节点的示例，以及将资源组指定为目标的示例，请参阅 [示例：向维护时段注册目标](mw-cli-tutorial-targets-examples.md)。

**注意**  
您应该已经创建了要在此步骤中使用的 Amazon Elastic Compute Cloud (Amazon EC2) 实例，如 [Maintenance Windows 教程先决条件](maintenance-windows-tutorials.md)中所述。

**要使用 AWS CLI 将目标节点注册到维护时段**

1. 在本地计算机上运行以下命令。将每个*示例资源占位符*替换为您自己的信息。

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

   ```
   aws ssm register-target-with-maintenance-window \
       --window-id "mw-0c50858d01EXAMPLE" \
       --resource-type "INSTANCE" \
       --target "Key=InstanceIds,Values=i-02573cafcfEXAMPLE"
   ```

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

   ```
   aws ssm register-target-with-maintenance-window ^
       --window-id "mw-0c50858d01EXAMPLE" ^
       --resource-type "INSTANCE" ^
       --target "Key=InstanceIds,Values=i-02573cafcfEXAMPLE"
   ```

------

   系统返回类似于以下内容的信息。

   ```
   {
      "WindowTargetId":"e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE"
   }
   ```

1. 现在，在本地计算机上运行以下命令，查看有关您的维护时段目标的详细信息。

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

   ```
   aws ssm describe-maintenance-window-targets \
       --window-id "mw-0c50858d01EXAMPLE"
   ```

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

   ```
   aws ssm describe-maintenance-window-targets ^
       --window-id "mw-0c50858d01EXAMPLE"
   ```

------

   系统返回类似于以下内容的信息。

   ```
   {
       "Targets": [
           {
               "WindowId": "mw-0c50858d01EXAMPLE",
               "WindowTargetId": "e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE",
               "ResourceType": "INSTANCE",
               "Targets": [
                   {
                       "Key": "InstanceIds",
                       "Values": [
                           "i-02573cafcfEXAMPLE"
                       ]
                   }
               ]
           }
       ]
   }
   ```

继续[步骤 3：使用 AWS CLI 向维护时段注册任务](mw-cli-tutorial-tasks.md)。

# 示例：向维护时段注册目标
<a name="mw-cli-tutorial-targets-examples"></a>

您可以使用节点 ID 将单个节点注册为目标，如 [步骤 2：使用 AWS CLI 将目标节点注册到维护时段](mw-cli-tutorial-targets.md) 中所示。您还可以使用此页面的命令格式将一个或多个节点注册为目标。

一般情况下，有两种方法用于标识您要用作维护时段目标的节点：指定各个节点和使用资源标签。资源标签方法提供了更多选项，如示例 2-3 中所示。

您也可以指定一个或多个资源组作为维护时段的目标。资源组可包含节点和许多其他类型的受支持的 AWS 资源。接下来的示例 4 和 5 演示如何将资源组添加到您的维护时段目标。

**注意**  
如果将单个维护时段任务注册到多个目标，则其任务调用将按顺序进行，而不是并行发生。如果您的任务必须同时在多个目标上运行，请为每个目标分别注册一个任务，并为每个任务分配相同的优先级。

有关创建和管理资源组的更多信息，请参阅 *AWS Resource Groups 用户指南*中的[什么是资源组？](https://docs.aws.amazon.com/ARG/latest/userguide/resource-groups.html)，以及 *AWS 新闻博客*中的 [AWS 的资源组和标记](https://aws.amazon.com/blogs/aws/resource-groups-and-tagging/)。

有关 Maintenance Windows（AWS Systems Manager 中的一项工具）配额的信息，除了以下示例中指定的内容，另请参阅《Amazon Web Services 一般参考》**中的 [Systems Manager service quotas](https://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm)。

## 示例 1：使用节点 ID 注册多个目标
<a name="mw-target-example-1"></a>

在本地计算机上运行以下命令，使用多个节点的节点 ID 将它们注册为目标。将每个*示例资源占位符*替换为您自己的信息。

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

```
aws ssm register-target-with-maintenance-window \
    --window-id "mw-0c50858d01EXAMPLE" \
    --resource-type "INSTANCE" \
    --target "Key=InstanceIds,Values=i-02573cafcfEXAMPLE,i-0471e04240EXAMPLE,i-07782c72faEXAMPLE"
```

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

```
aws ssm register-target-with-maintenance-window ^
    --window-id "mw-0c50858d01EXAMPLE ^
    --resource-type "INSTANCE" ^
    --target "Key=InstanceIds,Values=i-02573cafcfEXAMPLE,i-0471e04240EXAMPLE,i-07782c72faEXAMPLE
```

------

**建议使用**：在首次将唯一一组节点注册到任何维护时段，并且这些节点*不*共享公用节点标签时最有用。

**配额：**您总共可以为每个维护时段目标指定最多 50 个节点。

## 示例 2：使用应用到节点的资源标签注册目标
<a name="mw-target-example-2"></a>

在本地计算机上运行以下命令，注册所有已使用您分配的键值对标记的节点。将每个*示例资源占位符*替换为您自己的信息。

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

```
aws ssm register-target-with-maintenance-window \
    --window-id "mw-0c50858d01EXAMPLE" \
    --resource-type "INSTANCE" \
    --target "Key=tag:Region,Values=East"
```

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

```
aws ssm register-target-with-maintenance-window ^
    --window-id "mw-0c50858d01EXAMPLE" ^
    --resource-type "INSTANCE" ^
    --target "Key=tag:Region,Values=East"
```

------

**建议使用**：在首次将唯一一组节点注册到任何维护时段，并且这些节点*共享*公用节点标签时最有用。

**配额：**您总共可以为每个目标指定最多 5 个键/值对。如果您指定了多个键/值对，则必须使用您指定的*所有* 标签键和值来标记节点，才能将该节点包含在目标组中。

**注意**  
您可以使用标签键`Patch Group`或`PatchGroup`来标记一组节点并向节点分配通用键值，例如 `my-patch-group`。（如果[在 EC2 实例元数据中允许使用标签](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html#allow-access-to-tags-in-IMDS)，则必须使用 `PatchGroup`，且不能使用空格。）Patch Manager是 Systems Manager 中的一项工具，用于评估节点上的 `Patch Group` 或 `PatchGroup` 键，以便确定适用的补丁基准。如果您的任务将运行 `AWS-RunPatchBaseline` SSM 文档（或传统 `AWS-ApplyPatchBaseline` SSM 文档），则在将目标注册到维护时段时，可以指定相同的`Patch Group`或`PatchGroup`键值对。例如：`--target "Key=tag:PatchGroup,Values=my-patch-group`。这样做可让您使用维护时段，在已经与相同补丁基准关联的一组节点上更新补丁。有关更多信息，请参阅 [补丁组](patch-manager-patch-groups.md)。

## 示例 3：使用一组标签键（无标签值）注册目标
<a name="mw-target-example-3"></a>

在本地计算机上运行以下命令，注册所有已分配有一个或多个标签键的节点（不考虑其键值）。将每个*示例资源占位符*替换为您自己的信息。

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

```
aws ssm register-target-with-maintenance-window \
    --window-id "mw-0c50858d01EXAMPLE" \
    --resource-type "INSTANCE" \
    --target "Key=tag-key,Values=Name,Instance-Type,CostCenter"
```

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

```
aws ssm register-target-with-maintenance-window ^
    --window-id "mw-0c50858d01EXAMPLE" ^
    --resource-type "INSTANCE" ^
    --target "Key=tag-key,Values=Name,Instance-Type,CostCenter"
```

------

**建议使用**：当您想要通过指定多个标签*键*（无值），而非仅指定一个标签键或标签键值对来将节点设为目标时很有用。

**配额：**您总共可以为每个目标指定最多 5 个标签键。如果您指定了多个标签键，则必须使用您指定的*所有*标签键来标记节点，才能将该节点包含在目标组中。

## 示例 4：使用资源组名称注册目标
<a name="mw-target-example-4"></a>

在本地计算机上运行以下命令，注册指定的资源组，而不管其包含的资源类型。将 *mw-0c50858d01EXAMPLE* 替换为您自己的信息。如果分配给维护时段的任务不会在此资源组中包含的某资源类型上执行操作，则系统可能会报告错误。尽管存在这些错误，但找到了支持的资源类型的任务仍会继续运行。

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

```
aws ssm register-target-with-maintenance-window \
    --window-id "mw-0c50858d01EXAMPLE" \
    --resource-type "RESOURCE_GROUP" \
    --target "Key=resource-groups:Name,Values=MyResourceGroup"
```

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

```
aws ssm register-target-with-maintenance-window ^
    --window-id "mw-0c50858d01EXAMPLE" ^
    --resource-type "RESOURCE_GROUP" ^
    --target "Key=resource-groups:Name,Values=MyResourceGroup"
```

------

**建议使用**：当您想要将资源组快速指定为目标而不评估维护时段是否将其所有资源类型设为目标时，或者当您知道资源组仅包含任务对其执行操作的资源类型时，此选项很有用。

**限额：**您只能将一个资源组指定为目标。

## 示例 5：通过筛选资源组中的资源类型来注册目标
<a name="mw-target-example-5"></a>

在本地计算机上运行以下命令，只注册属于您所指定的资源组的某些资源类型。将 *mw-0c50858d01EXAMPLE* 替换为您自己的信息。使用此选项，即使您为属于资源组的资源类型添加任务，但如果尚未将资源类型显式添加到筛选器，则任务也不会运行。

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

```
aws ssm register-target-with-maintenance-window \
    --window-id "mw-0c50858d01EXAMPLE" \
    --resource-type "RESOURCE_GROUP" \
    --target "Key=resource-groups:Name,Values=MyResourceGroup" \
    "Key=resource-groups:ResourceTypeFilters,Values=AWS::EC2::Instance,AWS::ECS::Cluster"
```

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

```
aws ssm register-target-with-maintenance-window ^
    --window-id "mw-0c50858d01EXAMPLE" ^
    --resource-type "RESOURCE_GROUP" ^
    --target "Key=resource-groups:Name,Values=MyResourceGroup" ^
    "Key=resource-groups:ResourceTypeFilters,Values=AWS::EC2::Instance,AWS::ECS::Cluster"
```

------

**建议使用**：当您希望严格控制维护时段可在其上运行操作的 AWS 资源的类型时，或者当您的资源组包含大量资源类型而您希望在维护时段日志中避免不必要的错误报告时，这非常有用。

**限额：**您只能将一个资源组指定为目标。

# 步骤 3：使用 AWS CLI 向维护时段注册任务
<a name="mw-cli-tutorial-tasks"></a>

在教程的此步骤中，您将注册 AWS Systems Manager Run Command 任务，该任务将在适用于 Linux 的 Amazon Elastic Compute Cloud (Amazon EC2) 实例上运行 `df` 命令。此标准 Linux 命令的结果显示实例的磁盘文件系统上的空闲空间数量和已用空间数量。

–或者–

如果您设定的目标是适用于 Windows Server 而不是 Linux 的 Amazon EC2 实例，请将以下命令中的 **df** 替换为 **ipconfig**。此命令的输出列出了有关目标实例上适配器的 IP 地址、子网掩码和默认网关等详细信息。

当您准备好注册其他任务类型，或使用更多可用 Systems Manager Run Command 选项时，请参阅 [示例：向维护时段注册任务](mw-cli-register-tasks-examples.md)。我们在这里提供了有关全部四种任务类型的更多信息，以及它们最重要的一些选项，以帮助您针对更广泛的真实情况制定计划。

**向维护时段注册任务**

1. 在本地计算机上运行以下命令。将每个*示例资源占位符*替换为您自己的信息。从本地 Windows 计算机运行的版本包含转义字符 (“/”)，您需要从命令行工具运行命令。

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

   ```
   aws ssm register-task-with-maintenance-window \
       --window-id mw-0c50858d01EXAMPLE \
       --task-arn "AWS-RunShellScript" \
       --max-concurrency 1 --max-errors 1 \
       --priority 10 \
       --targets "Key=InstanceIds,Values=i-0471e04240EXAMPLE" \
       --task-type "RUN_COMMAND" \
       --task-invocation-parameters '{"RunCommand":{"Parameters":{"commands":["df"]}}}'
   ```

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

   ```
   aws ssm register-task-with-maintenance-window ^
       --window-id mw-0c50858d01EXAMPLE ^
       --task-arn "AWS-RunShellScript" ^
       --max-concurrency 1 --max-errors 1 ^
       --priority 10 ^
       --targets "Key=InstanceIds,Values=i-02573cafcfEXAMPLE" ^
       --task-type "RUN_COMMAND" ^
       --task-invocation-parameters={\"RunCommand\":{\"Parameters\":{\"commands\":[\"df\"]}}}
   ```

------

   系统返回类似于下文的信息：

   ```
   {
       "WindowTaskId": "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE"
   }
   ```

1. 现在，运行以下命令查看有关您创建的维护时段任务的详细信息。

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

   ```
   aws ssm describe-maintenance-window-tasks \
       --window-id mw-0c50858d01EXAMPLE
   ```

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

   ```
   aws ssm describe-maintenance-window-tasks ^
       --window-id mw-0c50858d01EXAMPLE
   ```

------

1. 系统返回类似于以下内容的信息。

   ```
   {
       "Tasks": [
           {
               "WindowId": "mw-0c50858d01EXAMPLE",
               "WindowTaskId": "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE",
               "TaskArn": "AWS-RunShellScript",
               "Type": "RUN_COMMAND",
               "Targets": [
                   {
                       "Key": "InstanceIds",
                       "Values": [
                           "i-02573cafcfEXAMPLE"
                       ]
                   }
               ],
               "TaskParameters": {},
               "Priority": 10,
               "ServiceRoleArn": "arn:aws:iam::123456789012:role/MyMaintenanceWindowServiceRole",
               "MaxConcurrency": "1",
               "MaxErrors": "1"
           }
       ]
   }
   ```

1. 请耐心等待，直到有足够的时间根据您在[步骤 1：使用 AWS CLI 创建维护时段](mw-cli-tutorial-create-mw.md) 中指定的计划运行任务。例如，如果您指定了 **--schedule "rate(5 minutes)"**，则等待五分钟。然后，运行以下命令来查看此任务所进行的任何执行的相关信息。

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

   ```
   aws ssm describe-maintenance-window-executions \
       --window-id mw-0c50858d01EXAMPLE
   ```

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

   ```
   aws ssm describe-maintenance-window-executions ^
       --window-id mw-0c50858d01EXAMPLE
   ```

------

   系统返回类似于以下内容的信息。

   ```
   {
       "WindowExecutions": [
           {
               "WindowId": "mw-0c50858d01EXAMPLE",
               "WindowExecutionId": "14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE",
               "Status": "SUCCESS",
               "StartTime": 1557593493.096,
               "EndTime": 1557593498.611
           }
       ]
   }
   ```

**提示**  
任务成功运行后，您可以降低维护时段运行的速率。例如，运行以下命令以将频率减少为每周一次。将 *mw-0c50858d01EXAMPLE* 替换为您自己的信息。  

```
aws ssm update-maintenance-window \
    --window-id mw-0c50858d01EXAMPLE \
    --schedule "rate(7 days)"
```

```
aws ssm update-maintenance-window ^
    --window-id mw-0c50858d01EXAMPLE ^
    --schedule "rate(7 days)"
```
有关管理维护时段计划的信息，请参阅 [参考：适用于 Systems Manager 的 Cron 和 Rate 表达式](reference-cron-and-rate-expressions.md) 和 [维护时段计划和活动期间选项](maintenance-windows-schedule-options.md)。  
有关使用 AWS Command Line Interface (AWS CLI) 修改维护时段的信息，请参阅 [教程：使用 AWS CLI 更新维护时段](maintenance-windows-cli-tutorials-update.md)。

有关运行 AWS CLI 命令以查看有关维护时段任务及其执行详细信息的练习，请转到[教程：查看有关任务和使用 AWS CLI 执行任务的信息](mw-cli-tutorial-task-info.md)。

**访问教程命令输出**  
使用 AWS CLI 查看与您的维护时段任务执行相关联的 Run Command 命令的*输出*，不在本教程的讨论范围内。

不过，您可以使用 AWS CLI 查看此数据。（您还可以在 Systems Manager 控制台中或存储在 Amazon Simple Storage Service (Amazon S3) 存储桶内的日志文件中（如果您已配置维护时段将命令输出存储在其中）查看输出。） 您会看到，适用于 Linux 的 Amazon EC2 实例上 **df** 命令的输出类似于下文：

```
Filesystem 1K-blocks Used Available Use% Mounted on

devtmpfs 485716 0 485716 0% /dev

tmpfs 503624 0 503624 0% /dev/shm

tmpfs 503624 328 503296 1% /run

tmpfs 503624 0 503624 0% /sys/fs/cgroup

/dev/xvda1 8376300 1464160 6912140 18% /
```

Windows Server 的 EC2 实例上 **ipconfig** 命令的输出类似于下文：

```
Windows IP Configuration


Ethernet adapter Ethernet 2:

   Connection-specific DNS Suffix  . : example.com
   IPv4 Address. . . . . . . . . . . : 10.24.34.0/23
   Subnet Mask . . . . . . . . . . . : 255.255.255.255
   Default Gateway . . . . . . . . . : 0.0.0.0

Ethernet adapter Ethernet:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . : abc1.wa.example.net

Wireless LAN adapter Local Area Connection* 1:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :

Wireless LAN adapter Wi-Fi:

   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::100b:c234:66d6:d24f%4
   IPv4 Address. . . . . . . . . . . : 192.0.2.0
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 192.0.2.0

Ethernet adapter Bluetooth Network Connection:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :
```

# 示例：向维护时段注册任务
<a name="mw-cli-register-tasks-examples"></a>

您可以使用 AWS Command Line Interface（AWS CLI）将 Run Command（AWS Systems Manager 中的一项工具）中的任务注册到维护时段，如[向维护时段注册任务](mw-cli-tutorial-tasks.md)中所示。您还可以为 Systems Manager 自动化 工作流、AWS Lambda 函数和 AWS Step Functions 任务注册任务，如本主题后面的内容所示。

**注意**  
为维护时段 Run Command 类型任务指定一个或多个目标。根据任务的不同，目标对于其他维护时段任务类型（自动化、AWS Lambda 和 AWS Step Functions）是可选的。有关运行未指定目标的任务的更多信息，请参阅 [注册不含目标的维护时段任务](maintenance-windows-targetless-tasks.md)。

在本主题中，我们提供的示例演示了如何使用 AWS Command Line Interface (AWS CLI) 命令 `register-task-with-maintenance-window`，分别将四种支持的任务类型注册到维护时段。这些示例仅用于演示目的，不过您可以修改它们以创建工作任务注册命令。

**使用 --cli-input-json 选项**  
为了更好地管理任务选项，您可以使用命令选项 `--cli-input-json`，其选项值在 JSON 文件中引用。

要使用我们在下列示例中提供的示例 JSON 文件内容，请在您本地计算机上执行以下操作：

1. 创建一个文件，采用类似于 `MyRunCommandTask.json`、`MyAutomationTask.json` 或其他您偏好的名称。

1. 将 JSON 示例内容复制到该文件中。

1. 为您的任务注册修改文件内容，然后保存该文件。

1. 在存储文件的同一个目录中，运行以下命令：用您的文件名替换 *MyFile.json*。

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

   ```
   aws ssm register-task-with-maintenance-window \
       --cli-input-json file://MyFile.json
   ```

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

   ```
   aws ssm register-task-with-maintenance-window ^
       --cli-input-json file://MyFile.json
   ```

------

**维护时段任务中的伪参数**  
在某些示例中，我们使用*伪参数* 作为将 ID 信息传递到您任务的方法。例如，`{{TARGET_ID}}` 和 `{{RESOURCE_ID}}` 可用于将 AWS 资源的 ID 传递到 自动化、Lambda 和 Step Functions 任务。有关 `--task-invocation-parameters` 内容中伪参数的更多信息，请参阅 [注册维护时段任务时使用伪参数](maintenance-window-tasks-pseudo-parameters.md)。

**更多信息**  
+ [register-task-with-maintenance-windows 命令的参数选项](mw-cli-task-options.md).
+ 《AWS CLI Command Reference》**中的 [https://docs.aws.amazon.com/cli/latest/reference/ssm/register-task-with-maintenance-window.html](https://docs.aws.amazon.com/cli/latest/reference/ssm/register-task-with-maintenance-window.html)。
+ **《AWS Systems Manager API 参考》中的 [https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_RegisterTaskWithMaintenanceWindow.html](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_RegisterTaskWithMaintenanceWindow.html)

## 任务注册示例
<a name="task-examples"></a>

以下部分提供了一个示例 AWS CLI 命令，用于注册支持的任务类型和可与 `--cli-input-json` 选项一起使用的 JSON 示例。

### 注册 Systems Manager Run Command 任务
<a name="register-tasks-tutorial-run-command"></a>

以下示例演示了如何使用 AWS CLI 将 Systems Manager Run Command 任务注册到维护时段。

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

```
aws ssm register-task-with-maintenance-window \
    --window-id mw-0c50858d01EXAMPLE \
    --task-arn "AWS-RunShellScript" \
    --max-concurrency 1 --max-errors 1 --priority 10 \
    --targets "Key=InstanceIds,Values=i-02573cafcfEXAMPLE" \
    --task-type "RUN_COMMAND" \
    --task-invocation-parameters '{"RunCommand":{"Parameters":{"commands":["df"]}}}'
```

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

```
aws ssm register-task-with-maintenance-window ^
    --window-id mw-0c50858d01EXAMPLE ^
    --task-arn "AWS-RunShellScript" ^
    --max-concurrency 1 --max-errors 1 --priority 10 ^
    --targets "Key=InstanceIds,Values=i-02573cafcfEXAMPLE" ^
    --task-type "RUN_COMMAND" ^
    --task-invocation-parameters "{\"RunCommand\":{\"Parameters\":{\"commands\":[\"df\"]}}}"
```

------

**用于 `--cli-input-json` 文件选项的 JSON 内容：**

```
{
    "TaskType": "RUN_COMMAND",
    "WindowId": "mw-0c50858d01EXAMPLE",
    "Description": "My Run Command task to update SSM Agent on an instance",
    "MaxConcurrency": "1",
    "MaxErrors": "1",
    "Name": "My-Run-Command-Task",
    "Priority": 10,
    "Targets": [
        {
            "Key": "WindowTargetIds",
            "Values": [
                "e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE"
            ]
        }
    ],
    "TaskArn": "AWS-UpdateSSMAgent",
    "TaskInvocationParameters": {
        "RunCommand": {
            "Comment": "A TaskInvocationParameters test comment",
            "NotificationConfig": {
                "NotificationArn": "arn:aws:sns:region:123456789012:my-sns-topic-name",
                "NotificationEvents": [
                    "All"
                ],
                "NotificationType": "Invocation"
            },
            "OutputS3BucketName": "amzn-s3-demo-bucket",
            "OutputS3KeyPrefix": "S3-PREFIX",
            "TimeoutSeconds": 3600
        }
    }
}
```

### 注册 Systems Manager 自动化 任务
<a name="register-tasks-tutorial-automation"></a>

以下示例演示了如何使用 AWS CLI 将 Systems Manager 自动化 任务注册到维护时段：

**AWS CLI 命令：**

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

```
aws ssm register-task-with-maintenance-window \
    --window-id "mw-0c50858d01EXAMPLE" \
    --task-arn "AWS-RestartEC2Instance" \
    --service-role-arn arn:aws:iam::123456789012:role/MyMaintenanceWindowServiceRole \
    --task-type AUTOMATION \
    --task-invocation-parameters "Automation={DocumentVersion=5,Parameters={InstanceId='{{RESOURCE_ID}}'}}" \
    --priority 0 --name "My-Restart-EC2-Instances-Automation-Task" \
    --description "Automation task to restart EC2 instances"
```

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

```
aws ssm register-task-with-maintenance-window ^
    --window-id "mw-0c50858d01EXAMPLE" ^
    --task-arn "AWS-RestartEC2Instance" ^
    --service-role-arn arn:aws:iam::123456789012:role/MyMaintenanceWindowServiceRole ^
    --task-type AUTOMATION ^
    --task-invocation-parameters "Automation={DocumentVersion=5,Parameters={InstanceId='{{TARGET_ID}}'}}" ^
    --priority 0 --name "My-Restart-EC2-Instances-Automation-Task" ^
    --description "Automation task to restart EC2 instances"
```

------

**用于 `--cli-input-json` 文件选项的 JSON 内容：**

```
{
    "WindowId": "mw-0c50858d01EXAMPLE",
        "TaskArn": "AWS-PatchInstanceWithRollback",
    "TaskType": "AUTOMATION","TaskInvocationParameters": {
        "Automation": {
            "DocumentVersion": "1",
            "Parameters": {
                "instanceId": [
                    "{{RESOURCE_ID}}"
                ]
            }
        }
    }
}
```

### 注册 AWS Lambda 任务
<a name="register-tasks-tutorial-lambda"></a>

以下示例演示了如何使用 AWS CLI 将 Lambda 函数任务注册到维护时段。

对于这些示例，创建 Lambda 函数的用户将其命名为 `SSMrestart-my-instances`，并创建了名为 `instanceId` 和 `targetType` 的两个参数。

**重要**  
Maintenance Windows 的 IAM policy 要求您将前缀 `SSM` 添加到 Lambda 函数（或别名）名称。继续注册此类型的任务之前，请在 AWS Lambda 中更新其名称，以包含 `SSM`。例如，如果您的 Lambda 函数名称为 `MyLambdaFunction`，请将其更改为 `SSMMyLambdaFunction`。

**AWS CLI 命令：**

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

**重要**  
如果您使用的是版本 2 的 AWS CLI，并且您的 Lambda 有效负载没有进行 base64 编码，则您必须在以下命令中包含选项 `--cli-binary-format raw-in-base64-out`。`cli_binary_format` 选项仅在版本 2 中可用。有关此设置和其他 AWS CLI `config` 文件设置的信息，请参阅 *AWS Command Line Interface 用户指南*中的[受支持的 `config` 文件设置](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html#cli-configure-files-settings)。

```
aws ssm register-task-with-maintenance-window \
    --window-id "mw-0c50858d01EXAMPLE" \
    --targets "Key=WindowTargetIds,Values=e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE" \
    --priority 2 --max-concurrency 10 --max-errors 5 --name "My-Lambda-Example" \
    --description "A description for my LAMBDA example task" --task-type "LAMBDA" \
    --task-arn "arn:aws:lambda:region:123456789012:function:serverlessrepo-SSMrestart-my-instances-C4JF9EXAMPLE" \
    --task-invocation-parameters '{"Lambda":{"Payload":"{\"InstanceId\":\"{{RESOURCE_ID}}\",\"targetType\":\"{{TARGET_TYPE}}\"}","Qualifier": "$LATEST"}}'
```

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

**重要**  
如果您使用的是版本 2 的 AWS CLI，并且您的 Lambda 有效负载没有进行 base64 编码，则您必须在以下命令中包含选项 `--cli-binary-format raw-in-base64-out`。`cli_binary_format` 选项仅在版本 2 中可用。有关此设置和其他 AWS CLI `config` 文件设置的信息，请参阅 *AWS Command Line Interface 用户指南*中的[受支持的 `config` 文件设置](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html#cli-configure-files-settings)。

```
aws ssm register-task-with-maintenance-window `
    --window-id "mw-0c50858d01EXAMPLE" `
    --targets "Key=WindowTargetIds,Values=e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE" `
    --priority 2 --max-concurrency 10 --max-errors 5 --name "My-Lambda-Example" `
    --description "A description for my LAMBDA example task" --task-type "LAMBDA" `
    --task-arn "arn:aws:lambda:region:123456789012:function:serverlessrepo-SSMrestart-my-instances-C4JF9EXAMPLE" `
    --task-invocation-parameters '{\"Lambda\":{\"Payload\":\"{\\\"InstanceId\\\":\\\"{{RESOURCE_ID}}\\\",\\\"targetType\\\":\\\"{{TARGET_TYPE}}\\\"}\",\"Qualifier\": \"$LATEST\"}}'
```

------

**用于 `--cli-input-json` 文件选项的 JSON 内容：**

```
{
    "WindowId": "mw-0c50858d01EXAMPLE",
    "Targets": [
        {
            "Key": "WindowTargetIds",
            "Values": [
                "e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE"
            ]
        }
    ],
    "TaskArn": "SSM_RestartMyInstances",
    "TaskType": "LAMBDA",
    "MaxConcurrency": "10",
    "MaxErrors": "10",
    "TaskInvocationParameters": {
        "Lambda": {
            "ClientContext": "ew0KICAi--truncated--0KIEXAMPLE",
            "Payload": "{ \"instanceId\": \"{{RESOURCE_ID}}\", \"targetType\": \"{{TARGET_TYPE}}\" }",
            "Qualifier": "$LATEST"
        }
    },
    "Name": "My-Lambda-Task",
    "Description": "A description for my LAMBDA task",
    "Priority": 5
}
```

### 注册 Step Functions 任务
<a name="register-tasks-tutorial-step-functions"></a>

以下示例演示了如何使用 AWS CLI 将 Step Functions 状态机任务注册到维护时段。

**注意**  
维护时段任务仅支持 Step Functions 标准状态机工作流。它们不支持快速状态机工作流。有关状态机工作流类型的信息，请参阅《AWS Step Functions 开发人员指南》**中的[标准与快速工作流](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-standard-vs-express.html)。

对于这些示例，创建 Step Functions 状态机的用户使用名为 `instanceId` 的参数创建名为 `SSMMyStateMachine` 的状态机。

**重要**  
Maintenance Windows 的 AWS Identity and Access Management （IAM）policy 要求您使用 `SSM` 作为 Step Functions 状态机名称的前缀。继续注册此类型的任务之前，您必须在 AWS Step Functions 中更新此名称以包括 `SSM`。例如，如果您的状态机名为 `MyStateMachine`，则将其更改为 `SSMMyStateMachine`。

**AWS CLI 命令：**

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

```
aws ssm register-task-with-maintenance-window \
    --window-id "mw-0c50858d01EXAMPLE" \
    --targets "Key=WindowTargetIds,Values=e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE" \
    --task-arn arn:aws:states:region:123456789012:stateMachine:SSMMyStateMachine-MggiqEXAMPLE \
    --task-type STEP_FUNCTIONS \
    --task-invocation-parameters '{"StepFunctions":{"Input":"{\"InstanceId\":\"{{RESOURCE_ID}}\"}", "Name":"{{INVOCATION_ID}}"}}' \
    --priority 0 --max-concurrency 10 --max-errors 5 \
    --name "My-Step-Functions-Task" --description "A description for my Step Functions task"
```

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

```
aws ssm register-task-with-maintenance-window `
    --window-id "mw-0c50858d01EXAMPLE" `
    --targets "Key=WindowTargetIds,Values=e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE" `
    --task-arn arn:aws:states:region:123456789012:stateMachine:SSMMyStateMachine-MggiqEXAMPLE `
    --task-type STEP_FUNCTIONS `
    --task-invocation-parameters '{\"StepFunctions\":{\"Input\":\"{\\\"InstanceId\\\":\\\"{{RESOURCE_ID}}\\\"}\", \"Name\":\"{{INVOCATION_ID}}\"}}' `
    --priority 0 --max-concurrency 10 --max-errors 5 `
    --name "My-Step-Functions-Task" --description "A description for my Step Functions task"
```

------

**用于 `--cli-input-json` 文件选项的 JSON 内容：**

```
{
    "WindowId": "mw-0c50858d01EXAMPLE",
    "Targets": [
        {
            "Key": "WindowTargetIds",
            "Values": [
                "e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE"
            ]
        }
    ],
    "TaskArn": "SSM_MyStateMachine",
    "TaskType": "STEP_FUNCTIONS",
    "MaxConcurrency": "10",
    "MaxErrors": "10",
    "TaskInvocationParameters": {
        "StepFunctions": {
            "Input": "{ \"instanceId\": \"{{TARGET_ID}}\" }",
            "Name": "{{INVOCATION_ID}}"
        }
    },
    "Name": "My-Step-Functions-Task",
    "Description": "A description for my Step Functions task",
    "Priority": 5
}
```

# register-task-with-maintenance-windows 命令的参数选项
<a name="mw-cli-task-options"></a>

**register-task-with-maintenance-window** 命令提供多个选项用于根据您的需求配置任务。其中一些任务为必需，一些为可选，还有一些仅适用于单个维护时段任务类型。

本主题提供了有关其中一些选项的信息，以帮助您使用本教程这一部分中的示例。有关所有命令选项的信息，请参阅 *AWS CLI 命令参考*中的 **[https://docs.aws.amazon.com/cli/latest/reference/ssm/register-task-with-maintenance-window.html](https://docs.aws.amazon.com/cli/latest/reference/ssm/register-task-with-maintenance-window.html)**。

**命令选项：`--task-arn`**  
`--task-arn` 选项用于指定执行任务的资源。您指定的值取决于所要注册的任务类型，如下表中所述。


**维护时段任务的 TaskArn 格式**  

| 维护时段任务类型 | TaskArn 值 | 
| --- | --- | 
|  **`RUN_COMMAND`** 和 **`AUTOMATION`**  |  `TaskArn` 是 SSM 文档名称或 Amazon Resource Name (ARN)。例如： `AWS-RunBatchShellScript`  –或者– `arn:aws:ssm:region:111122223333:document/My-Document`.  | 
|  **`LAMBDA`**  |  `TaskArn` 是函数名称或 ARN。例如： `SSMMy-Lambda-Function` –或者– `arn:aws:lambda:region:111122223333:function:SSMMyLambdaFunction`.  Maintenance Windows 的 IAM policy 要求您将前缀 `SSM` 添加到 Lambda 函数（或别名）名称。继续注册此类型的任务之前，请在 AWS Lambda 中更新其名称，以包含 `SSM`。例如，如果您的 Lambda 函数名称为 `MyLambdaFunction`，请将其更改为 `SSMMyLambdaFunction`。   | 
|  **`STEP_FUNCTIONS`**  |  `TaskArn` 是状态机 ARN。例如： `arn:aws:states:us-east-2:111122223333:stateMachine:SSMMyStateMachine`.  维护时段的 IAM policy 要求您使用 `SSM` 作为 Step Functions 状态机名称的前缀。您应先注册此类型的任务，然后必须在 AWS Step Functions 中更新其名称以包含 `SSM`。例如，如果您的状态机名为 `MyStateMachine`，则将其更改为 `SSMMyStateMachine`。   | 

**命令选项：`--service-role-arn`**  
运行维护时段任务时 AWS Systems Manager 要代入的角色。

有关更多信息，请参阅 [设置 Maintenance Windows](setting-up-maintenance-windows.md)。

**命令选项：`--task-invocation-parameters`**  
`--task-invocation-parameters` 选项用于指定分别对于四种任务类型唯一的参数。四种任务类型分别支持的参数如下表中所述。

**注意**  
有关在 `--task-invocation-parameters` 内容中使用伪参数的信息，例如 \$1\$1TARGET\$1ID\$1\$1，请参阅[注册维护时段任务时使用伪参数](maintenance-window-tasks-pseudo-parameters.md)。

维护任务时段的任务调用参数选项


| 维护时段任务类型 | 可用参数  | 示例 | 
| --- | --- | --- | 
|  **`RUN_COMMAND`**  |  `Comment` `DocumentHash` `DocumentHashType` `NotificationConfig` `OutputS3BucketName` `OutPutS3KeyPrefix` `Parameters` `ServiceRoleArn` `TimeoutSeconds`  |  <pre>"TaskInvocationParameters": {<br />        "RunCommand": {<br />            "Comment": "My Run Command task comment",<br />            "DocumentHash": "6554ed3d--truncated--5EXAMPLE",<br />            "DocumentHashType": "Sha256",<br />            "NotificationConfig": {<br />                "NotificationArn": "arn:aws:sns:region:123456789012:my-sns-topic-name",<br />                "NotificationEvents": [<br />                    "FAILURE"<br />                ],<br />                "NotificationType": "Invocation"<br />            },<br />            "OutputS3BucketName": "amzn-s3-demo-bucket",<br />            "OutputS3KeyPrefix": "S3-PREFIX",<br />            "Parameters": {<br />                "commands": [<br />                    "Get-ChildItem$env: temp-Recurse|Remove-Item-Recurse-force"<br />                ]<br />            },<br />            "ServiceRoleArn": "arn:aws:iam::123456789012:role/MyMaintenanceWindowServiceRole",<br />            "TimeoutSeconds": 3600<br />        }<br />    }</pre>  | 
|  **`AUTOMATION`**  |  `DocumentVersion` `Parameters`  |  <pre>"TaskInvocationParameters": {<br />        "Automation": {<br />            "DocumentVersion": "3",<br />            "Parameters": {<br />                "instanceid": [<br />                    "{{TARGET_ID}}"<br />                ]<br />            }<br />        }<br />    }</pre>  | 
|  **`LAMBDA`**  |  `ClientContext` `Payload` `Qualifier`  |  <pre>"TaskInvocationParameters": {<br />        "Lambda": {<br />            "ClientContext": "ew0KICAi--truncated--0KIEXAMPLE",<br />            "Payload": "{ \"targetId\": \"{{TARGET_ID}}\", \"targetType\": \"{{TARGET_TYPE}}\" }",<br />            "Qualifier": "$LATEST"<br />        }<br />    }</pre>  | 
|  **`STEP_FUNCTIONS`**  |  `Input` `Name`  |  <pre>"TaskInvocationParameters": {<br />        "StepFunctions": {<br />            "Input": "{ \"targetId\": \"{{TARGET_ID}}\" }",<br />            "Name": "{{INVOCATION_ID}}"<br />        }<br />    }</pre>  | 

# 教程：使用 AWS CLI 查看有关维护时段的信息
<a name="maintenance-windows-cli-tutorials-describe"></a>

本教程包含的命令可帮助您更新维护时段、任务、执行和调用或获取相关信息。这些示例按命令进行组织，说明如何使用命令选项筛选要查看的详细信息类型。

在按照本教程中的步骤操作时，请将以斜体*红色*文本显示的值替换为您自己的选项和 ID。例如，请将维护时段 ID *mw-0c50858d01EXAMPLE* 和实例 ID *i-02573cafcfEXAMPLE* 替换为您创建的资源的 ID。

有关设置和配置 AWS Command Line Interface (AWS CLI) 的信息，请参阅[安装、更新和卸载 AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html) 和[配置 AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)。

**Topics**
+ ['describe-maintenance-windows' 的示例](#mw-cli-tutorials-describe-maintenance-windows)
+ ['describe-maintenance-window-targets' 的示例](#mw-cli-tutorials-describe-maintenance-window-targets)
+ ['describe-maintenance-window-tasks' 的示例](#mw-cli-tutorials-describe-maintenance-window-tasks)
+ ['describe-maintenance-windows-for-target' 的示例](#mw-cli-tutorials-describe-maintenance-windows-for-target)
+ ['describe-maintenance-window-executions' 的示例](#mw-cli-tutorials-describe-maintenance-window-executions)
+ ['describe-maintenance-window-schedule' 的示例](#mw-cli-tutorials-describe-maintenance-window-schedule)

## 'describe-maintenance-windows' 的示例
<a name="mw-cli-tutorials-describe-maintenance-windows"></a>

**列出您的 AWS 账户中的所有维护时段**  
运行如下命令。

```
aws ssm describe-maintenance-windows
```

系统返回类似于以下内容的信息。

```
{
   "WindowIdentities":[
      {
         "WindowId":"mw-0c50858d01EXAMPLE",
         "Name":"My-First-Maintenance-Window",
         "Enabled":true,
         "Duration":2,
         "Cutoff":0,
         "NextExecutionTime": "2019-05-18T17:01:01.137Z"        
      },
      {
         "WindowId":"mw-9a8b7c6d5eEXAMPLE",
         "Name":"My-Second-Maintenance-Window",
         "Enabled":true,
         "Duration":4,
         "Cutoff":1,
         "NextExecutionTime": "2019-05-30T03:30:00.137Z"        
      },
   ]
}
```

**列出所有已启用的维护时段**  
运行如下命令。

```
aws ssm describe-maintenance-windows --filters "Key=Enabled,Values=true"
```

系统返回类似于以下内容的信息。

```
{
   "WindowIdentities":[
      {
         "WindowId":"mw-0c50858d01EXAMPLE",
         "Name":"My-First-Maintenance-Window",
         "Enabled":true,
         "Duration":2,
         "Cutoff":0,
         "NextExecutionTime": "2019-05-18T17:01:01.137Z"        
      },
      {
         "WindowId":"mw-9a8b7c6d5eEXAMPLE",
         "Name":"My-Second-Maintenance-Window",
         "Enabled":true,
         "Duration":4,
         "Cutoff":1,
         "NextExecutionTime": "2019-05-30T03:30:00.137Z"        
      },
   ]
}
```

**列出所有已禁用的维护时段**  
运行如下命令。

```
aws ssm describe-maintenance-windows --filters "Key=Enabled,Values=false"
```

系统返回类似于以下内容的信息。

```
{
    "WindowIdentities": [
        {
            "WindowId": "mw-6e5c9d4b7cEXAMPLE",
            "Name": "My-Disabled-Maintenance-Window",
            "Enabled": false,
            "Duration": 2,
            "Cutoff": 1
        }
    ]
}
```

**列出名称以特定前缀开头的所有维护时段**  
运行如下命令。

```
aws ssm describe-maintenance-windows --filters "Key=Name,Values=My"
```

系统返回类似于以下内容的信息。

```
{
    "WindowIdentities": [
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "Name": "My-First-Maintenance-Window",
            "Enabled": true,
            "Duration": 2,
            "Cutoff": 0,
            "NextExecutionTime": "2019-05-18T17:01:01.137Z"
        },
        {
            "WindowId": "mw-9a8b7c6d5eEXAMPLE",
            "Name": "My-Second-Maintenance-Window",
            "Enabled": true,
            "Duration": 4,
            "Cutoff": 1,
            "NextExecutionTime": "2019-05-30T03:30:00.137Z"
        },
        {
            "WindowId": "mw-6e5c9d4b7cEXAMPLE",
            "Name": "My-Disabled-Maintenance-Window",
            "Enabled": false,
            "Duration": 2,
            "Cutoff": 1
        }
    ]
}
```

## 'describe-maintenance-window-targets' 的示例
<a name="mw-cli-tutorials-describe-maintenance-window-targets"></a>

**显示匹配特定所有者信息值的维护时段的目标**  
运行如下命令。

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

```
aws ssm describe-maintenance-window-targets \
    --window-id "mw-6e5c9d4b7cEXAMPLE" \
    --filters "Key=OwnerInformation,Values=CostCenter1"
```

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

```
aws ssm describe-maintenance-window-targets ^
    --window-id "mw-6e5c9d4b7cEXAMPLE" ^
    --filters "Key=OwnerInformation,Values=CostCenter1"
```

------

**注意**  
支持的筛选条件键为 `Type`、`WindowTargetId` 和 `OwnerInformation`。

系统返回类似于以下内容的信息。

```
{
    "Targets": [
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "WindowTargetId": "e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE",
            "ResourceType": "INSTANCE",
            "Targets": [
                {
                    "Key": "tag:Name",
                    "Values": [
                        "Production"
                    ]
                }
            ],
            "OwnerInformation": "CostCenter1",
            "Name": "Target1"
        }
    ]
}
```

## 'describe-maintenance-window-tasks' 的示例
<a name="mw-cli-tutorials-describe-maintenance-window-tasks"></a>

**显示调用 SSM 命令文档 `AWS-RunPowerShellScript` 的所有已注册任务**  
运行如下命令。

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

```
aws ssm describe-maintenance-window-tasks \
    --window-id "mw-0c50858d01EXAMPLE" \
    --filters "Key=TaskArn,Values=AWS-RunPowerShellScript"
```

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

```
aws ssm describe-maintenance-window-tasks ^
    --window-id "mw-0c50858d01EXAMPLE" ^
    --filters "Key=TaskArn,Values=AWS-RunPowerShellScript"
```

------

系统返回类似于以下内容的信息。

```
{
   "Tasks":[
      {
         "ServiceRoleArn": "arn:aws:iam::111122223333:role/MyMaintenanceWindowServiceRole",
         "MaxErrors":"1",
         "TaskArn":"AWS-RunPowerShellScript",
         "MaxConcurrency":"1",
         "WindowTaskId":"4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE",
         "TaskParameters":{
            "commands":{
               "Values":[
                  "driverquery.exe"
               ]
            }
         },
         "Priority":3,
         "Type":"RUN_COMMAND",
         "Targets":[
            {
               "TaskTargetId":"i-02573cafcfEXAMPLE",
               "TaskTargetType":"INSTANCE"
            }
         ]
      },
      {
         "ServiceRoleArn":"arn:aws:iam::111122223333:role/MyMaintenanceWindowServiceRole",
         "MaxErrors":"1",
         "TaskArn":"AWS-RunPowerShellScript",
         "MaxConcurrency":"1",
         "WindowTaskId":"4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE",
         "TaskParameters":{
            "commands":{
               "Values":[
                  "ipconfig"
               ]
            }
         },
         "Priority":1,
         "Type":"RUN_COMMAND",
         "Targets":[
            {
               "TaskTargetId":"i-02573cafcfEXAMPLE",
               "TaskTargetType":"WINDOW_TARGET"
            }
         ]
      }
   ]
}
```

**显示优先级为“3”的所有已注册任务**  
运行如下命令。

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

```
aws ssm describe-maintenance-window-tasks \
    --window-id "mw-9a8b7c6d5eEXAMPLE" \
    --filters "Key=Priority,Values=3"
```

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

```
aws ssm describe-maintenance-window-tasks ^
    --window-id "mw-9a8b7c6d5eEXAMPLE" ^
    --filters "Key=Priority,Values=3"
```

------

系统返回类似于以下内容的信息。

```
{
   "Tasks":[
      {
         "ServiceRoleArn":"arn:aws:iam::111122223333:role/MyMaintenanceWindowServiceRole",
         "MaxErrors":"1",
         "TaskArn":"AWS-RunPowerShellScript",
         "MaxConcurrency":"1",
         "WindowTaskId":"4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE",
         "TaskParameters":{
            "commands":{
               "Values":[
                  "driverquery.exe"
               ]
            }
         },
         "Priority":3,
         "Type":"RUN_COMMAND",
         "Targets":[
            {
               "TaskTargetId":"i-02573cafcfEXAMPLE",
               "TaskTargetType":"INSTANCE"
            }
         ]
      }
   ]
}
```

**显示优先级为 1 且使用 Run Command 的所有已注册任务**  
运行如下命令。

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

```
aws ssm describe-maintenance-window-tasks \
    --window-id "mw-0c50858d01EXAMPLE" \
    --filters "Key=Priority,Values=1" "Key=TaskType,Values=RUN_COMMAND"
```

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

```
aws ssm describe-maintenance-window-tasks ^
    --window-id "mw-0c50858d01EXAMPLE" ^
    --filters "Key=Priority,Values=1" "Key=TaskType,Values=RUN_COMMAND"
```

------

系统返回类似于以下内容的信息。

```
{
    "Tasks": [
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "WindowTaskId": "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE",
            "TaskArn": "AWS-RunShellScript",
            "Type": "RUN_COMMAND",
            "Targets": [
                {
                    "Key": "InstanceIds",
                    "Values": [
                        "i-02573cafcfEXAMPLE"
                    ]
                }
            ],
            "TaskParameters": {},
            "Priority": 1,
            "ServiceRoleArn": "arn:aws:iam::111122223333:role/MyMaintenanceWindowServiceRole",
            "MaxConcurrency": "1",
            "MaxErrors": "1"
        },
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "WindowTaskId": "8a5c4629-31b0-4edd-8aea-33698EXAMPLE",
            "TaskArn": "AWS-UpdateSSMAgent",
            "Type": "RUN_COMMAND",
            "Targets": [
                {
                    "Key": "InstanceIds",
                    "Values": [
                        "i-0471e04240EXAMPLE"
                    ]
                }
            ],
            "TaskParameters": {},
            "Priority": 1,
            "ServiceRoleArn": "arn:aws:iam::111122223333:role/MyMaintenanceWindowServiceRole",
            "MaxConcurrency": "1",
            "MaxErrors": "1",
            "Name": "My-Run-Command-Task",
            "Description": "My Run Command task to update SSM Agent on an instance"
        }
    ]
}
```

## 'describe-maintenance-windows-for-target' 的示例
<a name="mw-cli-tutorials-describe-maintenance-windows-for-target"></a>

**列出与特定节点关联的维护时段目标或任务的相关信息**  
运行如下命令。

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

```
aws ssm describe-maintenance-windows-for-target \
    --resource-type INSTANCE \
    --targets "Key=InstanceIds,Values=i-02573cafcfEXAMPLE" \
    --max-results 10
```

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

```
aws ssm describe-maintenance-windows-for-target ^
    --resource-type INSTANCE ^
    --targets "Key=InstanceIds,Values=i-02573cafcfEXAMPLE" ^
    --max-results 10
```

------

系统返回类似于以下内容的信息。

```
{
    "WindowIdentities": [
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "Name": "My-First-Maintenance-Window"
        },
        {
            "WindowId": "mw-9a8b7c6d5eEXAMPLE",
            "Name": "My-Second-Maintenance-Window"
        }
    ]
}
```

## 'describe-maintenance-window-executions' 的示例
<a name="mw-cli-tutorials-describe-maintenance-window-executions"></a>

**列出在特定日期前运行的所有任务**  
运行如下命令。

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

```
aws ssm describe-maintenance-window-executions \
    --window-id "mw-9a8b7c6d5eEXAMPLE" \
    --filters "Key=ExecutedBefore,Values=2019-05-12T05:00:00Z"
```

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

```
aws ssm describe-maintenance-window-executions ^
    --window-id "mw-9a8b7c6d5eEXAMPLE" ^
    --filters "Key=ExecutedBefore,Values=2019-05-12T05:00:00Z"
```

------

系统返回类似于以下内容的信息。

```
{
    "WindowExecutions": [
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "WindowExecutionId": "14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE",
            "Status": "FAILED",
            "StatusDetails": "The following SSM parameters are invalid: LevelUp",
            "StartTime": 1557617747.993,
            "EndTime": 1557617748.101
        },
        {
            "WindowId": "mw-9a8b7c6d5eEXAMPLE",
            "WindowExecutionId": "791b72e0-f0da-4021-8b35-f95dfEXAMPLE",
            "Status": "SUCCESS",
            "StartTime": 1557594085.428,
            "EndTime": 1557594090.978
        },
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "WindowExecutionId": "ecec60fa-6bb0-4d26-98c7-140308EXAMPLE",
            "Status": "SUCCESS",
            "StartTime": 1557593793.483,
            "EndTime": 1557593798.978
        }
    ]
}
```

**列出在特定日期后运行的所有任务**  
运行如下命令。

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

```
aws ssm describe-maintenance-window-executions \
    --window-id "mw-9a8b7c6d5eEXAMPLE" \
    --filters "Key=ExecutedAfter,Values=2018-12-31T17:00:00Z"
```

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

```
aws ssm describe-maintenance-window-executions ^
    --window-id "mw-9a8b7c6d5eEXAMPLE" ^
    --filters "Key=ExecutedAfter,Values=2018-12-31T17:00:00Z"
```

------

系统返回类似于以下内容的信息。

```
{
    "WindowExecutions": [
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "WindowExecutionId": "14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE",
            "Status": "FAILED",
            "StatusDetails": "The following SSM parameters are invalid: LevelUp",
            "StartTime": 1557617747.993,
            "EndTime": 1557617748.101
        },
        {
            "WindowId": "mw-9a8b7c6d5eEXAMPLE",
            "WindowExecutionId": "791b72e0-f0da-4021-8b35-f95dfEXAMPLE",
            "Status": "SUCCESS",
            "StartTime": 1557594085.428,
            "EndTime": 1557594090.978
        },
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "WindowExecutionId": "ecec60fa-6bb0-4d26-98c7-140308EXAMPLE",
            "Status": "SUCCESS",
            "StartTime": 1557593793.483,
            "EndTime": 1557593798.978
        }
    ]
}
```

## 'describe-maintenance-window-schedule' 的示例
<a name="mw-cli-tutorials-describe-maintenance-window-schedule"></a>

**显示特定节点接下来的十次已计划的维护时段运行**  
运行如下命令。

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

```
aws ssm describe-maintenance-window-schedule \
    --resource-type INSTANCE \
    --targets "Key=InstanceIds,Values=i-07782c72faEXAMPLE" \
    --max-results 10
```

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

```
aws ssm describe-maintenance-window-schedule ^
    --resource-type INSTANCE ^
    --targets "Key=InstanceIds,Values=i-07782c72faEXAMPLE" ^
    --max-results 10
```

------

系统返回类似于以下内容的信息。

```
{
    "ScheduledWindowExecutions": [
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "Name": "My-First-Maintenance-Window",
            "ExecutionTime": "2019-05-18T23:35:24.902Z"
        },
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "Name": "My-First-Maintenance-Window",
            "ExecutionTime": "2019-05-25T23:35:24.902Z"
        },
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "Name": "My-First-Maintenance-Window",
            "ExecutionTime": "2019-06-01T23:35:24.902Z"
        },
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "Name": "My-First-Maintenance-Window",
            "ExecutionTime": "2019-06-08T23:35:24.902Z"
        },
        {
            "WindowId": "mw-9a8b7c6d5eEXAMPLE",
            "Name": "My-Second-Maintenance-Window",
            "ExecutionTime": "2019-06-15T23:35:24.902Z"
        },
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "Name": "My-First-Maintenance-Window",
            "ExecutionTime": "2019-06-22T23:35:24.902Z"
        },
        {
            "WindowId": "mw-9a8b7c6d5eEXAMPLE",
            "Name": "My-Second-Maintenance-Window",
            "ExecutionTime": "2019-06-29T23:35:24.902Z"
        },
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "Name": "My-First-Maintenance-Window",
            "ExecutionTime": "2019-07-06T23:35:24.902Z"
        },
        {
            "WindowId": "mw-9a8b7c6d5eEXAMPLE",
            "Name": "My-Second-Maintenance-Window",
            "ExecutionTime": "2019-07-13T23:35:24.902Z"
        },
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "Name": "My-First-Maintenance-Window",
            "ExecutionTime": "2019-07-20T23:35:24.902Z"
        }
    ],
    "NextToken": "AAEABUXdceT92FvtKld/dGHELj5Mi+GKW/EXAMPLE"
}
```

**显示使用特定键值对标记的节点的维护时段计划**  
运行如下命令。

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

```
aws ssm describe-maintenance-window-schedule \
    --resource-type INSTANCE \
    --targets "Key=tag:prod,Values=rhel7"
```

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

```
aws ssm describe-maintenance-window-schedule ^
    --resource-type INSTANCE ^
    --targets "Key=tag:prod,Values=rhel7"
```

------

系统返回类似于以下内容的信息。

```
{
    "ScheduledWindowExecutions": [
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "Name": "DemoRateStartDate",
            "ExecutionTime": "2019-10-20T05:34:56-07:00"
        },
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "Name": "DemoRateStartDate",
            "ExecutionTime": "2019-10-21T05:34:56-07:00"
        },
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "Name": "DemoRateStartDate",
            "ExecutionTime": "2019-10-22T05:34:56-07:00"
        },
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "Name": "DemoRateStartDate",
            "ExecutionTime": "2019-10-23T05:34:56-07:00"
        },
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "Name": "DemoRateStartDate",
            "ExecutionTime": "2019-10-24T05:34:56-07:00"
        }
    ],
    "NextToken": "AAEABccwSXqQRGKiTZ1yzGELR6cxW4W/EXAMPLE"
}
```

**显示某个维护时段接下来的四个运行的开始时间**  
运行如下命令。

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

```
aws ssm describe-maintenance-window-schedule \
    --window-id "mw-0c50858d01EXAMPLE" \
    --max-results "4"
```

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

```
aws ssm describe-maintenance-window-schedule ^
    --window-id "mw-0c50858d01EXAMPLE" ^
    --max-results "4"
```

------

系统返回类似于以下内容的信息。

```
{
    "WindowSchedule": [
        {
            "ScheduledWindowExecutions": [
                {
                    "ExecutionTime": "2019-10-04T10:10:10Z",
                    "Name": "My-First-Maintenance-Window",
                    "WindowId": "mw-0c50858d01EXAMPLE"
                },
                {
                    "ExecutionTime": "2019-10-11T10:10:10Z",
                    "Name": "My-First-Maintenance-Window",
                    "WindowId": "mw-0c50858d01EXAMPLE"
                },
                {
                    "ExecutionTime": "2019-10-18T10:10:10Z",
                    "Name": "My-First-Maintenance-Window",
                    "WindowId": "mw-0c50858d01EXAMPLE"
                },
                {
                    "ExecutionTime": "2019-10-25T10:10:10Z",
                    "Name": "My-First-Maintenance-Window",
                    "WindowId": "mw-0c50858d01EXAMPLE"
                }
            ]
        }
    ]
}
```

# 教程：查看有关任务和使用 AWS CLI 执行任务的信息
<a name="mw-cli-tutorial-task-info"></a>

本教程演示了如何使用 AWS Command Line Interface (AWS CLI) 查看有关您已完成的维护时段任务的详细信息。

如果您直接从 [教程：使用 AWS CLI 创建和配置维护时段](maintenance-windows-cli-tutorials-create.md) 继续，请确保您已为维护时段留出足够时间至少运行一次，以查看其执行结果。

在按照本教程中的步骤操作时，请将以斜体*红色*文本显示的值替换为您自己的选项和 ID。例如，请将维护时段 ID *mw-0c50858d01EXAMPLE* 和实例 ID *i-02573cafcfEXAMPLE* 替换为您创建的资源的 ID。

**要查看有关任务和使用 AWS CLI 执行任务的信息**

1. 运行以下命令，查看特定维护时段的任务执行列表。

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

   ```
   aws ssm describe-maintenance-window-executions \
       --window-id "mw-0c50858d01EXAMPLE"
   ```

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

   ```
   aws ssm describe-maintenance-window-executions ^
       --window-id "mw-0c50858d01EXAMPLE"
   ```

------

   系统返回类似于以下内容的信息。

   ```
   {
       "WindowExecutions": [
           {
               "WindowId": "mw-0c50858d01EXAMPLE",
               "WindowExecutionId": "14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE",
               "Status": "SUCCESS",
               "StartTime": 1557593793.483,
               "EndTime": 1557593798.978
           },
           {
               "WindowId": "mw-0c50858d01EXAMPLE",
               "WindowExecutionId": "791b72e0-f0da-4021-8b35-f95dfEXAMPLE",
               "Status": "SUCCESS",
               "StartTime": 1557593493.096,
               "EndTime": 1557593498.611
           },
           {
               "WindowId": "mw-0c50858d01EXAMPLE",
               "WindowExecutionId": "ecec60fa-6bb0-4d26-98c7-140308EXAMPLE",
               "Status": "SUCCESS",
               "StatusDetails": "No tasks to execute.",
               "StartTime": 1557593193.309,
               "EndTime": 1557593193.334
           }
       ]
   }
   ```

1. 运行以下命令，获取有关维护时段任务执行的信息。

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

   ```
   aws ssm get-maintenance-window-execution \
       --window-execution-id "14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE"
   ```

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

   ```
   aws ssm get-maintenance-window-execution ^
       --window-execution-id "14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE"
   ```

------

   系统返回类似于以下内容的信息。

   ```
   {
       "WindowExecutionId": "14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE",
       "TaskIds": [
           "c9b05aba-197f-4d8d-be34-e73fbEXAMPLE"
       ],
       "Status": "SUCCESS",
       "StartTime": 1557593493.096,
       "EndTime": 1557593498.611
   }
   ```

1. 运行以下命令，列出作为维护时段执行的组成部分运行的任务。

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

   ```
   aws ssm describe-maintenance-window-execution-tasks \
       --window-execution-id "14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE"
   ```

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

   ```
   aws ssm describe-maintenance-window-execution-tasks ^
       --window-execution-id "14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE"
   ```

------

   系统返回类似于以下内容的信息。

   ```
   {
       "WindowExecutionTaskIdentities": [
           {
               "WindowExecutionId": "14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE",
               "TaskExecutionId": "c9b05aba-197f-4d8d-be34-e73fbEXAMPLE",
               "Status": "SUCCESS",
               "StartTime": 1557593493.162,
               "EndTime": 1557593498.57,
               "TaskArn": "AWS-RunShellScript",
               "TaskType": "RUN_COMMAND"
           }
       ]
   }
   ```

1. 运行以下命令，获取有关任务执行的详情。

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

   ```
   aws ssm get-maintenance-window-execution-task \
       --window-execution-id "14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE" \
       --task-id "c9b05aba-197f-4d8d-be34-e73fbEXAMPLE"
   ```

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

   ```
   aws ssm get-maintenance-window-execution-task ^
       --window-execution-id "14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE" ^
       --task-id "c9b05aba-197f-4d8d-be34-e73fbEXAMPLE"
   ```

------

   系统返回类似于以下内容的信息。

   ```
   {
       "WindowExecutionId": "14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE",
       "TaskExecutionId": "c9b05aba-197f-4d8d-be34-e73fbEXAMPLE",
       "TaskArn": "AWS-RunShellScript",
       "ServiceRole": "arn:aws:iam::111122223333:role/MyMaintenanceWindowServiceRole",
       "Type": "RUN_COMMAND",
       "TaskParameters": [
           {
               "aws:InstanceId": {
                   "Values": [
                       "i-02573cafcfEXAMPLE"
                   ]
               },
               "commands": {
                   "Values": [
                       "df"
                   ]
               }
           }
       ],
       "Priority": 10,
       "MaxConcurrency": "1",
       "MaxErrors": "1",
       "Status": "SUCCESS",
       "StartTime": 1557593493.162,
       "EndTime": 1557593498.57
   }
   ```

1. 运行以下命令，获取执行某个任务时执行的具体任务调用。

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

   ```
   aws ssm describe-maintenance-window-execution-task-invocations \
       --window-execution-id "14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE" \
       --task-id "c9b05aba-197f-4d8d-be34-e73fbEXAMPLE"
   ```

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

   ```
   aws ssm describe-maintenance-window-execution-task-invocations ^
       --window-execution-id "14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE" ^
       --task-id "c9b05aba-197f-4d8d-be34-e73fbEXAMPLE"
   ```

------

   系统返回类似于以下内容的信息。

   ```
   {
       "WindowExecutionTaskInvocationIdentities": [
           {
               "WindowExecutionId": "14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE",
               "TaskExecutionId": "c9b05aba-197f-4d8d-be34-e73fbEXAMPLE",
               "InvocationId": "c336d2ab-09de-44ba-8f6a-6136cEXAMPLE",
               "ExecutionId": "76a5a04f-caf6-490c-b448-92c02EXAMPLE",
               "TaskType": "RUN_COMMAND",
               "Parameters": "{\"documentName\":\"AWS-RunShellScript\",\"instanceIds\":[\"i-02573cafcfEXAMPLE\"],\"maxConcurrency\":\"1\",\"maxErrors\":\"1\",\"parameters\":{\"commands\":[\"df\"]}}",
               "Status": "SUCCESS",
               "StatusDetails": "Success",
               "StartTime": 1557593493.222,
               "EndTime": 1557593498.466
           }
       ]
   }
   ```

# 教程：使用 AWS CLI 更新维护时段
<a name="maintenance-windows-cli-tutorials-update"></a>

本教程演示了如何使用 AWS Command Line Interface (AWS CLI) 更新维护时段。它还向您演示了如何更新不同的任务类型，包括 AWS Systems Manager Run Command、自动化、AWS Lambda 和 AWS Step Functions 任务类型。

本节中的示例使用以下 Systems Manager 操作来更新维护时段。
+ [UpdateMaintenanceWindow](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_UpdateMaintenanceWindow.html)
+ [UpdateMaintenanceWindowTarget](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_UpdateMaintenanceWindowTarget.html)
+ [UpdateMaintenanceWindowTask](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_UpdateMaintenanceWindowTask.html)
+ [DeregisterTargetFromMaintenanceWindow](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DeregisterTargetFromMaintenanceWindow.html)

有关使用 Systems Manager 控制台来更新维护时段的信息，请参阅 [使用控制台更新或删除维护时段资源](sysman-maintenance-update.md)。

在按照本教程中的步骤操作时，请将以斜体*红色*文本显示的值替换为您自己的选项和 ID。例如，请将维护时段 ID *mw-0c50858d01EXAMPLE* 和实例 ID *i-02573cafcfEXAMPLE* 替换为您创建的资源的 ID。

**要使用 AWS CLI 更新维护时段**

1. 打开 AWS CLI 并运行以下命令将目标更新为包括名称和描述。

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

   ```
   aws ssm update-maintenance-window-target \
       --window-id "mw-0c50858d01EXAMPLE" \
       --window-target-id "e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE" \
       --name "My-Maintenance-Window-Target" \
       --description "Description for my maintenance window target"
   ```

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

   ```
   aws ssm update-maintenance-window-target ^
       --window-id "mw-0c50858d01EXAMPLE" ^
       --window-target-id "e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE" ^
       --name "My-Maintenance-Window-Target" ^
       --description "Description for my maintenance window target"
   ```

------

   系统返回类似于以下内容的信息。

   ```
   {
       "WindowId": "mw-0c50858d01EXAMPLE",
       "WindowTargetId": "e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE",
       "Targets": [
           {
               "Key": "InstanceIds",
               "Values": [
                   "i-02573cafcfEXAMPLE"
               ]
           }
       ],
       "Name": "My-Maintenance-Window-Target",
       "Description": "Description for my maintenance window target"
   }
   ```

1. 运行以下命令，使用 `replace` 选项来删除描述字段和添加更多目标。描述字段被删除，因为更新不包含该字段（空值）。请务必指定已配置为用于 Systems Manager 的其他节点。

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

   ```
   aws ssm update-maintenance-window-target \
       --window-id "mw-0c50858d01EXAMPLE" \
       --window-target-id "d208dedf-3f6b-41ff-ace8-8e751EXAMPLE" \
       --targets "Key=InstanceIds,Values=i-02573cafcfEXAMPLE,i-0471e04240EXAMPLE" \
       --name "My-Maintenance-Window-Target" \
       --replace
   ```

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

   ```
   aws ssm update-maintenance-window-target ^
       --window-id "mw-0c50858d01EXAMPLE" ^
       --window-target-id "d208dedf-3f6b-41ff-ace8-8e751EXAMPLE" ^
       --targets "Key=InstanceIds,Values=i-02573cafcfEXAMPLE,i-0471e04240EXAMPLE" ^
       --name "My-Maintenance-Window-Target" ^
       --replace
   ```

------

   系统返回类似于以下内容的信息。

   ```
   {
       "WindowId": "mw-0c50858d01EXAMPLE",
       "WindowTargetId": "e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE",
       "Targets": [
           {
               "Key": "InstanceIds",
               "Values": [
                   "i-02573cafcfEXAMPLE",
                   "i-0471e04240EXAMPLE"
               ]
           }
       ],
       "Name": "My-Maintenance-Window-Target"
   }
   ```

1. `start-date` 选项用于将维护时段的激活时间延迟到一个指定的未来日期。`end-date` 选项用于设置在某个未来的日期和时间后不再运行维护时段。请以 ISO-8601 扩展格式指定这些选项。

   运行以下命令可为定期执行的维护时段指定日期和时间范围。

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

   ```
   aws ssm update-maintenance-window \
       --window-id "mw-0c50858d01EXAMPLE" \
       --start-date "2020-10-01T10:10:10Z" \
       --end-date "2020-11-01T10:10:10Z"
   ```

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

   ```
   aws ssm update-maintenance-window ^
       --window-id "mw-0c50858d01EXAMPLE" ^
       --start-date "2020-10-01T10:10:10Z" ^
       --end-date "2020-11-01T10:10:10Z"
   ```

------

1. 运行以下命令可更新 Run Command 任务。
**提示**  
如果您的目标是 Windows Server 的 Amazon Elastic Compute Cloud (Amazon EC2) 实例，请将以下命令中的 `df` 更改为 `ipconfig`，并将 `AWS-RunShellScript` 更改为 `AWS-RunPowerShellScript`。

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

   ```
   aws ssm update-maintenance-window-task \
       --window-id "mw-0c50858d01EXAMPLE" \
       --window-task-id "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE" \
       --targets "Key=WindowTargetIds,Values=e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE" \
       --task-arn "AWS-RunShellScript" \
       --service-role-arn "arn:aws:iam::account-id:role/MaintenanceWindowsRole" \
       --task-invocation-parameters "RunCommand={Comment=Revising my Run Command task,Parameters={commands=df}}" \
       --priority 1 --max-concurrency 10 --max-errors 4 \
       --name "My-Task-Name" --description "A description for my Run Command task"
   ```

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

   ```
   aws ssm update-maintenance-window-task ^
       --window-id "mw-0c50858d01EXAMPLE" ^
       --window-task-id "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE" ^
       --targets "Key=WindowTargetIds,Values=e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE" ^
       --task-arn "AWS-RunShellScript" ^
       --service-role-arn "arn:aws:iam::account-id:role/MaintenanceWindowsRole" ^
       --task-invocation-parameters "RunCommand={Comment=Revising my Run Command task,Parameters={commands=df}}" ^
       --priority 1 --max-concurrency 10 --max-errors 4 ^
       --name "My-Task-Name" --description "A description for my Run Command task"
   ```

------

   系统返回类似于以下内容的信息。

   ```
   {
       "WindowId": "mw-0c50858d01EXAMPLE",
       "WindowTaskId": "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE",
       "Targets": [
           {
               "Key": "WindowTargetIds",
               "Values": [
                   "e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE"
               ]
           }
       ],
       "TaskArn": "AWS-RunShellScript",
       "ServiceRoleArn": "arn:aws:iam::111122223333:role/MaintenanceWindowsRole",
       "TaskParameters": {},
       "TaskInvocationParameters": {
           "RunCommand": {
               "Comment": "Revising my Run Command task",
               "Parameters": {
                   "commands": [
                       "df"
                   ]
               }
           }
       },
       "Priority": 1,
       "MaxConcurrency": "10",
       "MaxErrors": "4",
       "Name": "My-Task-Name",
       "Description": "A description for my Run Command task"
   }
   ```

1. 改写并运行以下命令以更新 Lambda 任务。

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

   ```
   aws ssm update-maintenance-window-task \
       --window-id mw-0c50858d01EXAMPLE \
       --window-task-id 4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE \
       --targets "Key=WindowTargetIds,Values=e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE" \
       --task-arn "arn:aws:lambda:region:111122223333:function:SSMTestLambda" \
       --service-role-arn "arn:aws:iam:account-id:role/MaintenanceWindowsRole" \
       --task-invocation-parameters '{"Lambda":{"Payload":"{\"InstanceId\":\"{{RESOURCE_ID}}\",\"targetType\":\"{{TARGET_TYPE}}\"}"}}' \
       --priority 1 --max-concurrency 10 --max-errors 5 \
       --name "New-Lambda-Task-Name" \
       --description "A description for my Lambda task"
   ```

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

   ```
   aws ssm update-maintenance-window-task ^
       --window-id mw-0c50858d01EXAMPLE ^
       --window-task-id 4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE ^
       --targets "Key=WindowTargetIds,Values=e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE" ^
       --task-arn --task-arn "arn:aws:lambda:region:111122223333:function:SSMTestLambda" ^
       --service-role-arn "arn:aws:iam:account-id:role/MaintenanceWindowsRole" ^
       --task-invocation-parameters '{"Lambda":{"Payload":"{\"InstanceId\":\"{{RESOURCE_ID}}\",\"targetType\":\"{{TARGET_TYPE}}\"}"}}' ^
       --priority 1 --max-concurrency 10 --max-errors 5 ^
       --name "New-Lambda-Task-Name" ^
       --description "A description for my Lambda task"
   ```

------

   系统返回类似于以下内容的信息。

   ```
   {
       "WindowId": "mw-0c50858d01EXAMPLE",
       "WindowTaskId": "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE",
       "Targets": [
           {
               "Key": "WindowTargetIds",
               "Values": "e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE"
           }
       ],
       "TaskArn": "arn:aws:lambda:us-east-2:111122223333:function:SSMTestLambda",
       "ServiceRoleArn": "arn:aws:iam::111122223333:role/MaintenanceWindowsRole",
       "TaskParameters": {},
       "TaskInvocationParameters": {
           "Lambda": {
               "Payload": "e30="
           }
       },
       "Priority": 1,
       "MaxConcurrency": "10",
       "MaxErrors": "5",
       "Name": "New-Lambda-Task-Name",
       "Description": "A description for my Lambda task"
   }
   ```

1. 如果您要更新 Step Functions 任务，请改写并运行以下命令，以更新其 task-invocation-parameters。

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

   ```
   aws ssm update-maintenance-window-task \
       --window-id "mw-0c50858d01EXAMPLE" \
       --window-task-id "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE" \
       --targets "Key=WindowTargetIds,Values=e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE" \
       --task-arn "arn:aws:states:region:execution:SSMStepFunctionTest" \
       --service-role-arn "arn:aws:iam:account-id:role/MaintenanceWindowsRole" \
       --task-invocation-parameters '{"StepFunctions":{"Input":"{\"InstanceId\":\"{{RESOURCE_ID}}\"}"}}' \
       --priority 0 --max-concurrency 10 --max-errors 5 \
       --name "My-Step-Functions-Task" \
       --description "A description for my Step Functions task"
   ```

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

   ```
   aws ssm update-maintenance-window-task ^
       --window-id "mw-0c50858d01EXAMPLE" ^
       --window-task-id "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE" ^
       --targets "Key=WindowTargetIds,Values=e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE" ^
       --task-arn "arn:aws:states:region:execution:SSMStepFunctionTest" ^
       --service-role-arn "arn:aws:iam:account-id:role/MaintenanceWindowsRole" ^
       --task-invocation-parameters '{"StepFunctions":{"Input":"{\"InstanceId\":\"{{RESOURCE_ID}}\"}"}}' ^
       --priority 0 --max-concurrency 10 --max-errors 5 ^
       --name "My-Step-Functions-Task" ^
       --description "A description for my Step Functions task"
   ```

------

   系统返回类似于以下内容的信息。

   ```
   {
       "WindowId": "mw-0c50858d01EXAMPLE",
       "WindowTaskId": "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE",
       "Targets": [
           {
               "Key": "WindowTargetIds",
               "Values": [
                   "e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE"
               ]
           }
       ],
       "TaskArn": "arn:aws:states:us-east-2:111122223333:execution:SSMStepFunctionTest",
       "ServiceRoleArn": "arn:aws:iam::111122223333:role/MaintenanceWindowsRole",
       "TaskParameters": {},
       "TaskInvocationParameters": {
           "StepFunctions": {
               "Input": "{\"instanceId\":\"{{RESOURCE_ID}}\"}"
           }
       },
       "Priority": 0,
       "MaxConcurrency": "10",
       "MaxErrors": "5",
       "Name": "My-Step-Functions-Task",
       "Description": "A description for my Step Functions task"
   }
   ```

1. 运行以下命令可从维护时段中注销目标。本示例使用 `safe` 参数确定目标是否被任何任务引用，从而确定注销是否安全。

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

   ```
   aws ssm deregister-target-from-maintenance-window \
       --window-id "mw-0c50858d01EXAMPLE" \
       --window-target-id "e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE" \
       --safe
   ```

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

   ```
   aws ssm deregister-target-from-maintenance-window ^
       --window-id "mw-0c50858d01EXAMPLE" ^
       --window-target-id "e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE" ^
       --safe
   ```

------

   系统返回类似于以下内容的信息。

   ```
   An error occurred (TargetInUseException) when calling the DeregisterTargetFromMaintenanceWindow operation: 
   This Target cannot be deregistered because it is still referenced in Task: 4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE
   ```

1. 运行以下命令可从维护时段注销目标，即使该目标已被某个任务引用。您可以使用 `no-safe` 参数强制执行注销操作。

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

   ```
   aws ssm deregister-target-from-maintenance-window \
       --window-id "mw-0c50858d01EXAMPLE" \
       --window-target-id "e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE" \
       --no-safe
   ```

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

   ```
   aws ssm deregister-target-from-maintenance-window ^
       --window-id "mw-0c50858d01EXAMPLE" ^
       --window-target-id "e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE" ^
       --no-safe
   ```

------

   系统返回类似于以下内容的信息。

   ```
   {
       "WindowId": "mw-0c50858d01EXAMPLE",
       "WindowTargetId": "e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE"
   }
   ```

1. 运行以下命令可更新 Run Command 任务。此示例使用名为 `UpdateLevel` 的 Systems Manager Parameter Store 参数，其格式如下所示：“`{{ssm:UpdateLevel}}`”

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

   ```
   aws ssm update-maintenance-window-task \
       --window-id "mw-0c50858d01EXAMPLE" \
       --window-task-id "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE" \
       --targets "Key=InstanceIds,Values=i-02573cafcfEXAMPLE"  \
       --task-invocation-parameters "RunCommand={Comment=A comment for my task update,Parameters={UpdateLevel='{{ssm:UpdateLevel}}'}}"
   ```

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

   ```
   aws ssm update-maintenance-window-task ^
       --window-id "mw-0c50858d01EXAMPLE" ^
       --window-task-id "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE" ^
       --targets "Key=InstanceIds,Values=i-02573cafcfEXAMPLE"  ^
       --task-invocation-parameters "RunCommand={Comment=A comment for my task update,Parameters={UpdateLevel='{{ssm:UpdateLevel}}'}}"
   ```

------

   系统返回类似于以下内容的信息。

   ```
   {
       "WindowId": "mw-0c50858d01EXAMPLE",
       "WindowTaskId": "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE",
       "Targets": [
           {
               "Key": "InstanceIds",
               "Values": [
                   "i-02573cafcfEXAMPLE"
               ]
           }
       ],
       "TaskArn": "AWS-RunShellScript",
       "ServiceRoleArn": "arn:aws:iam::111122223333:role/MyMaintenanceWindowServiceRole",
       "TaskParameters": {},
       "TaskInvocationParameters": {
           "RunCommand": {
               "Comment": "A comment for my task update",
               "Parameters": {
                   "UpdateLevel": [
                       "{{ssm:UpdateLevel}}"
                   ]
               }
           }
       },
       "Priority": 10,
       "MaxConcurrency": "1",
       "MaxErrors": "1"
   }
   ```

1. 运行以下命令可更新 自动化 任务，为 `task-invocation-parameters` 参数指定 `WINDOW_ID` 和 `WINDOW_TASK_ID` 参数：

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

   ```
   aws ssm update-maintenance-window-task \
       --window-id "mw-0c50858d01EXAMPLE" \
       --window-task-id "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE" \
       --targets "Key=WindowTargetIds,Values=e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE \
       --task-arn "AutoTestDoc" \
       --service-role-arn "arn:aws:iam:account-id:role/MyMaintenanceWindowServiceRole \
       --task-invocation-parameters "Automation={Parameters={InstanceId='{{RESOURCE_ID}}',initiator='{{WINDOW_ID}}.Task-{{WINDOW_TASK_ID}}'}}" \
       --priority 3 --max-concurrency 10 --max-errors 5
   ```

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

   ```
   aws ssm update-maintenance-window-task ^
       --window-id "mw-0c50858d01EXAMPLE" ^
       --window-task-id "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE" ^
       --targets "Key=WindowTargetIds,Values=e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE ^
       --task-arn "AutoTestDoc" ^
       --service-role-arn "arn:aws:iam:account-id:role/MyMaintenanceWindowServiceRole ^
       --task-invocation-parameters "Automation={Parameters={InstanceId='{{RESOURCE_ID}}',initiator='{{WINDOW_ID}}.Task-{{WINDOW_TASK_ID}}'}}" ^
       --priority 3 --max-concurrency 10 --max-errors 5
   ```

------

   系统返回类似于以下内容的信息。

   ```
   {
       "WindowId": "mw-0c50858d01EXAMPLE",
       "WindowTaskId": "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE",
       "Targets": [
           {
               "Key": "WindowTargetIds",
               "Values": [
                   "e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE"
               ]
           }
       ],
       "TaskArn": "AutoTestDoc",
       "ServiceRoleArn": "arn:aws:iam::111122223333:role/MyMaintenanceWindowServiceRole",
       "TaskParameters": {},
       "TaskInvocationParameters": {
           "Automation": {
               "Parameters": {
                   "multi": [
                       "{{WINDOW_TASK_ID}}"
                   ],
                   "single": [
                       "{{WINDOW_ID}}"
                   ]
               }
           }
       },
       "Priority": 0,
       "MaxConcurrency": "10",
       "MaxErrors": "5",
       "Name": "My-Automation-Task",
       "Description": "A description for my Automation task"
   }
   ```

# 教程：使用 AWS CLI 删除维护时段
<a name="mw-cli-tutorial-delete-mw"></a>

要删除您在这些教程中创建的维护时段，请运行以下命令。

```
aws ssm delete-maintenance-window --window-id "mw-0c50858d01EXAMPLE"
```

系统返回类似于以下内容的信息。

```
{
   "WindowId":"mw-0c50858d01EXAMPLE"
}
```