

• 2026 年 4 月 30 日之後， AWS Systems Manager CloudWatch Dashboard 將不再可用。客戶可以繼續使用 Amazon CloudWatch 主控台來檢視、建立和管理其 Amazon CloudWatch 儀表板，就像現在一樣。如需詳細資訊，請參閱 [Amazon CloudWatch Dashboard 文件](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Dashboards.html)。

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

# 教學課程：使用 建立和設定維護時段 AWS CLI
<a name="maintenance-windows-cli-tutorials-create"></a>

本教學課程示範如何使用 AWS Command Line Interface (AWS CLI) 來建立和設定維護時段、其目標及其任務。此教學的主要過程包含幾個簡單的步驟。建立一個維護時段、識別單一目標，並為要執行的維護時段設定簡單的任務。我們會在過程中提供您可用來嘗試更複雜案例的資訊。

當您按照此教學課程中的步驟，使用自己的選項和 ID 來取代斜體*紅色*文字。例如，使用您所建立之資源 ID 取代維護時段 ID *mw-0c50858d01EXAMPLE* 和執行個體 ID *i-02573cafcfEXAMPLE*。

**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) 並在本機電腦上執行下列命令，以建立執行下列動作的維護時段：
   + 每 5 分鐘執行一次，持續時間長達兩個小時 (視需要)。
   + 避免讓新任務在維護時段操作結束的 1 小時內啟動。
   + 允許沒有關聯的目標可讓您尚未註冊 (您未向維護時段註冊的執行個體)。
   + 自訂標籤的使用，表示其建立者想要在教學中使用它。

------
#### [ 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，除了下列範例中指定的配額之外，請參閱《》中的 [Systems Manager 服務配額](https://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm)*Amazon Web Services 一般參考*。

## 範例 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"
```

------

**建議使用**：在第一次使用任何維護時段註冊唯一一組的節點時非常有用，但它們「會」**共用常見的節點標籤。

**配額：**您可以為每個目標指定總計最多五個鍵值組。如果您指定了多個鍵值對，則節點必須加上您指定的*所有*標籤鍵和值，才會包含在目標群組中。

**注意**  
您可以使用標籤金鑰 `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"
```

------

**建議使用**：當您想要透過指定多個標籤*索引鍵* (不含其值)，而不只是一個標籤索引鍵或標籤索引鍵值對，來鎖定節點時很有用。

**配額：**您可以為每個目標指定總計最多五個標籤鍵。如果您指定多個標籤鍵，則節點必須加上您指定的*所有*標籤鍵，才會包含在目標群組中。

## 範例 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 的 Amazon EC2 執行個體為目標 (而不是 Linux)，請在下列命令中以 **ipconfig** 取代 **df**。此命令中的輸出會列出在目標執行個體上適用於轉接器的 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 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 Automation 工作流程、 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 傳遞給 Automation、Lambda 和 Step Functions 任務。如需 `--task-invocation-parameters` 內容中虛擬參數的詳細資訊，請參閱[註冊維護時段任務時使用虛擬參數](maintenance-window-tasks-pseudo-parameters.md)。

**詳細資訊**  
+ [register-task-with-maintenance-windows 命令的參數選項](mw-cli-task-options.md).
+ 《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) 一節
+ *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 Automation 任務
<a name="register-tasks-tutorial-automation"></a>

以下範例示範如何使用 AWS CLI向維護時段註冊 Systems Manager Automation 任務：

**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 政策需要您為 Lambda 函數 (或別名) 名稱新增 `SSM` 字首。在您繼續註冊此類任務之前，請在 中更新其名稱 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)。

對於這些範例，建立步驟函數狀態機器的使用者會使用名為 `instanceId` 的參數建立名為 `SSMMyStateMachine` 的狀態機器。

**重要**  
的 AWS Identity and Access Management (IAM) 政策Maintenance Windows需要您在 Step Functions 狀態機器名稱前面加上 `SSM`。在繼續註冊這類任務前，您必須在 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 政策需要您為 Lambda 函數 (或別名) 名稱新增 `SSM` 字首。在您繼續註冊此類任務之前，請在 中更新其名稱 AWS Lambda 以包含 `SSM`。例如，如果 Lambda 函數名稱為 `MyLambdaFunction`，請變更為 `SSMMyLambdaFunction`。   | 
|  **`STEP_FUNCTIONS`**  |  `TaskArn` 是狀態機器的 ARN。例如： `arn:aws:states:us-east-2:111122223333:stateMachine:SSMMyStateMachine`.  維護時段的 IAM 政策需要您為 Step Functions 狀態機器名稱加上 `SSM` 字首。註冊這類任務前，您必須在 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>  | 