

• 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)。

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

# 結構描述、功能以及範例
<a name="documents-schemas-features"></a>

AWS Systems Manager (SSM) 文件使用以下結構描述版本。
+ `Command` 類型的文件可以使用結構描述 1.2、2.0 和 2.2 版本。如果您使用的文件為結構描述 1.2 版本，我們建議您使用結構描述 2.2 版本建立文件。
+ `Policy` 類型的文件必須使用結構描述 2.0 版本或更新版本。
+ `Automation` 類型的文件必須使用結構描述 0.3 版本。
+ `Session` 類型的文件必須使用結構描述 1.0 版本。
+ 您可以以 JSON 或 YAML 建立文件。

如需有關`Session`文件結構描述的詳細資訊，請參閱[工作階段文件結構描述](session-manager-schema.md)。

`Command` 和 `Policy` 文件使用最新的結構描述版本，您可以善用以下功能。


**結構描述版本 2.2 文件的功能**  

| 功能 | 詳細資訊 | 
| --- | --- | 
|  文件編輯  |  文件現在可以進行更新。在版本 1.2 中，您需要將文件中任何更新儲存為不同名稱的文件。  | 
|  自動版本控制  |  文件中任何更新建立新的版本。這並非結構描述的版本，而是文件的版本。  | 
|  預設版本  |  如果您有多個版本的文件，您可以指定哪個版本為預設的文件。  | 
|  定序  |  文件中中的外掛程式或*步驟*將按照您所指定的順序執行。  | 
|  跨平台支援  |  跨平台支援允許您在相同的 SSM 文件中為不同的外掛程式指定不同的作業系統。跨平台支援使用 `precondition` 參數，只需要幾個步驟。  | 
| 參數插補 | 插補表示將變數值插入或替換為字串。將其視為在使用字串前，使用實際值填入空格。在 SSM 文件環境中，參數插補允許字串參數在命令執行之前，插入到環境變數中，提供更高安全性以防止命令注入。設定為 `ENV_VAR` 時，Agent 會建立名為 `SSM_parameter-name` 的環境變數，其中包含參數的值。 | 

**注意**  
您必須將執行個體上的 AWS Systems Manager SSM Agent 更新為最新版本，才能使用新的 Systems Manager 功能和 SSM 文件功能。如需詳細資訊，請參閱[使用 Run Command 更新 SSM Agent](run-command-tutorial-update-software.md#rc-console-agentexample)。

下表列出了主要的結構描述各版本的差異。


****  

| 第 1.2 版 | 版本 2.2 (最新版本) | 詳細資訊 | 
| --- | --- | --- | 
|  runtimeConfig  |  mainSteps  |  在版本 2.2 中，`mainSteps` 區塊取代了 `runtimeConfig`。`mainSteps` 區段可讓 Systems Manager 按順序執行步驟。  | 
|  屬性  |  inputs  |  在版本 2.2 中，`inputs` 區塊取代了 `properties` 區塊。`inputs` 區塊接受了參數的做法步驟。  | 
|  commands  |  runCommand  |  在版本 2.2 中，`inputs` 區塊接受 `runCommand` 的參數，而非 `commands` 的參數。  | 
|  id  |  動作  |  在版本 2.2 中，`Action` 取代了 `ID`。這是名稱變更。  | 
|  不適用  |  name  |  在版本 2.2 中，`name` 是一個任何使用者替步驟定義的名稱。  | 

**使用 precondition 參數**  
使用結構描述 2.2 版或更新版本，您可以使用 `precondition` 參數為每個外掛程式指定目標作業系統，或驗證您在 SSM 文件中定義的輸入參數。`precondition` 參數支援引用 SSM 文件的輸入參數，以及使用值 `Linux`、`MacOS` 以及 `Windows` 的 `platformType`。只支援 `StringEquals` 運算子。

對於文件使用結構描述版本 2.2 或更新版本，如果未指定 `precondition`，每個外掛程式是根據外掛程式的相容性來決定在作業系統執行或略過。與作業系統的外掛程式相容性會在 `precondition` 之前評估。對於文件使用結構描述 2.0 或更舊版本，不相容的外掛程式會產生錯誤。

例如，在結構描述版本 2.2 文件中，如果未指定 `precondition` 但有列出`aws:runShellScript` 外掛程式，則在 Linux 執行個體上會執行該步驟，但在 Windows Server 執行個體上會略過該步驟，因為 `aws:runShellScript` 與 Windows Server 執行個體不相容。但就結構描述版本 2.0 文件來說，如果您指定 `aws:runShellScript` 外掛程式，然後在 Windows Server 執行個體上執行該文件，則執行會失敗。您可以在本節稍後的 SSM 文件中查看先決條件參數範例。

## 結構描述版本 2.2
<a name="documents-schema-twox"></a>

**頂層元素**  
以下範例顯示使用結構描述版本 2.2 的 SSM 文件上層元素。

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

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

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

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

------

**結構描述版本 2.2 範例**  
下列範例會使用 `aws:runPowerShellScript` 外掛程式在目標執行個體上執行 PowerShell 命令。

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

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

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

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

------

**結構描述版本 2.2 precondition 參數範例**  
結構描述版本 2.2 提供跨平台支援。這表示您可以在同一個 SSM 文件中為不同的外掛程式指定不同的作業系統。跨平台支援在步驟中使用 `precondition` 參數，如下所示。您也可以使用 `precondition` 參數來驗證您在 SSM 文件中定義的輸入參數。您可以在以下第二個範例中看到它。

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

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

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

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

------

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

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

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

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

------

**具有 3.3.2746.0 之前 SSM Agent 版本的結構描述 2.2 版插補範例**  
在 3.3.2746.0 之前的 SSM Agent 版本上，Agent 會忽略 `interpolationType` 參數，並改為執行原始字串替換。如果您明確參考 `SSM_parameter-name`，則必須明確設定此項目。在下列的 Linux 範例中，明確參考了 `SSM_Message` 環境變數。

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

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

**注意**  
如果 SSM 文件不使用雙括號，則技術上不需要 `allowedPattern`：`{{ }}`

**結構描述版本 2.2 State Manager 範例**  
您可以搭配使用以下 SSM 文件與 State Manager (Systems Manager 中的工具)，以下載並安裝 ClamAV 防毒軟體。State Manager 會強制實施特定組態，這表示每次執行 State Manager 關聯時，系統會檢查是否已安裝 ClamAV 軟體。如果不是，State Manager 會重新執行此文件。

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

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

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

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

------

**結構描述版本 2.2 庫存範例**  
您可以搭配使用以下 SSM 文件與 State Manager，收集有關執行個體的庫存中繼資料。

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

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

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

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

------

**結構描述版本 2.2 `AWS-ConfigureAWSPackage` 範例**  
以下範例顯示 `AWS-ConfigureAWSPackage` 文件。`mainSteps` 區段包含 `action` 步驟中的 `aws:configurePackage` 外掛程式。

**注意**  
在 Linux 作業系統上，只有支援 `AmazonCloudWatchAgent` 和 `AWSSupport-EC2Rescue` 的套件。

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

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

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

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

------

## 結構描述版本 1.2
<a name="documents-schema-onex"></a>

以下範例顯示結構描述版本 1.2 文件的上層元素。

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

**結構描述版本 1.2 `aws:runShellScript` 範例**  
以下範例顯示 `AWS-RunShellScript` SSM 文件。**runtimeConfig** 區段包含 `aws:runShellScript` 外掛程式。

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

## 結構描述版本 0.3
<a name="automation-doc-syntax-examples"></a>

**頂層元素**  
下列範例以 JSON 格式顯示結構描述 0.3 版 Automation Runbook 的最上層元素。

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

**YAML Automation Runbook 範例**  
下列範例以 YAML 格式顯示 Automation Runbook 的內容。文件結構描述的這份 0.3 版運作範例，也示範了如何使用 Markdown 來格式化文件描述。

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

  -----

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


  ##Parameters:

  -----

  Name | Type | Description | Default Value

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

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

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


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

          ec2 = boto3.client('ec2')

          instance_id = events['InstanceId']

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

          instance_status = "null"

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

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

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

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

            if instance_status == 'ok':
              break

            time.sleep(10)

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


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

## 安全參數處理範例
<a name="secure-parameter-examples"></a>

下列範例示範使用環境變數 `interpolationType` 來安全處理參數。

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

此範例說明如何安全地處理命令參數：

**注意**  
在不使用雙括號的 SSM 文件中，技術上不需要 `allowedPattern`：`{{ }}`

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

```
---

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

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

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

------

### 以編譯語言使用參數
<a name="interpreted-language-example"></a>

此範例示範在 Python 中安全處理參數：

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

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

------

### 回溯相容性範例
<a name="backwards-compatibility-example"></a>

此範例說明如何安全地處理參數，同時保持回溯相容性：

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

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

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

------

**注意**  
在不使用雙括號的 SSM 文件中，技術上不需要 `allowedPattern`：`{{ }}`

## 參數安全最佳實務
<a name="parameter-security-best-practices"></a>

處理 SSM 文件中的參數時，請遵循下列最佳實務：
+ **使用環境變數插補** – 一律將 `interpolationType: "ENV_VAR"` 用於在命令執行中使用的字串參數。
+ **實作輸入驗證** – 使用 `allowedPattern`，將參數值限制為安全模式。
+ **處理舊式系統** – 包含不支援環境變數插補之舊版 SSM Agent 的備用邏輯。
+ **逸出特殊字元** – 在命令中使用參數值時，請正確逸出特殊字元，以防止 shell 解譯。
+ **限制參數範圍** – 為您的使用案例使用最嚴格的參數模式。