

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

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

# Systems Manager Automation 動作參考
<a name="automation-actions"></a>

此參考描述您可在 Automation Runbook 中指定的自動化動作。Automation 是 AWS Systems Manager中的工具。這些動作無法用於其他類型的 Systems Manager (SSM) 文件中。如需其他 SSM 文件類型的外掛程式詳細資訊，請參閱 [命令文件外掛程式參考](documents-command-ssm-plugin-reference.md)。

Systems Manager Automation 會執行 Automation Runbook 中定義的步驟。每個步驟皆與一個特定動作關聯。動作會決定輸入、行為和步驟的輸出。Runbook 的 `mainSteps` 章節中會定義步驟。

您不需要指定動作或步驟的輸出。輸出是由與步驟關聯的動作預先定義。在 Runbook 中指定步驟輸入時，您可以參考先前步驟的一個或多個輸出。例如，您可以讓 `aws:runInstances` 輸出用於後續的 `aws:runCommand` 動作。您也可以參考 Runbook `Output` 區段中先前步驟的輸出。

**重要**  
如果您執行可使用 AWS Identity and Access Management (IAM) 服務角色叫用其他服務的自動化工作流程，請注意您必須為該服務角色設定可叫用這些服務的許可。此需求適用於所有 AWS Automation Runbook (`AWS-*` Runbook)，例如 `AWS-ConfigureS3BucketLogging`、 `AWS-CreateDynamoDBBackup`和 `AWS-RestartEC2Instance` Runbook。此要求也適用於您建立的任何自訂 Automation Runbook， AWS 服務 其會透過呼叫其他 服務的動作來叫用其他 。例如，如果您使用 `aws:executeAwsApi`、`aws:createStack` 或 `aws:copyImage` 動作，為服務角色設定可叫用這些服務的許可。您可新增 IAM 內嵌政策到角色，以啟用其他 AWS 服務 的許可。如需詳細資訊，請參閱[（選用） 新增自動化內嵌政策或客戶受管政策以叫用其他 AWS 服務](automation-setup-iam.md#add-inline-policy)。

**Topics**
+ [依所有動作共用的屬性](#automation-common)
+ [`aws:approve` – 暫停自動化以進行手動核准](automation-action-approve.md)
+ [`aws:assertAwsResourceProperty` – 宣告 AWS 資源狀態或事件狀態](automation-action-assertAwsResourceProperty.md)
+ [`aws:branch` – 執行條件式自動化步驟](automation-action-branch.md)
+ [`aws:changeInstanceState` – 變更或宣告執行個體狀態](automation-action-changestate.md)
+ [`aws:copyImage` – 複製或加密 Amazon Machine Image](automation-action-copyimage.md)
+ [`aws:createImage` – 建立 Amazon Machine Image](automation-action-create.md)
+ [`aws:createStack` – 建立 CloudFormation 堆疊](automation-action-createstack.md)
+ [`aws:createTags` – 建立 AWS 資源的標籤](automation-action-createtag.md)
+ [`aws:deleteImage` – 刪除 Amazon Machine Image](automation-action-delete.md)
+ [`aws:deleteStack` – 刪除 CloudFormation 堆疊](automation-action-deletestack.md)
+ [`aws:executeAutomation` – 執行另一項自動化](automation-action-executeAutomation.md)
+ [`aws:executeAwsApi` – 呼叫並執行 AWS API 操作](automation-action-executeAwsApi.md)
+ [`aws:executeScript` – 執行指令碼](automation-action-executeScript.md)
+ [`aws:executeStateMachine` – 執行 AWS Step Functions 狀態機器](automation-action-executeStateMachine.md)
+ [`aws:invokeWebhook`：叫用 Automation Webhook 整合](invoke-webhook.md)
+ [`aws:invokeLambdaFunction` – 叫用 AWS Lambda 函數](automation-action-lamb.md)
+ [`aws:loop` - 迭代自動化中的步驟](automation-action-loop.md)
+ [`aws:pause` – 暫停自動化](automation-action-pause.md)
+ [`aws:runCommand` – 在受管執行個體上執行命令](automation-action-runcommand.md)
+ [`aws:runInstances` – 啟動 Amazon EC2 執行個體。](automation-action-runinstance.md)
+ [`aws:sleep` – 延遲自動化](automation-action-sleep.md)
+ [`aws:updateVariable` - 更新執行手冊變數的值](automation-action-update-variable.md)
+ [`aws:waitForAwsResourceProperty` – 等待 AWS 資源屬性](automation-action-waitForAwsResourceProperty.md)
+ [自動化系統變數](automation-variables.md)

## 依所有動作共用的屬性
<a name="automation-common"></a>

一般屬性是可在所有動作中找到的參數或選項。某些選項會定義步驟的行為，例如，等待步驟完成的時間，以及如果步驟失敗時該怎麼做。以下為所有動作中常見的屬性。

[description](#descriptProp)  
您提供用於描述執行手冊或步驟之目的的資訊。  
類型：字串  
必要：否

[name](#nameProp)  
一種識別符，在 Runbook 的所有步驟名稱中必須獨一無二。  
類型：字串  
允許的模式：[a-zA-Z0-9\$1]\$1\$1  
必要：是

[action](#actProp)  
步驟要執行的動作名稱。[`aws:runCommand` – 在受管執行個體上執行命令](automation-action-runcommand.md) 是您可以在此指定的動作範例。此文件提供所有可用動作的詳細資訊。  
類型：字串  
必要：是

[maxAttempts](#maxProp)  
步驟在故障時應重試的次數。如果值大於 1，則在所有重試嘗試失敗之前，步驟不會視為失敗。預設值為 1.  
類型：整數  
必要：否

[timeoutSeconds](#timeProp)  
步驟的逾時值。如果達到逾時且 `maxAttempts` 的值大於 1，則在嘗試完所有重試之前，步驟不會視為逾時。  
類型：整數  
必要：否

[onFailure](#failProp)  
指示自動化在失敗時應中止、繼續或前往不同的步驟。此選項的預設值為 abort。  
類型：字串  
有效值：Abort \$1 Continue \$1 step:*step\$1name*  
必要：否

[onCancel](#canProp)  
指出當使用者取消自動化時，自動化應移至哪個步驟。自動化會執行取消工作流程最多兩分鐘。  
類型：字串  
有效值：Abort \$1 step:*step\$1name*  
必要：否  
`onCancel` 屬性不支援移至下列動作：  
+ `aws:approve`
+ `aws:copyImage`
+ `aws:createImage`
+ `aws:createStack`
+ `aws:createTags`
+ `aws:loop`
+ `aws:pause`
+ `aws:runInstances`
+ `aws:sleep`

[isEnd](#endProp)  
此選項會在特定步驟結束時停止自動化。如果步驟執行失敗或成功，自動化就會停止。預設值為 false。  
類型：布林值  
有效值：true \$1 false  
必要：否

[nextStep](#nextProp)  
指定在成功完成步驟後要接著處理自動化中的哪個步驟。  
類型：字串  
必要：否

[isCritical](#critProp)  
指定某個步驟是成功完成自動化的關鍵。如果此指定步驟失敗，則自動化會將自動化的最終狀態回報為 Failed (失敗)。只有當您在步驟中明確定義此屬性時，才會評估此屬性。如果 `onFailure` 屬性在步驟中已設為 `Continue`，則該值預設為 false。否則，此選項的預設值為 true。  
類型：布林值  
有效值：true \$1 false  
必要：否

[inputs](#inProp)  
專屬於動作的屬性。  
類型：映射  
必要：是

### 範例
<a name="automation-demo"></a>

```
---
description: "Custom Automation Example"
schemaVersion: '0.3'
assumeRole: "{{ AutomationAssumeRole }}"
parameters:
  AutomationAssumeRole:
    type: String
    description: "(Required) The ARN of the role that allows Automation to perform
      the actions on your behalf. If no role is specified, Systems Manager Automation
      uses your IAM permissions to run this runbook."
    default: ''
  InstanceId:
      type: String
      description: "(Required) The Instance Id whose root EBS volume you want to restore the latest Snapshot."
      default: ''
mainSteps:
- name: getInstanceDetails
  action: aws:executeAwsApi
  onFailure: Abort
  inputs:
    Service: ec2
    Api: DescribeInstances
    InstanceIds:
    - "{{ InstanceId }}"
  outputs:
    - Name: availabilityZone
      Selector: "$.Reservations[0].Instances[0].Placement.AvailabilityZone"
      Type: String
    - Name: rootDeviceName
      Selector: "$.Reservations[0].Instances[0].RootDeviceName"
      Type: String
  nextStep: getRootVolumeId
- name: getRootVolumeId
  action: aws:executeAwsApi
  maxAttempts: 3
  onFailure: Abort
  inputs:
    Service: ec2
    Api: DescribeVolumes
    Filters:
    -  Name: attachment.device
       Values: ["{{ getInstanceDetails.rootDeviceName }}"]
    -  Name: attachment.instance-id
       Values: ["{{ InstanceId }}"]
  outputs:
    - Name: rootVolumeId
      Selector: "$.Volumes[0].VolumeId"
      Type: String
  nextStep: getSnapshotsByStartTime
- name: getSnapshotsByStartTime
  action: aws:executeScript
  timeoutSeconds: 45
  onFailure: Abort
  inputs:
    Runtime: python3.8
    Handler: getSnapshotsByStartTime
    InputPayload:
      rootVolumeId : "{{ getRootVolumeId.rootVolumeId }}"
    Script: |-
      def getSnapshotsByStartTime(events,context):
        import boto3

        #Initialize client
        ec2 = boto3.client('ec2')
        rootVolumeId = events['rootVolumeId']
        snapshotsQuery = ec2.describe_snapshots(
          Filters=[
            {
              "Name": "volume-id",
              "Values": [rootVolumeId]
            }
          ]
        )
        if not snapshotsQuery['Snapshots']:
          noSnapshotFoundString = "NoSnapshotFound"
          return { 'noSnapshotFound' : noSnapshotFoundString }
        else:
          jsonSnapshots = snapshotsQuery['Snapshots']
          sortedSnapshots = sorted(jsonSnapshots, key=lambda k: k['StartTime'], reverse=True)
          latestSortedSnapshotId = sortedSnapshots[0]['SnapshotId']
          return { 'latestSnapshotId' : latestSortedSnapshotId }
  outputs:
  - Name: Payload
    Selector: $.Payload
    Type: StringMap
  - Name: latestSnapshotId
    Selector: $.Payload.latestSnapshotId
    Type: String
  - Name: noSnapshotFound
    Selector: $.Payload.noSnapshotFound
    Type: String 
  nextStep: branchFromResults
- name: branchFromResults
  action: aws:branch
  onFailure: Abort
  onCancel: step:startInstance
  inputs:
    Choices:
    - NextStep: createNewRootVolumeFromSnapshot
      Not:
        Variable: "{{ getSnapshotsByStartTime.noSnapshotFound }}"
        StringEquals: "NoSnapshotFound"
  isEnd: true
- name: createNewRootVolumeFromSnapshot
  action: aws:executeAwsApi
  onFailure: Abort
  inputs:
    Service: ec2
    Api: CreateVolume
    AvailabilityZone: "{{ getInstanceDetails.availabilityZone }}"
    SnapshotId: "{{ getSnapshotsByStartTime.latestSnapshotId }}"
  outputs:
    - Name: newRootVolumeId
      Selector: "$.VolumeId"
      Type: String
  nextStep: stopInstance
- name: stopInstance
  action: aws:executeAwsApi
  onFailure: Abort
  inputs:
    Service: ec2
    Api: StopInstances
    InstanceIds:
    - "{{ InstanceId }}"
  nextStep: verifyVolumeAvailability
- name: verifyVolumeAvailability
  action: aws:waitForAwsResourceProperty
  timeoutSeconds: 120
  inputs:
    Service: ec2
    Api: DescribeVolumes
    VolumeIds:
    - "{{ createNewRootVolumeFromSnapshot.newRootVolumeId }}"
    PropertySelector: "$.Volumes[0].State"
    DesiredValues:
    - "available"
  nextStep: verifyInstanceStopped
- name: verifyInstanceStopped
  action: aws:waitForAwsResourceProperty
  timeoutSeconds: 120
  inputs:
    Service: ec2
    Api: DescribeInstances
    InstanceIds:
    - "{{ InstanceId }}"
    PropertySelector: "$.Reservations[0].Instances[0].State.Name"
    DesiredValues:
    - "stopped"
  nextStep: detachRootVolume
- name: detachRootVolume
  action: aws:executeAwsApi
  onFailure: Abort
  isCritical: true
  inputs:
    Service: ec2
    Api: DetachVolume
    VolumeId: "{{ getRootVolumeId.rootVolumeId }}"
  nextStep: verifyRootVolumeDetached
- name: verifyRootVolumeDetached
  action: aws:waitForAwsResourceProperty
  timeoutSeconds: 30
  inputs:
    Service: ec2
    Api: DescribeVolumes
    VolumeIds:
    - "{{ getRootVolumeId.rootVolumeId }}"
    PropertySelector: "$.Volumes[0].State"
    DesiredValues:
    - "available"
  nextStep: attachNewRootVolume
- name: attachNewRootVolume
  action: aws:executeAwsApi
  onFailure: Abort
  inputs:
    Service: ec2
    Api: AttachVolume
    Device: "{{ getInstanceDetails.rootDeviceName }}"
    InstanceId: "{{ InstanceId }}"
    VolumeId: "{{ createNewRootVolumeFromSnapshot.newRootVolumeId }}"
  nextStep: verifyNewRootVolumeAttached
- name: verifyNewRootVolumeAttached
  action: aws:waitForAwsResourceProperty
  timeoutSeconds: 30
  inputs:
    Service: ec2
    Api: DescribeVolumes
    VolumeIds:
    - "{{ createNewRootVolumeFromSnapshot.newRootVolumeId }}"
    PropertySelector: "$.Volumes[0].Attachments[0].State"
    DesiredValues:
    - "attached"
  nextStep: startInstance
- name: startInstance
  action: aws:executeAwsApi
  onFailure: Abort
  inputs:
    Service: ec2
    Api: StartInstances
    InstanceIds:
    - "{{ InstanceId }}"
```

# `aws:approve` – 暫停自動化以進行手動核准
<a name="automation-action-approve"></a>

暫時暫停自動化，直到指定的委託人核准或拒絕動作。達到所需的核准數量後，自動化會繼續。您可以將核准步驟插入 Runbook `mainSteps` 章節的任何地方。

**注意**  
此動作不支援多帳戶和區域自動化。此動作的預設逾時時間為 7 天 (604800 秒)，最大值為 30 天 (2592000 秒)。您可以透過指定 `aws:approve` 步驟的 `timeoutSeconds` 參數來限制或延長逾時。

在以下範例中，`aws:approve` 動作暫時暫停了自動化，直到核准者接受或拒絕自動化為止。核准後，自動化會執行簡單的 PowerShell 命令。

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

```
---
description: RunInstancesDemo1
schemaVersion: '0.3'
assumeRole: "{{ assumeRole }}"
parameters:
  assumeRole:
    type: String
  message:
    type: String
mainSteps:
- name: approve
  action: aws:approve
  timeoutSeconds: 1000
  onFailure: Abort
  inputs:
    NotificationArn: arn:aws:sns:us-east-2:12345678901:AutomationApproval
    Message: "{{ message }}"
    MinRequiredApprovals: 1
    Approvers:
    - arn:aws:iam::12345678901:user/AWS-User-1
- name: run
  action: aws:runCommand
  inputs:
    InstanceIds:
    - i-1a2b3c4d5e6f7g
    DocumentName: AWS-RunPowerShellScript
    Parameters:
      commands:
      - date
```

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

```
{
   "description":"RunInstancesDemo1",
   "schemaVersion":"0.3",
   "assumeRole":"{{ assumeRole }}",
   "parameters":{
      "assumeRole":{
         "type":"String"
      },
      "message":{
         "type":"String"
      }
   },
   "mainSteps":[
      {
         "name":"approve",
         "action":"aws:approve",
         "timeoutSeconds":1000,
         "onFailure":"Abort",
         "inputs":{
            "NotificationArn":"arn:aws:sns:us-east-2:12345678901:AutomationApproval",
            "Message":"{{ message }}",
            "MinRequiredApprovals":1,
            "Approvers":[
               "arn:aws:iam::12345678901:user/AWS-User-1"
            ]
         }
      },
      {
         "name":"run",
         "action":"aws:runCommand",
         "inputs":{
            "InstanceIds":[
               "i-1a2b3c4d5e6f7g"
            ],
            "DocumentName":"AWS-RunPowerShellScript",
            "Parameters":{
               "commands":[
                  "date"
               ]
            }
         }
      }
   ]
}
```

------

您可以核准或拒絕在主控台等待核准的自動化。

**核准或拒絕等待自動化**

1. 在 https：//[https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/) 開啟 AWS Systems Manager 主控台。

1. 在導覽窗格中，選擇 **Automation** (自動化)。

1. 選擇狀態為 **Waiting (正在等待)** 自動化旁的選項。  
![\[存取核准/拒絕自動化頁面\]](http://docs.aws.amazon.com/zh_tw/systems-manager/latest/userguide/images/automation-approve-action-aws.png)

1. 選擇 **Approve/Deny (核准/拒絕)**。

1. 檢閱自動化的詳細資訊。

1. 選擇 **Approve (核准)** 或 **Deny (拒絕)**，輸入選擇性的註解，接著選擇 **Submit (提交)**。

**輸入範例**

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

```
NotificationArn: arn:aws:sns:us-west-1:12345678901:Automation-ApprovalRequest
Message: Please approve this step of the Automation.
MinRequiredApprovals: 3
Approvers:
- IamUser1
- IamUser2
- arn:aws:iam::12345678901:user/IamUser3
- arn:aws:iam::12345678901:role/IamRole
```

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

```
{
   "NotificationArn":"arn:aws:sns:us-west-1:12345678901:Automation-ApprovalRequest",
   "Message":"Please approve this step of the Automation.",
   "MinRequiredApprovals":3,
   "Approvers":[
      "IamUser1",
      "IamUser2",
      "arn:aws:iam::12345678901:user/IamUser3",
      "arn:aws:iam::12345678901:role/IamRole"
   ]
}
```

------

NotificationArn  
適用於 Automation 核准的 Amazon Simple Notification Service (Amazon SNS) 主題 Amazon Resource Name (ARN)。當您在 Runbook 中指定 `aws:approve` 步驟，自動化會傳送訊息至此主題，讓委託人知道必須核准或拒絕自動化步驟。Amazon SNS 主題的標題必須以「Automation」為字首。  
類型：字串  
必要：否

訊息  
您想要在核准請求傳送時包含於 Amazon SNS 主題的資訊。訊息長度上限為 4096 個字元。  
類型：字串  
必要：否

MinRequiredApprovals  
繼續自動化所需的核准數量下限。如果您不指定值，系統會預設一個。此參數的值必須為正數。此參數的值不得超過由 `Approvers` 參數定義的核准者數量。  
類型：整數  
必要：否

Approvers  
能夠核准或拒絕動作的已 AWS 驗證主體清單。核准者的數量上限為 10。您可以使用以下任一格式指定委託人：  
+ 使用者名稱
+ 使用者 ARN
+ IAM 角色 ARN
+ IAM 擔任角色 ARN
類型：StringList  
必要：是

EnhancedApprovals  
此輸入僅用於 Change Manager 範本。能夠核准或拒絕動作、IAM 主體類型以及核准者人數下限的已驗證 AWS 主體清單。以下是範例：  

```
schemaVersion: "0.3"
emergencyChange: false
autoApprovable: false
mainSteps:
    - name: ApproveAction1
    action: aws:approve
    timeoutSeconds: 604800
    inputs:
        Message: Please approve this change request
        MinRequiredApprovals: 3
        EnhancedApprovals:
        Approvers:
            - approver: John Stiles
            type: IamUser
            minRequiredApprovals: 0
            - approver: Ana Carolina Silva
            type: IamUser
            minRequiredApprovals: 0
            - approver: GroupOfThree
            type: IamGroup
            minRequiredApprovals: 0
            - approver: RoleOfTen
            type: IamRole
            minRequiredApprovals: 0
```
類型：StringList  
必要：是

**輸出**

ApprovalStatus  
步驟的核准狀態。狀態可以是以下其中一項：Approved (核准)、Rejected (拒絕) 或 Waiting (等待)。等待表示自動化要等待核准者輸入。  
類型：字串

ApproverDecisions  
一種 JSON 對應，包括每個核准者的核准決定。  
類型：MapList

# `aws:assertAwsResourceProperty` – 宣告 AWS 資源狀態或事件狀態
<a name="automation-action-assertAwsResourceProperty"></a>

`aws:assertAwsResourceProperty` 動作可讓您針對特定自動化步驟宣告特定的資源狀態或事件狀態。

**注意**  
`aws:assertAwsResourceProperty` 動作支援自動限流重試。如需詳細資訊，請參閱[設定限流操作的自動重試](automation-throttling-retry.md)。

如需有關如何使用此動作的更多範例，請參閱 [其他執行手冊範例](automation-document-examples.md)。

**Input**  
輸入是由您選擇的 API 操作定義。

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

```
action: aws:assertAwsResourceProperty
inputs:
  Service: The official namespace of the service
  Api: The API operation or method name
  API operation inputs or parameters: A value
  PropertySelector: Response object
  DesiredValues:
  - Desired property values
```

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

```
{
  "action": "aws:assertAwsResourceProperty",
  "inputs": {
    "Service":"The official namespace of the service",
    "Api":"The API operation or method name",
    "API operation inputs or parameters":"A value",
    "PropertySelector": "Response object",
    "DesiredValues": [
      "Desired property values"
    ]
  }
}
```

------

服務  
包含您要執行之 API 操作的 AWS 服務 命名空間。例如，Systems Manager 的命名空間為 `ssm`。Amazon EC2 的命名空間為 `ec2`。您可以檢視*AWS CLI 命令參考*[可用服務](https://docs.aws.amazon.com/cli/latest/reference/#available-services)章節中的受支援 AWS 服務 命名空間。  
類型：字串  
必要：是

Api  
您想要執行的 API 操作之名稱。您可以檢視 API 操作 (也稱為方法)，方式是在以下[服務參考](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html)頁面的左側導覽中選擇一項服務。在您想要呼叫之服務的 **Client (用戶端)** 部分選擇一個方法。例如，Amazon Relational Database Service (Amazon RDS) 的所有 API 操作 (方法) 均列於以下頁面：[Amazon RDS 方法](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html)。  
類型：字串  
必要：是

API 操作輸入  
一個或多個 API 操作輸入。您可以檢視可用的輸入 (也稱為參數)，方式是在以下[服務參考](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html)頁面的左側導覽中選擇一項服務。在您想要呼叫之服務的 **Client (用戶端)** 部分選擇一個方法。例如，Amazon RDS 的所有方法均列於以下頁面：[Amazon RDS 方法](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html)。選擇 [describe\$1db\$1instances](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html#RDS.Client.describe_db_instances) 方法並向下捲動以查看可用的參數，例如 **DBInstanceIdentifier**、**Name**、**Values**。使用以下格式指定一個以上的輸入。  

```
inputs:
  Service: The official namespace of the service
  Api: The API operation name
  API input 1: A value
  API Input 2: A value
  API Input 3: A value
```

```
"inputs":{
      "Service":"The official namespace of the service",
      "Api":"The API operation name",
      "API input 1":"A value",
      "API Input 2":"A value",
      "API Input 3":"A value"
}
```
類型：由所選的 API 操作決定  
必要：是

PropertySelector  
回應物件中特定屬性的 JSONPath。您可以檢視回應物件，方式是在以下[服務參考](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html)頁面的左側導覽中選擇一項服務。在您想要呼叫之服務的 **Client (用戶端)** 部分選擇一個方法。例如，Amazon RDS 的所有方法均列於以下頁面：[Amazon RDS 方法](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html)。選擇 [describe\$1db\$1instances](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html#RDS.Client.describe_db_instances) 方法並向下捲動至 **Response Structure (回應結構)** 區段。**DBInstances** 列為回應物件。  
類型：字串  
必要：是

DesiredValues  
讓自動化繼續的預期狀態。如果指定布林值，您必須使用大寫字母，例如 True 或 False。  
類型：StringList  
必要：是

# `aws:branch` – 執行條件式自動化步驟
<a name="automation-action-branch"></a>

`aws:branch` 動作可讓您建立動態自動化，以評估單一步驟中的不同選擇，接著根據該評估的結果跳至 Runbook 中的不同步驟。

指定步驟的 `aws:branch` 動作時，您要指定自動化必須評估的 `Choices`。`Choices` 可根據您在 Runbook 之 `Parameters` 區段所指定的值，或是產生做為先前步驟之輸出的動態值。自動化會使用布林值表達式評估每個選擇。如果第一個選擇為 true，則自動化會跳至針對該選擇指定的步驟。如果第一個選擇為 false，則自動化會評估下一個選擇。自動化會繼續評估每個選擇，直到處理的選擇是 true 為止。接著自動化會跳至選擇為 true 的指定步驟。

如果選擇均不為 true，則自動化會檢查步驟是否包含 `default` 值。如果沒有選擇為 true，則預設值會定義自動化應跳至的步驟。如果未針對步驟指定 `default` 值，則自動化會處理 Runbook 中的下一個步驟。

`aws:branch` 動作可結合使用 `And`、`Not`、`Or` 運算子來支援複雜的選擇評估。如需使用 `aws:branch` 的詳細資訊，包括使用不同運算子的範例 Runbook 和範例，請參閱 [在執行手冊中使用條件陳述式](automation-branch-condition.md)。

**Input**  
在步驟中指定一個或多個 `Choices`。`Choices` 可根據您在 Runbook 之 `Parameters` 區段所指定的值，或是產生做為先前步驟之輸出的動態值。以下為可評估參數的 YAML 範例。

```
mainSteps:
- name: chooseOS
  action: aws:branch
  inputs:
    Choices:
    - NextStep: runWindowsCommand
      Variable: "{{Name of a parameter defined in the Parameters section. For example: OS_name}}"
      StringEquals: windows
    - NextStep: runLinuxCommand
      Variable: "{{Name of a parameter defined in the Parameters section. For example: OS_name}}"
      StringEquals: linux
    Default:
      sleep3
```

以下為可評估先前步驟之輸出的 YAML 範例。

```
mainSteps:
- name: chooseOS
  action: aws:branch
  inputs:
    Choices:
    - NextStep: runPowerShellCommand
      Variable: "{{Name of a response object. For example: GetInstance.platform}}"
      StringEquals: Windows
    - NextStep: runShellCommand
      Variable: "{{Name of a response object. For example: GetInstance.platform}}"
      StringEquals: Linux
    Default:
      sleep3
```

選擇  
在決定要處理的下一個步驟時，自動化應評估的一個或多個運算式。選擇是使用布林值運算式評估。每個選擇都必須定義以下選項：  
+ **NextStep**：如果指定選擇為 true，在 Runbook 中要處理的下一個步驟。
+ **Variable** (變數)：指定 Runbook 之 `Parameters` 區段中定義的參數名稱。或指定 Runbook 中先前步驟的輸出物件。如需為 `aws:branch` 建立變數的詳細資訊，請參閱 [關於建立輸出變數](automation-branch-condition.md#branch-action-output)。
+ **Operation (運算)**：用於評估選擇的條件。`aws:branch` 動作支援以下運算：

**字串運算**
  + StringEquals
  + EqualsIgnoreCase
  + StartsWith
  + EndsWith
  + Contains

**數值運算**
  + NumericEquals
  + NumericGreater
  + NumericLesser
  + NumericGreaterOrEquals
  + NumericLesser
  + NumericLesserOrEquals

**布林運算**
  + BooleanEquals
**重要**  
當您建立 Runbook 時，系統會驗證 Runbook 中的每個操作。如果不支援操作，系統會在您嘗試建立 Runbook 時傳回錯誤。

預設  
自動化在 `Choices` 均不為 true 時應跳至某步驟的名稱。  
類型：字串  
必要：否

**注意**  
`aws:branch` 動作支援 `And`、`Or`、`Not` 運算子。如需使用運算子的 `aws:branch` 範例，請參閱 [在執行手冊中使用條件陳述式](automation-branch-condition.md)。

# `aws:changeInstanceState` – 變更或宣告執行個體狀態
<a name="automation-action-changestate"></a>

變更或宣告執行個體的狀態。

此動作可用於宣告模式 (不執行 API 以變更狀態，但會驗證執行個體處於所需的狀態)。若要使用宣告模式，請將 `CheckStateOnly` 參數設定為 true。此模式可用於在 Windows Server 上執行 Sysprep 命令，這是一種非同步命令，可在背景長時間執行。您可以確保執行個體在您建立 Amazon Machine Image (AMI) 之前停止。

**注意**  
此動作的預設逾時值為 3600 秒 (1 小時)。您可以透過指定 `aws:changeInstanceState` 步驟的 `timeoutSeconds` 參數來限制或延長逾時。

**注意**  
`aws:changeInstanceState` 動作支援自動限流重試。如需詳細資訊，請參閱[設定限流操作的自動重試](automation-throttling-retry.md)。

**輸入**

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

```
name: stopMyInstance
action: aws:changeInstanceState
maxAttempts: 3
timeoutSeconds: 3600
onFailure: Abort
inputs:
  InstanceIds:
  - i-1234567890abcdef0
  CheckStateOnly: true
  DesiredState: stopped
```

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

```
{
    "name":"stopMyInstance",
    "action": "aws:changeInstanceState",
    "maxAttempts": 3,
    "timeoutSeconds": 3600,
    "onFailure": "Abort",
    "inputs": {
        "InstanceIds": ["i-1234567890abcdef0"],
        "CheckStateOnly": true,
        "DesiredState": "stopped"
    }
}
```

------

InstanceIds  
執行個體的 ID。  
類型：StringList  
必要：是

CheckStateOnly  
如果為 false，則會將執行個體狀態設為所需的狀態。如果為 true，則會使用輪詢宣告所需的狀態。  
預設：`false`  
類型：布林值  
必要：否

DesiredState  
所需的狀態。設為 `running` 時，則在完成之前，此動作會等待 Amazon EC2 狀態成為 `Running`，執行個體狀態成為 `OK`，系統狀態成為 `OK`。  
類型：字串  
有效值：`running` \$1 `stopped` \$1 `terminated`  
必要：是

Force  
如果設定，則會強制執行個體停止。執行個體沒有機會排清檔案系統快取或檔案系統中繼資料。如果使用此選項，您必須執行檔案系統檢查及修復程序。此選項不建議用於 Windows Server 的 EC2 執行個體。  
類型：布林值  
必要：否

AdditionalInfo  
預訂.  
類型：字串  
必要：否

**Output**  
無

# `aws:copyImage` – 複製或加密 Amazon Machine Image
<a name="automation-action-copyimage"></a>

將 Amazon Machine Image(AMI) 從任何 複製到 AWS 區域 目前的 區域。此動作也可以加密新的 AMI。

**注意**  
`aws:copyImage` 動作支援自動限流重試。如需詳細資訊，請參閱[設定限流操作的自動重試](automation-throttling-retry.md)。

**Input**  
此動作支援大部分的 `CopyImage` 參數。如需詳細資訊，請參閱 [CopyImage](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CopyImage.html)。

以下範例是在首爾區域建立 AMI 的複本 (`SourceImageID`: ami-0fe10819. `SourceRegion`: ap-northeast-2)。新 AMI 已複製到您啟動自動化動作的區域。由於選用的 `Encrypted` 旗標設為 `true`，因此複製的 AMI 都會加密。

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

```
name: createEncryptedCopy
action: aws:copyImage
maxAttempts: 3
onFailure: Abort
inputs:
  SourceImageId: ami-0fe10819
  SourceRegion: ap-northeast-2
  ImageName: Encrypted Copy of LAMP base AMI in ap-northeast-2
  Encrypted: true
```

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

```
{   
    "name": "createEncryptedCopy",
    "action": "aws:copyImage",
    "maxAttempts": 3,
    "onFailure": "Abort",
    "inputs": {
        "SourceImageId": "ami-0fe10819",
        "SourceRegion": "ap-northeast-2",
        "ImageName": "Encrypted Copy of LAMP base AMI in ap-northeast-2",
        "Encrypted": true
    }   
}
```

------

SourceRegion  
來源 AMI 存在的區域。  
類型：字串  
必要：是

SourceImageId  
要從來源區域複製的 AMI ID。  
類型：字串  
必要：是

ImageName  
新映像的名稱。  
類型：字串  
必要：是

ImageDescription  
目標映像的描述。  
類型：字串  
必要：否

加密  
加密目標 AMI。  
類型：布林值  
必要：否

KmsKeyId  
在複製操作期間加密映像快照時， AWS KMS key 要使用的完整 Amazon Resource Name (ARN)。如需詳細資訊，請參閱 [CopyImage](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/api_copyimage.html)。  
類型：字串  
必要：否

ClientToken  
唯一且區分大小寫的識別符，由您提供以確保請求的冪等。如需詳細資訊，請參閱 [CopyImage](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/api_copyimage.html)。  
類型：字串  
必要：否Output

ImageId  
所複製映像的 ID。

ImageState  
所複製映像的狀態。  
有效值：`available` \$1 `pending` \$1 `failed`

# `aws:createImage` – 建立 Amazon Machine Image
<a name="automation-action-create"></a>

從正在執行、正在停止或已停止以及 `ImageState` 輪詢狀態為 `available` 的執行個體建立 Amazon Machine Image (AMI)。

**注意**  
`aws:createImage` 動作支援自動限流重試。如需詳細資訊，請參閱[設定限流操作的自動重試](automation-throttling-retry.md)。

**Input**  
此動作支援下列 `CreateImage` 參數。如需詳細資訊，請參閱 [CreateImage](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateImage.html)。

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

```
name: createMyImage
action: aws:createImage
maxAttempts: 3
onFailure: Abort
inputs:
  InstanceId: i-1234567890abcdef0
  ImageName: AMI Created on{{global:DATE_TIME}}
  NoReboot: true
  ImageDescription: My newly created AMI
```

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

```
{
    "name": "createMyImage",
    "action": "aws:createImage",
    "maxAttempts": 3,
    "onFailure": "Abort",
    "inputs": {
        "InstanceId": "i-1234567890abcdef0",
        "ImageName": "AMI Created on{{global:DATE_TIME}}",
        "NoReboot": true,
        "ImageDescription": "My newly created AMI"
    }
}
```

------

InstanceId  
執行個體的 ID。  
類型：字串  
必要：是

ImageName  
映像的名稱。  
類型：字串  
必要：是

ImageDescription  
映像的描述。  
類型：字串  
必要：否

NoReboot  
布林值常值。  
根據預設，Amazon Elastic Compute Cloud (Amazon EC2) 會在建立映像之前嘗試關閉並重新開機執行個體。若 **No Reboot (不重新啟動)** 選項設為 `true`，則 Amazon EC2 在建立映像之前不會關閉執行個體。使用此選項時，無法保證所建立映像的檔案系統完整性。  
如果您不希望執行個體在您從其建立 AMI 映像後執行，首先請使用 [`aws:changeInstanceState` – 變更或宣告執行個體狀態](automation-action-changestate.md) 動作停止執行個體，接著使用 `aws:createImage` 動作並將 **NoReboot** 選項設為 `true`。  
類型：布林值  
必要：否

BlockDeviceMappings  
執行個體的區塊型儲存設備。  
類型：映射  
必要：否Output

ImageId  
新建立映像的 ID。  
類型：字串

ImageState  
映像目前的狀態。如果狀態可用，則表示已成功註冊映像，且該映像可以用來啟動執行個體。  
類型：字串

# `aws:createStack` – 建立 CloudFormation 堆疊
<a name="automation-action-createstack"></a>

從範本建立 AWS CloudFormation 堆疊。

**注意**  
`aws:createStack` 動作支援自動限流重試。如需詳細資訊，請參閱[設定限流操作的自動重試](automation-throttling-retry.md)。

如需建立 CloudFormation 堆疊的補充資訊，請參閱《*AWS CloudFormation API 參考*》中的 [CreateStack](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_CreateStack.html)。

**輸入**

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

```
name: makeStack
action: aws:createStack
maxAttempts: 1
onFailure: Abort
inputs:
  Capabilities:
  - CAPABILITY_IAM
  StackName: myStack
  TemplateURL: http://s3.amazonaws.com/amzn-s3-demo-bucket/myStackTemplate
  TimeoutInMinutes: 5
  Parameters:
    - ParameterKey: LambdaRoleArn
      ParameterValue: "{{LambdaAssumeRole}}"
    - ParameterKey: createdResource
      ParameterValue: createdResource-{{automation:EXECUTION_ID}}
```

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

```
{
    "name": "makeStack",
    "action": "aws:createStack",
    "maxAttempts": 1,
    "onFailure": "Abort",
    "inputs": {
        "Capabilities": [
            "CAPABILITY_IAM"
        ],
        "StackName": "myStack",
        "TemplateURL": "http://s3.amazonaws.com/amzn-s3-demo-bucket/myStackTemplate",
        "TimeoutInMinutes": 5,
        "Parameters": [
          {
            "ParameterKey": "LambdaRoleArn",
            "ParameterValue": "{{LambdaAssumeRole}}"
          },
          {
            "ParameterKey": "createdResource",
            "ParameterValue": "createdResource-{{automation:EXECUTION_ID}}"
          }
    }
}
```

------

功能  
在 CloudFormation 可以建立特定堆疊之前，您所指定之值的清單。有些堆疊範本包含的資源可能會影響 中的許可 AWS 帳戶。對於這些堆疊，您必須藉由指定此參數明確地確認其功能。  
有效值包括 `CAPABILITY_IAM`、`CAPABILITY_NAMED_IAM` 與 `CAPABILITY_AUTO_EXPAND`。  
**CAPABILITY\$1IAM 和 CAPABILITY\$1NAMED\$1IAM**  
如果您有 IAM 資源，您可以指定其中一個功能。如果您有自訂名稱的 IAM 資源，則您必須指定 `CAPABILITY_NAMED_IAM`。如果您不指定此參數，此動作會傳回 `InsufficientCapabilities` 錯誤。下列資源需要您指定 `CAPABILITY_IAM` 或 `CAPABILITY_NAMED_IAM`。
+ [https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-accesskey.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-accesskey.html)
+ [https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-group.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-group.html)
+ [https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-instanceprofile.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-instanceprofile.html)
+ [https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-policy.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-policy.html)
+ [https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html)
+ [https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-user.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-user.html)
+ [https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-addusertogroup.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-addusertogroup.html)
如果您的堆疊範本包含這些資源，建議您檢閱與其關聯的所有許可並視需要編輯其許可。  
如需詳細資訊，請參閱 [CloudFormation 範本中的確認 IAM 資源](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities)。  
**CAPABILITY\$1AUTO\$1EXPAND**  
某些範本包含巨集。巨集會在範本上執行自訂處理，範圍涵蓋尋找和取代操作這種簡單動作，乃至於全部範本的大規模轉換。因此，使用者通常會從已處理的範本建立變更集，以在實際建立堆疊前先檢閱巨集產生的變更。如果堆疊範本包含一或多個巨集，且您選擇直接從已處理的範本建立堆疊，而不先檢閱變更集中所產生的變更，則您必須認可此功能。
如需詳細資訊，請參閱*AWS CloudFormation 《 使用者指南*》中的[使用 AWS CloudFormation 巨集在範本上執行自訂處理](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-macros.html)。  
類型：字串的陣列  
有效值:`CAPABILITY_IAM | CAPABILITY_NAMED_IAM | CAPABILITY_AUTO_EXPAND`  
必要：否

ClientRequestToken  
此 CreateStack 請求的唯一識別符。如果您將此步驟中的 maxAttempts 設為大於 1 之值，請指定此字符。藉由指定此字符，CloudFormation 會知道您並非嘗試以相同名稱建立新的堆疊。  
類型：字串  
必要：否  
長度限制：長度下限為 1。長度上限為 128。  
模式：[a-zA-Z0-9][-a-zA-Z0-9]\$1

DisableRollback  
設為 `true` 以在堆疊建立失敗時關閉堆疊回復。  
條件：您可以指定 `DisableRollback` 參數或 `OnFailure` 參數，但不能同時指定兩者。  
預設：`false`  
類型：布林值  
必要：否

NotificationARNs  
用來發佈堆疊相關事件的 Amazon Simple Notification Service (Amazon SNS) 主題 ARN。您可以使用 Amazon SNS 主控台尋找 SNS 主題 ARN，[https://console.aws.amazon.com/sns/v3/home](https://console.aws.amazon.com/sns/v3/home)。  
類型：字串的陣列  
陣列成員：最多 5 個項目。  
必要：否

OnFailure  
決定堆疊建立失敗時要採取的動作。您必須指定 `DO_NOTHING`、`ROLLBACK` 或 `DELETE`。  
條件：您可以指定 `OnFailure` 參數或 `DisableRollback` 參數，但不能同時指定兩者。  
預設：`ROLLBACK`  
類型：字串  
有效值：` DO_NOTHING | ROLLBACK | DELETE`  
必要：否

Parameters  
針對堆疊指定輸入參數的 `Parameter` 結構清單。如需詳細資訊，請參閱 [Parameter (參數)](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_Parameter.html) 資料類型。  
類型：[Parameter (參數)](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_Parameter.html) 物件的陣列   
必要：否

ResourceTypes  
針對此建立堆疊的動作，您有許可使用的範本資源類型。例如，`AWS::EC2::Instance`、`AWS::EC2::*` 或 `Custom::MyCustomInstance`。使用以下語法來描述範本資源類型。  
+ 對於所有 AWS 資源：

  ```
  AWS::*
  ```
+ 用於所有自訂資源：

  ```
  Custom::*
  ```
+ 用於特定自訂資源：

  ```
  Custom::logical_ID
  ```
+ 用於特定 AWS 服務的所有資源︰

  ```
  AWS::service_name::*
  ```
+ 對於特定 AWS 資源：

  ```
  AWS::service_name::resource_logical_ID
  ```
如果資源類型的清單不包括您正在建立的資源，則堆疊建立會失敗。根據預設，CloudFormation 會授予所有資源類型的許可。IAM 針對 IAM 政策中的 CloudFormation 特定條件索引鍵使用此參數。如需詳細資訊，請參閱[使用 控制存取 AWS Identity and Access Management](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html)。  
類型：字串的陣列  
長度限制：長度下限為 1。長度上限為 256。  
必要：否

RoleARN  
CloudFormation 假設建立堆疊之 IAM 角色的 Amazon Resource Name (ARN)。CloudFormation 會使用該角色的憑證代表您進行呼叫。CloudFormation 一律會將此角色用於堆疊上的所有未來操作。只要使用者擁有在堆疊上操作的許可，即使使用者沒有傳遞此角色的許可，CloudFormation 也會使用此角色。確保角色授予最少量的權限。  
如果您不指定值，CloudFormation 會使用先前與堆疊關聯的角色。如果沒有可用的角色，CloudFormation 會使用從您的使用者登入資料產生的暫時工作階段。  
類型：字串  
長度限制︰長度下限為 20。長度上限為 2048。  
必要：否

StackName  
與堆疊關聯的名稱。在您建立堆疊的區域中，名稱必須是唯一的。  
堆疊名稱僅能使用英數字元 (區分大小寫) 和連字號。必須以字母字元開頭，且長度不可超過 128 個字元。
類型：字串  
必要：是

StackPolicyBody  
包含堆疊政策內文的結構。如需詳細資訊，請參閱[避免更新堆疊資源](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/protect-stack-resources.html)。  
條件：您可以指定 `StackPolicyBody` 參數或 `StackPolicyURL` 參數，但不能同時指定兩者。  
類型：字串  
長度限制：長度下限為 1。長度上限為 16384。  
必要：否

StackPolicyURL  
包含堆疊政策之檔案的位置。URL 指向的政策必須位於與堆疊在相同區域中的 S3 儲存貯體。堆疊政策允許的檔案大小上限為 16 KB。  
條件：您可以指定 `StackPolicyBody` 參數或 `StackPolicyURL` 參數，但不能同時指定兩者。  
類型：字串  
長度限制：長度下限為 1。長度上限為 1350。  
必要：否

Tags (標籤)  
要與此堆疊相關聯的索引鍵/值組。CloudFormation 也會將這些標籤散佈到堆疊中建立的資源。您最多可指定 10 個標籤。  
類型：[Tag (標籤)](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_Tag.html) 物件的陣列   
必要：否

TemplateBody  
包含範本內文的結構，長度下限為 1 位元組，上限為 51,200 位元組。如需詳細資訊，請參閱[範本剖析](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-anatomy.html)。  
條件：您可以指定 `TemplateBody` 參數或 `TemplateURL` 參數，但不能同時指定兩者。  
類型：字串  
長度限制：長度下限為 1。  
必要：否

TemplateURL  
包含範本內文之檔案的位置。URL 必須指向位於 S3 儲存貯體的範本。範本允許的大小上限為 460,800 位元組。如需詳細資訊，請參閱[範本剖析](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-anatomy.html)。  
條件：您可以指定 `TemplateBody` 參數或 `TemplateURL` 參數，但不能同時指定兩者。  
類型：字串  
長度限制：長度下限為 1。長度上限為 1024。  
必要：否

TimeoutInMinutes  
在堆疊狀態成為 `CREATE_FAILED` 之前可經過的時間。如果 `DisableRollback` 未設定或設為 `false`，堆疊將會轉返。  
類型：整數  
有效範圍：最小值為 1。  
必要：否

## 輸出
<a name="automation-action-createstack-output"></a>

StackId  
堆疊的唯一識別符。  
類型：字串

StackStatus  
堆疊的目前狀態。  
類型：字串  
有效值:`CREATE_IN_PROGRESS | CREATE_FAILED | CREATE_COMPLETE | ROLLBACK_IN_PROGRESS | ROLLBACK_FAILED | ROLLBACK_COMPLETE | DELETE_IN_PROGRESS | DELETE_FAILED | DELETE_COMPLETE | UPDATE_IN_PROGRESS | UPDATE_COMPLETE_CLEANUP_IN_PROGRESS | UPDATE_COMPLETE | UPDATE_ROLLBACK_IN_PROGRESS | UPDATE_ROLLBACK_FAILED | UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS | UPDATE_ROLLBACK_COMPLETE | REVIEW_IN_PROGRESS`  
必要：是

StackStatusReason  
與堆疊狀態關聯的成功或失敗訊息。  
類型：字串  
必要：否  
如需詳細資訊，請參閱 [CreateStack](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_CreateStack.html)。

## 安全考量
<a name="automation-action-createstack-security"></a>

在您可以使用 `aws:createStack` 動作之前，您必須將以下政策指派至 IAM 自動化擔任角色。如需擔任角色的詳細資訊，請參閱 [任務 1：建立自動化的服務角色](automation-setup-iam.md#create-service-role)。

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

****  

```
{
   "Version":"2012-10-17",		 	 	 
   "Statement":[
      {
         "Effect":"Allow",
         "Action":[
            "sqs:*",
            "cloudformation:CreateStack",
            "cloudformation:DescribeStacks"
         ],
         "Resource":"*"
      }
   ]
}
```

------

# `aws:createTags` – 建立 AWS 資源的標籤
<a name="automation-action-createtag"></a>

為 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體或 AWS Systems Manager 受管執行個體建立新的標籤。

**注意**  
`aws:createTags` 動作支援自動限流重試。如需詳細資訊，請參閱[設定限流操作的自動重試](automation-throttling-retry.md)。

**Input**  
此動作支援大部分 Amazon EC2 `CreateTags` 和 Systems Manager `AddTagsToResource` 參數。如需詳細資訊，請參閱 [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/api_createtags.html) 和 [AddTagsToResource](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/api_addtagstoresource.html)。

以下範例示範如何將 Amazon Machine Image (AMI) 和執行個體標記為特定部門的生產資源。

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

```
name: createTags
action: aws:createTags
maxAttempts: 3
onFailure: Abort
inputs:
  ResourceType: EC2
  ResourceIds:
  - ami-9a3768fa
  - i-02951acd5111a8169
  Tags:
  - Key: production
    Value: ''
  - Key: department
    Value: devops
```

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

```
{
    "name": "createTags",
    "action": "aws:createTags",
    "maxAttempts": 3,
    "onFailure": "Abort",
    "inputs": {
        "ResourceType": "EC2",
        "ResourceIds": [
            "ami-9a3768fa",
            "i-02951acd5111a8169"
        ],
        "Tags": [
            {
                "Key": "production",
                "Value": ""
            },
            {
                "Key": "department",
                "Value": "devops"
            }
        ]
    }
}
```

------

ResourceIds  
要標籤的資源之 ID。如果資源類型不是「EC2」，則此欄位只能包含單一項目。  
類型：字串清單  
必要：是

Tags (標籤)  
要與資源建立關聯的標籤。  
類型：對應清單  
必要：是

ResourceType  
要標籤的資源之類型。如果未提供，會使用「EC2」為預設值。  
類型：字串  
必要：否  
有效值：`EC2` \$1 `ManagedInstance` \$1 `MaintenanceWindow` \$1 `Parameter`

**Output**  
無

# `aws:deleteImage` – 刪除 Amazon Machine Image
<a name="automation-action-delete"></a>

刪除指定 Amazon Machine Image (AMI) 和所有相關的快照。

**注意**  
`aws:deleteImage` 動作支援自動限流重試。如需詳細資訊，請參閱[設定限流操作的自動重試](automation-throttling-retry.md)。

**Input**  
此動作僅支援一個參數。如需更多資訊，請參閱 [DeregisterImage](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DeregisterImage.html) 和 [DeleteSnapshot](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DeleteSnapshot.html) 文件。

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

```
name: deleteMyImage
action: aws:deleteImage
maxAttempts: 3
timeoutSeconds: 180
onFailure: Abort
inputs:
  ImageId: ami-12345678
```

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

```
{
    "name": "deleteMyImage",
    "action": "aws:deleteImage",
    "maxAttempts": 3,
    "timeoutSeconds": 180,
    "onFailure": "Abort",
    "inputs": {
        "ImageId": "ami-12345678"
    }
}
```

------

ImageId  
欲刪除的映像之 ID。  
類型：字串  
必要：是

**Output**  
無

# `aws:deleteStack` – 刪除 CloudFormation 堆疊
<a name="automation-action-deletestack"></a>

刪除 AWS CloudFormation 堆疊。

**注意**  
`aws:deleteStack` 動作支援自動限流重試。如需詳細資訊，請參閱[設定限流操作的自動重試](automation-throttling-retry.md)。

**輸入**

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

```
name: deleteStack
action: aws:deleteStack
maxAttempts: 1
onFailure: Abort
inputs:
  StackName: "{{stackName}}"
```

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

```
{
   "name":"deleteStack",
   "action":"aws:deleteStack",
   "maxAttempts":1,
   "onFailure":"Abort",
   "inputs":{
      "StackName":"{{stackName}}"
   }
}
```

------

ClientRequestToken  
`DeleteStack` 請求的唯一識別符。如果您打算重試請求，請指定此字符，讓 CloudFormation 知道您並非嘗試刪除名稱相同的堆疊。您可以重試 `DeleteStack` 請求以確認 CloudFormation 收到。  
類型：字串  
長度限制：長度下限為 1。長度上限為 128。  
模式：[a-zA-Z][-a-zA-Z0-9]\$1  
必要：否

RetainResources.member.N  
此輸入僅適用處於 `DELETE_FAILED` 狀態的堆疊。您想要保留之資源的邏輯資源 ID 清單。在刪除期間，CloudFormation 會刪除堆疊，但不會刪除保留資源。  
當您無法刪除資源 (例如非空的 S3 儲存貯體)，但想要刪除堆疊，保留資源會很有幫助。  
類型：字串的陣列  
必要：否

RoleARN  
CloudFormation 用來建立堆疊之 AWS Identity and Access Management (IAM) 角色的 Amazon Resource Name (ARN)。CloudFormation 會使用該角色的憑證代表您進行呼叫。CloudFormation 一律會將此角色用於堆疊上的所有未來操作。只要使用者擁有在堆疊上操作的許可，即使使用者沒有傳遞此角色的許可，CloudFormation 也會使用此角色。確保角色授予最少量的權限。  
如果您不指定值，CloudFormation 會使用先前與堆疊關聯的角色。如果沒有可用的角色，CloudFormation 會使用從您的使用者登入資料產生的暫時工作階段。  
類型：字串  
長度限制︰長度下限為 20。長度上限為 2048。  
必要：否

StackName  
與堆疊關聯的名稱或唯一的堆疊 ID。  
類型：字串  
必要：是

## 安全考量
<a name="automation-action-deletestack-security"></a>

在您可以使用 `aws:deleteStack` 動作之前，您必須將以下政策指派至 IAM 自動化擔任角色。如需擔任角色的詳細資訊，請參閱 [任務 1：建立自動化的服務角色](automation-setup-iam.md#create-service-role)。

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

****  

```
{
   "Version":"2012-10-17",		 	 	 
   "Statement":[
      {
         "Effect":"Allow",
         "Action":[
            "sqs:*",
            "cloudformation:DeleteStack",
            "cloudformation:DescribeStacks"
         ],
         "Resource":"*"
      }
   ]
}
```

------

# `aws:executeAutomation` – 執行另一項自動化
<a name="automation-action-executeAutomation"></a>

透過呼叫次要 Runbook 執行次要自動化。透過此動作，您可以為您最常用的操作建立 Runbook，並在自動化執行期間參考那些 Runbook。此動作可簡化您的 Runbook，讓您不需要在類似的 Runbook 之間重複步驟。

次要自動化會在啟動主要自動化的使用者之內容中執行。這表示次要自動化使用與啟動第一個自動化的使用者相同的 AWS Identity and Access Management (IAM) 角色或使用者。

**重要**  
如果由您指定參數的次要自動化使用擔任角色 (使用 iam:passRole 政策的角色)，則啟動主要自動化的使用者或角色必須擁有將擔任角色傳遞至次要自動化的許可。如需設定自動化之擔任角色的詳細資訊，請參閱 [使用主控台建立用於自動化的服務角色](automation-setup-iam.md)。

**輸入**

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

```
name: Secondary_Automation
action: aws:executeAutomation
maxAttempts: 3
timeoutSeconds: 3600
onFailure: Abort
inputs:
  DocumentName: secondaryAutomation
  RuntimeParameters:
    instanceIds:
    - i-1234567890abcdef0
```

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

```
{
   "name":"Secondary_Automation",
   "action":"aws:executeAutomation",
   "maxAttempts":3,
   "timeoutSeconds":3600,
   "onFailure":"Abort",
   "inputs":{
      "DocumentName":"secondaryAutomation",
      "RuntimeParameters":{
         "instanceIds":[
            "i-1234567890abcdef0"
         ]
      }
   }
}
```

------

DocumentName  
在步驟期間要執行的次要 Runbook 名稱。對於相同 中的 Runbook AWS 帳戶，指定 Runbook 名稱。對於從不同 共用的 Runbook AWS 帳戶，請指定 Runbook 的 Amazon Resource Name (ARN)。如需共用 Runbook 的詳細資訊，請參閱 [使用共用的 SSM 文件](documents-ssm-sharing.md#using-shared-documents)。  
類型：字串  
必要：是

DocumentVersion  
要執行的次要 Runbook 版本。如果未指定，自動化會執行預設 Runbook 版本。  
類型：字串  
必要：否

MaxConcurrency  
您可以平行執行此任務的目標數目上限。您可以指定數量如 10 或百分比如 10%。  
類型：字串  
必要：否

MaxErrors  
系統停止在其他目標上執行自動化前所允許的錯誤數量。您可以指定絕對數量的錯誤 (例如 10 個) 或目標集的百分比 (例如 10%)。例如，假設您指定 3，系統會在收到第四個錯誤時停止執行自動化。如果您指定 0，系統會在第一個錯誤結果傳回時停止其他目標上執行的自動化。如果您在 50 個資源上執行自動化，並將 `MaxErrors` 設為 10%，則系統會在收到第六個錯誤時停止對其他目標執行自動化。  
達到 `MaxErrors` 閾值時已經在執行的自動化允許完成，但其中某些自動化也可能會失敗。如果您需要確保不會有比指定 `MaxErrors` 多的失敗自動化操作，則將 `MaxConcurrency` 設定為 1，因此會一次進行一個自動化。  
類型：字串  
必要：否

RuntimeParameters  
次要 Runbook 的必要參數。映射使用以下格式：\$1"parameter1" : "value1", "parameter2" : "value2" \$1  
類型：映射  
必要：否

Tags (標籤)  
您指派給資源的選用中繼資料。您可以為自動化指定最多五個標籤。  
類型：MapList  
必要：否

TargetLocations  
位置是您想要執行自動化的 AWS 區域 和/或 AWS 帳戶 的組合。必須指定最少 1 個項目，且最多可指定 100 個項目。指定此參數的值時，輸出不會傳回至父系自動化。如有需要，您必須對 API 操作進行後續呼叫，才能從子系自動化擷取輸出。  
類型：MapList  
必要：否

TargetMaps  
文件參數到目標資源的鍵/值映射清單。不能同時指定 `Targets` 和 `TargetMaps`。  
類型：MapList  
必要：否

TargetParameterName  
作為速率控制自動化之目標資源使用的參數名稱。只在您指定 `Targets` 時需要  
類型：字串  
必要：否

目標  
至目標資源的鍵/值對映清單。只在您指定 `TargetParameterName` 時需要  
類型：MapList  
必要：否Output

Output  
由次要自動化產生的輸出。您可以使用以下格式參考輸出：*Secondary\$1Automation\$1Step\$1Name*.Output  
類型：StringList  
請見此處範例：  

```
- name: launchNewWindowsInstance
  action: 'aws:executeAutomation'
  onFailure: Abort
  inputs:
    DocumentName: launchWindowsInstance
  nextStep: getNewInstanceRootVolume
- name: getNewInstanceRootVolume
  action: 'aws:executeAwsApi'
  onFailure: Abort
  inputs:
    Service: ec2
    Api: DescribeVolumes
    Filters:
    - Name: attachment.device
      Values:
      - /dev/sda1
    - Name: attachment.instance-id
      Values:
      - '{{launchNewWindowsInstance.Output}}'
  outputs:
  - Name: rootVolumeId
    Selector: '$.Volumes[0].VolumeId'
    Type: String
  nextStep: snapshotRootVolume
- name: snapshotRootVolume
  action: 'aws:executeAutomation'
  onFailure: Abort
  inputs:
    DocumentName: AWS-CreateSnapshot
    RuntimeParameters:
    VolumeId:
    - '{{getNewInstanceRootVolume.rootVolumeId}}'
    Description:
    - 'Initial root snapshot for {{launchNewWindowsInstance.Output}}'
```

ExecutionId  
次要自動化的 ID。  
類型：字串

狀態  
次要自動化的 狀態。  
類型：字串

# `aws:executeAwsApi` – 呼叫並執行 AWS API 操作
<a name="automation-action-executeAwsApi"></a>

呼叫並執行 AWS API 操作。大部分 API 操作均有支援，但並非所有 API 操作都經過測試。不支援串流 API 操作，例如 [GetObject](https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectGET.html) 操作。如果不確定想要使用的 API 操作是否為串流操作，請檢閱 [Boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html) 服務文件，以確定 API 是否需要串流輸入或輸出。我們會定期更新此動作所使用的 Boto3 版本。但在新的 Boto3 版本發布之後，可能需要長達幾週的時間才能在此動作中反映出相關更改。每個 `aws:executeAwsApi` 動作最多可執行 25 秒。如需有關如何使用此動作的更多範例，請參閱 [其他執行手冊範例](automation-document-examples.md)。

**注意**  
`aws:executeAwsApi` 動作支援自動限流重試。如需詳細資訊，請參閱[設定限流操作的自動重試](automation-throttling-retry.md)。

**輸入**  
輸入是由您選擇的 API 操作定義。

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

```
action: aws:executeAwsApi
inputs:
  Service: The official namespace of the service
  Api: The API operation or method name
  API operation inputs or parameters: A value
outputs: # These are user-specified outputs
- Name: The name for a user-specified output key
  Selector: A response object specified by using jsonpath format
  Type: The data type
```

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

```
{
   "action":"aws:executeAwsApi",
   "inputs":{
      "Service":"The official namespace of the service",
      "Api":"The API operation or method name",
      "API operation inputs or parameters":"A value"
   },
   "outputs":[ These are user-specified outputs
      {
         "Name":"The name for a user-specified output key",
         "Selector":"A response object specified by using JSONPath format",
         "Type":"The data type"
      }
   ]
}
```

------

服務  
包含您要執行之 API 操作的 AWS 服務 命名空間。您可以在 的[可用服務](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html)中檢視支援的 AWS 服務 命名空間清單 適用於 Python (Boto3) 的 AWS SDK。您可以在 **Client (用戶端)** 區段中找到此命名空間。例如，Systems Manager 的命名空間為 `ssm`。Amazon Elastic Compute Cloud (Amazon EC2) 的命名空間為 `ec2`。  
類型：字串  
必要：是

Api  
您想要執行的 API 操作之名稱。您可以檢視 API 操作 (也稱為方法)，方式是在以下[服務參考](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html)頁面的左側導覽中選擇一項服務。在您想要呼叫之服務的 **Client (用戶端)** 部分選擇一個方法。例如，Amazon Relational Database Service (Amazon RDS) 的所有 API 操作 (方法) 均列於以下頁面：[Amazon RDS 方法](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html)。  
類型：字串  
必要：是

API 操作輸入  
一個或多個 API 操作輸入。您可以檢視可用的輸入 (也稱為參數)，方式是在以下[服務參考](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html)頁面的左側導覽中選擇一項服務。在您想要呼叫之服務的 **Client (用戶端)** 部分選擇一個方法。例如，Amazon RDS 的所有方法均列於以下頁面：[Amazon RDS 方法](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html)。選擇 [describe\$1db\$1instances](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html#RDS.Client.describe_db_instances) 方法並向下捲動以查看可用的參數，例如 **DBInstanceIdentifier**、**Name**、**Values**。  

```
inputs:
  Service: The official namespace of the service
  Api: The API operation name
  API input 1: A value
  API Input 2: A value
  API Input 3: A value
```

```
"inputs":{
      "Service":"The official namespace of the service",
      "Api":"The API operation name",
      "API input 1":"A value",
      "API Input 2":"A value",
      "API Input 3":"A value"
}
```
類型：由所選的 API 操作決定  
必要：是

**輸出**  
輸出由使用者根據所選 API 操作的回應來指定。

名稱  
輸出的名稱。  
類型：字串  
必要：是

選擇器  
回應物件中特定屬性的 JSONPath。您可以檢視回應物件，方式是在以下[服務參考](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html)頁面的左側導覽中選擇一項服務。在您想要呼叫之服務的 **Client (用戶端)** 部分選擇一個方法。例如，Amazon RDS 的所有方法均列於以下頁面：[Amazon RDS 方法](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html)。選擇 [describe\$1db\$1instances](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html#RDS.Client.describe_db_instances) 方法並向下捲動至 **Response Structure (回應結構)** 區段。**DBInstances** 列為回應物件。  
類型：整數、布林值、字串、StringList、StringMap 或 MapList  
必要：是

Type  
回應元素的資料類型。  
類型：Varies  
必要：是

# `aws:executeScript` – 執行指令碼
<a name="automation-action-executeScript"></a>

執行使用指定的執行時間和處理程序提供的 Python 或 PowerShell 指令碼。每個 `aws:executeScript` 動作最久可執行 600 秒 (10 分鐘)。您可以透過指定 `aws:executeScript` 步驟的 `timeoutSeconds` 參數來限制逾時。

在函數中使用傳回陳述式將輸出加入輸出承載。有關 `aws:executeScript` 動作定義輸出的範例，請參閱 [範例 2：指令碼式 Runbook](automation-authoring-runbooks-scripted-example.md)。您也可以把 Runbook 的 `aws:executeScript` 動作輸出傳送到您指定的 Amazon CloudWatch Logs 日誌群組。如需詳細資訊，請參閱[使用 CloudWatch Logs 記錄自動化動作輸出](automation-action-logging.md)。

如果您想要將`aws:executeScript`動作的輸出傳送至 CloudWatch Logs，或者您為`aws:executeScript`動作指定的指令碼呼叫 AWS API 操作，則一律需要 AWS Identity and Access Management (IAM) 服務角色 （或擔任角色） 才能執行 Runbook。

**注意**  
`aws:executeScript` 動作不支援自動限流重試。如果您的指令碼發出可能會調節的 AWS API 呼叫，您必須在指令碼程式碼中實作自己的重試邏輯。

`aws:executeScript` 動作包含下列預先安裝的 PowerShell Core 模組。
+ Microsoft.PowerShell.Host
+ Microsoft.PowerShell.Management
+ Microsoft.PowerShell.Security
+ Microsoft.PowerShell.Utility
+ PackageManagement
+ PowerShellGet

若要使用未預先安裝的 PowerShell Core 模組，您的指令碼必須使用 `-Force` 旗標安裝模組，如下列命令所示。不支援 `AWSPowerShell.NetCore` 模組。把 *ModuleName* (模組名稱) 取代為您想要安裝的模組。

```
Install-Module ModuleName -Force
```

若要在指令碼中使用 PowerShell Core Cmdlet，建議您使用 `AWS.Tools` 模組，如下列命令所示。將每個*範例資源預留位置*取代為您自己的資訊。
+ Amazon Simple Storage Service (Amazon S3) cmdlet。

  ```
  Install-Module AWS.Tools.S3 -Force
  Get-S3Bucket -BucketName amzn-s3-demo-bucket
  ```
+ Amazon EC2 cmdlet。

  ```
  Install-Module AWS.Tools.EC2 -Force
  Get-EC2InstanceStatus -InstanceId instance-id
  ```
+ 常見 或服務獨立 AWS Tools for Windows PowerShell cmdlet。

  ```
  Install-Module AWS.Tools.Common -Force
  Get-AWSRegion
  ```

如果指令碼除了使用 PowerShell Core Cmdlet 之外，還會初始化新物件，您也必須匯入模組，如下列命令所示。

```
Install-Module AWS.Tools.EC2 -Force
Import-Module AWS.Tools.EC2

$tag = New-Object Amazon.EC2.Model.Tag
$tag.Key = "Tag"
$tag.Value = "TagValue"

New-EC2Tag -Resource i-02573cafcfEXAMPLE -Tag $tag
```

如需在 Runbook 內容中安裝和匯入 `AWS.Tools` 模組，以及使用 PowerShell Core Cmdlet 的範例，請參閱 [Automation 執行手冊的視覺化設計體驗](automation-visual-designer.md)。

**Input**  
提供執行指令碼所需訊息。將每個*範例資源預留位置*取代為您自己的資訊。

**注意**  
Python 指令碼的附件可以是包含指令碼的 .py 檔案或 .zip 檔案。PowerShell 指令碼必須儲存在 .zip 檔案中。

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

```
action: "aws:executeScript"
inputs: 
 Runtime: runtime
 Handler: "functionName"
 InputPayload: 
  scriptInput: '{{parameterValue}}'
 Script: |-
   def functionName(events, context):
   ...
 Attachment: "scriptAttachment.zip"
```

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

```
{
    "action": "aws:executeScript",
    "inputs": {
        "Runtime": "runtime",
        "Handler": "functionName",
        "InputPayload": {
            "scriptInput": "{{parameterValue}}"
        },
        "Attachment": "scriptAttachment.zip"
    }
}
```

------

執行時期  
用於執行所提供指令碼的執行時間語言。 `aws:executeScript`支援下表中的執行時間。      
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/systems-manager/latest/userguide/automation-action-executeScript.html)
類型：字串  
必要：是  
對於 python 執行時期，該環境提供 512 MB 的記憶體與 512 MB 的磁碟空間。對於 PowerShell 執行時期，該環境提供 1024 MB 的記憶體與 512 MB 的磁碟空間。

處理常式  
函數名稱。您必須確保處理常式中定義的函數有兩個參數，`events` 和 `context`。PowerShell 執行階段不支援此參數。  
類型：字串  
必要：是 (Python) \$1 不支援 (PowerShell)

InputPayload  
將傳遞給處理程序的第一個參數的 JSON 或 YAML 物件。這可以用來將輸入資料傳入至指令碼。  
類型：字串  
必要：否  

```
description: Tag an instance
schemaVersion: '0.3'
assumeRole: '{{AutomationAssumeRole}}'
parameters:
    AutomationAssumeRole:
        type: String
        description: '(Required) The Amazon Resource Name (ARN) of the IAM role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to operate this runbook.'
    InstanceId:
        type: String
        description: (Required) The ID of the EC2 instance you want to tag.
mainSteps:
  - name: tagInstance
    action: 'aws:executeScript'
    inputs:
        Runtime: "python3.11"
        Handler: tagInstance
        InputPayload:
            instanceId: '{{InstanceId}}'
        Script: |-
          def tagInstance(events,context):
            import boto3

            #Initialize client
            ec2 = boto3.client('ec2')
            instanceId = events['instanceId']
            tag = {
                "Key": "Env",
                "Value": "ExamplePython"
            }
            print(f"Adding tag {tag} to instance id {instanceId}")
            ec2.create_tags(
                Resources=[instanceId],
                Tags=[tag]
            )
            return tag
    outputs:
      - Type: String
        Name: TagKey
        Selector: $.Payload.Key
outputs:
  - tagInstance.TagKey
```

```
description: Tag an instance
schemaVersion: '0.3'
assumeRole: '{{AutomationAssumeRole}}'
parameters:
  AutomationAssumeRole:
    type: String
    description: (Required) The Amazon Resource Name (ARN) of the IAM role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to operate this runbook.
  InstanceId:
    type: String
    description: (Required) The ID of the EC2 instance you want to tag.
mainSteps:
  - name: tagInstance
    action: aws:executeScript
    isEnd: true
    inputs:
      Runtime: PowerShell 7.4
      InputPayload:
        instanceId: '{{InstanceId}}'
      Script: |-
        Install-Module AWS.Tools.EC2 -Force
        Import-Module AWS.Tools.EC2

        $input = $env:InputPayload | ConvertFrom-Json

        $tag = New-Object Amazon.EC2.Model.Tag
        $tag.Key = "Env"
        $tag.Value = "ExamplePowerShell"

        Write-Information "Adding tag key: $($tag.Key) and value: $($tag.Value) to instance id $($input.instanceId)"
        New-EC2Tag -Resource $input.instanceId -Tag $tag

        return $tag
    outputs:
      - Type: String
        Name: TagKey
        Selector: $.Payload.Key
outputs:
  - tagInstance.TagKey
```

指令碼  
您想要在自動化期間執行的內嵌指令碼。  
類型：字串  
必要：No (Python) \$1 Yes (PowerShell)

連接  
動作可呼叫的獨立指令碼檔案或 .zip 檔案的名稱。指定與您在 `Attachments` 請求參數中指定的文件附件檔案的 `Name` 相同的數值。如須詳細資訊，請參閱《*AWS Systems Manager API 參考*》的[附件](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_CreateDocument.html#systemsmanager-CreateDocument-request-Attachments)。如果您使用附件提供指令碼，還必須定義 Runbook 頂層元素的 `files` 區段。如需詳細資訊，請參閱[結構描述版本 0.3](documents-schemas-features.md#automation-doc-syntax-examples)。  
若要為 Python 呼叫檔案，請在 `Handler` 中使用 `filename.method_name` 格式。  
Python 指令碼的附件可以是包含指令碼的 .py 檔案或 .zip 檔案。PowerShell 指令碼必須儲存在 .zip 檔案中。
當在附件中包含 Python 庫時，建議在每個模組目錄中新增空的 `__init__.py` 檔案。這允許您從指令碼內容中的附件庫匯入模組。例如：`from library import module`  
類型：字串  
必要：否Output

酬載  
由函數傳回之物件的 JSON 表示法。最多會傳回 100 KB。如果輸出清單，則最多只能傳回 100 個項目。

## 搭配 aws:executeScript 使用附件
<a name="automation-action-executeScript-attachments"></a>

附件提供了一種強大的方法，可將複雜的指令碼、多個模組和外部相依性與您的 `aws:executeScript` 動作一起封裝並重複使用。當您需要進行下列操作時，請使用附件：
+ 將多個 Python 模組或 PowerShell 指令碼封裝在一起。
+ 在多個執行手冊中，重複使用相同的指令碼邏輯。
+ 在您的指令碼中包含外部程式庫或相依性。
+ 分隔複雜的指令碼邏輯，保持執行手冊定義明確清晰。
+ 在團隊或自動化工作流程中共用指令碼套件。

### 附件結構和封裝
<a name="automation-action-executeScript-attachment-structure"></a>

您可以連接單一檔案或是包含多個檔案的 zip 套件。結構取決於您的使用案例：

**單一檔案附件**  
對於簡單的指令碼，您可以連接單一 `.py` 檔案 (Python) 或包含單一 PowerShell 指令碼的 `.zip` 檔案。

**多模組套件**  
對於需要多個模組的複雜自動化，請以下列建議的結構建立 zip 套件：

```
my-automation-package.zip
├── main.py                    # Entry point script
├── utils/
│   ├── __init__.py           # Required for Python module imports
│   ├── helper_functions.py   # Utility functions
│   └── aws_operations.py     # AWS-specific operations
├── config/
│   ├── __init__.py
│   └── settings.py           # Configuration settings
└── requirements.txt          # Optional: document dependencies
```

**重要**  
對於 Python 套件，您必須在包含 Python 模組的每個目錄中包含空白的 `__init__.py` 檔案。這可讓您使用標準的 Python 匯入語法 (例如 `from utils import helper_functions`) 來匯入模組。

**PowerShell 套件結構**  
PowerShell 附件必須使用下列結構，封裝在 zip 檔案中：

```
my-powershell-package.zip
├── Main.ps1                  # Entry point script
├── Modules/
│   ├── HelperFunctions.ps1   # Utility functions
│   └── AWSOperations.ps1     # AWS-specific operations
└── Config/
    └── Settings.ps1          # Configuration settings
```

### 建立含有附件的執行手冊
<a name="automation-action-executeScript-attachment-workflow"></a>

請依照下列步驟建立使用附件的執行手冊：

1. **將您的附件上傳至 Amazon S3**

   將您的指令碼檔案或 zip 套件上傳至自動化角色可存取的 S3 儲存貯體。請記下 S3 URI，以便在下一個步驟中使用。

   ```
   aws s3 cp my-automation-package.zip s3://my-automation-bucket/scripts/
   ```

1. **計算附件檢查總和**

   計算附件檔案的 SHA-256 檢查總和，以進行安全性驗證：

   ```
   # Linux/macOS
   shasum -a 256 my-automation-package.zip
   
   # Windows PowerShell
   Get-FileHash -Algorithm SHA256 my-automation-package.zip
   ```

1. **定義執行手冊中的檔案區段**

   在執行手冊的頂層新增 `files` 區段，以參考您的附件：

   ```
   files:
     my-automation-package.zip:
       checksums:
         sha256: "your-calculated-checksum-here"
   ```

1. **參考 executeScript 步驟中的附件**

   使用 `Attachment` 參數來參考您已上傳的檔案：

   ```
   - name: runMyScript
     action: aws:executeScript
     inputs:
       Runtime: python3.11
       Handler: main.process_data
       Attachment: my-automation-package.zip
       InputPayload:
         inputData: "{{InputParameter}}"
   ```

## aws:executeScript 附件範例
<a name="automation-action-executeScript-examples"></a>

下列範例示範搭配 `aws:executeScript` 動作使用附件的不同方式。

### 範例 1：單一檔案附件
<a name="automation-action-executeScript-single-file-example"></a>

此範例說明如何使用單一 Python 檔案作為附件來處理 EC2 執行個體資料。

**附件檔案：process\$1instance.py**  
使用下列內容建立 Python 檔案：

```
import boto3
import json

def process_instance_data(events, context):
    """Process EC2 instance data and return formatted results."""
    try:
        instance_id = events.get('instanceId')
        if not instance_id:
            raise ValueError("instanceId is required")
        
        ec2 = boto3.client('ec2')
        
        # Get instance details
        response = ec2.describe_instances(InstanceIds=[instance_id])
        instance = response['Reservations'][0]['Instances'][0]
        
        # Format the response
        result = {
            'instanceId': instance_id,
            'instanceType': instance['InstanceType'],
            'state': instance['State']['Name'],
            'availabilityZone': instance['Placement']['AvailabilityZone'],
            'tags': {tag['Key']: tag['Value'] for tag in instance.get('Tags', [])}
        }
        
        print(f"Successfully processed instance {instance_id}")
        return result
        
    except Exception as e:
        print(f"Error processing instance: {str(e)}")
        raise
```

**完成執行手冊**  
下方是使用單一檔案附件的完整執行手冊：

```
description: Process EC2 instance data using single file attachment
schemaVersion: '0.3'
assumeRole: '{{AutomationAssumeRole}}'
parameters:
  AutomationAssumeRole:
    type: String
    description: (Required) IAM role for automation execution
  InstanceId:
    type: String
    description: (Required) EC2 instance ID to process

files:
  process_instance.py:
    checksums:
      sha256: "abc123def456..."

mainSteps:
  - name: processInstance
    action: aws:executeScript
    inputs:
      Runtime: python3.11
      Handler: process_instance.process_instance_data
      Attachment: process_instance.py
      InputPayload:
        instanceId: '{{InstanceId}}'
    outputs:
      - Type: StringMap
        Name: InstanceData
        Selector: $.Payload

outputs:
  - processInstance.InstanceData
```

### 範例 2：多模組套件
<a name="automation-action-executeScript-multi-module-example"></a>

此範例示範如何使用包含多個 Python 模組的 zip 套件進行複雜的 S3 儲存貯體操作。

**套件結構**  
使用下列結構建立 zip 套件：

```
s3-operations.zip
├── main.py
├── utils/
│   ├── __init__.py
│   ├── s3_helper.py
│   └── validation.py
└── config/
    ├── __init__.py
    └── settings.py
```

**main.py (進入點)**  
協調操作的主要指令碼：

```
from utils.s3_helper import S3Operations
from utils.validation import validate_bucket_name
from config.settings import get_default_settings

def cleanup_s3_bucket(events, context):
    """Clean up S3 bucket based on specified criteria."""
    try:
        bucket_name = events.get('bucketName')
        max_age_days = events.get('maxAgeDays', 30)
        
        # Validate inputs
        if not validate_bucket_name(bucket_name):
            raise ValueError(f"Invalid bucket name: {bucket_name}")
        
        # Initialize S3 operations
        s3_ops = S3Operations()
        settings = get_default_settings()
        
        # Perform cleanup
        deleted_objects = s3_ops.delete_old_objects(
            bucket_name, 
            max_age_days,
            settings['dry_run']
        )
        
        result = {
            'bucketName': bucket_name,
            'deletedCount': len(deleted_objects),
            'deletedObjects': deleted_objects[:10],  # Return first 10 for brevity
            'dryRun': settings['dry_run']
        }
        
        print(f"Cleanup completed for bucket {bucket_name}")
        return result
        
    except Exception as e:
        print(f"Error during S3 cleanup: {str(e)}")
        raise
```

## 對 aws:executeScript 附件進行疑難排解
<a name="automation-action-executeScript-troubleshooting"></a>

使用以下指引來解決 `aws:executeScript` 附件的常見問題：

**模組匯入錯誤**  
如果您在使用多模組套件時收到匯入錯誤：
+ 請確保您已在每個包含 Python 模組的目錄中包含空白 `__init__.py` 檔案。
+ 驗證您的匯入陳述式是否符合 zip 套件中的實際檔案與目錄結構。
+ 一致地使用相對匯入 (例如 `from .utils import helper`) 或絕對匯入 (例如 `from utils import helper`)。

**找不到附件錯誤**  
如果您的 Automation 無法找到附件：
+ 驗證 `Attachment` 參數值是否與 `files` 區段中的索引鍵完全相符。
+ 檢查 `files` 區段中的 S3 儲存貯體路徑與檔案名稱是否正確。
+ 確保您的自動化角色具有附件 S3 位置的 `s3:GetObject` 許可。
+ 驗證執行手冊中的檢查總和是否符合實際檔案檢查總和。

**處理常式函數錯誤**  
如果您收到與處理常式相關的錯誤：
+ 對於 Python：在 `Handler` 參數中使用 `filename.function_name` 格式 (例如 `main.process_data`)。
+ 確保您的處理常式函數只接受兩個參數：`events` 和 `context`。
+ 對於 PowerShell：請勿指定 `Handler` 參數；指令碼會直接執行。

**指令碼執行失敗**  
如果您的指令碼在執行期間失敗：
+ 檢查自動化執行歷史記錄，以取得詳細的錯誤訊息和堆疊追蹤。
+ 使用 `print()` 陳述式 (Python) 或 `Write-Information` (PowerShell) 新增偵錯輸出。
+ 確認所有必要的 AWS 許可都授予您的自動化角色。
+ 將指令碼邏輯封裝為附件之前，先在本機測試指令碼邏輯。

**結束程式碼和錯誤處理**  
若要正確處理錯誤並傳回結束程式碼：
+ 在 Python 中：使用 `raise Exception("error message")` 指出指令碼失敗。
+ 在 PowerShell 中：使用 `throw "error message"` 或 `Write-Error` 指出失敗。
+ 從函數傳回結構化資料，以提供詳細的成功/失敗資訊。
+ 使用 try-catch 區塊，以正常方式處理例外狀況，並提供有意義的錯誤訊息。

# `aws:executeStateMachine` – 執行 AWS Step Functions 狀態機器
<a name="automation-action-executeStateMachine"></a>

執行 AWS Step Functions 狀態機器。

**注意**  
`aws:executeStateMachine` 動作支援自動限流重試。如需詳細資訊，請參閱[設定限流操作的自動重試](automation-throttling-retry.md)。

**輸入**

此動作支援 Step Functions [StartExecution](https://docs.aws.amazon.com/step-functions/latest/apireference/API_StartExecution.html) API 操作的大部分參數。

**Required AWS Identity and Access Management (IAM) 許可**
+ `states:DescribeExecution`
+ `states:StartExecution`
+ `states:StopExecution`

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

```
name: executeTheStateMachine
action: aws:executeStateMachine
inputs:
  stateMachineArn: StateMachine_ARN
  input: '{"parameters":"values"}'
  name: name
```

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

```
{
    "name": "executeTheStateMachine",
    "action": "aws:executeStateMachine",
    "inputs": {
        "stateMachineArn": "StateMachine_ARN",
        "input": "{\"parameters\":\"values\"}",
        "name": "name"
    }
}
```

------

stateMachineArn  
Step Functions 狀態機的 Amazon Resource Name (ARN)。  
類型：字串  
必要：是

name  
執行的名稱。  
類型：字串  
必要：否

input  
包含執行之 JSON 輸入資料的字串。  
類型：字串  
必要：否

**輸出**  
以下是針對此動作預先定義的輸出。

executionArn  
執行的 ARN。  
類型：字串

input  
包含執行之 JSON 輸入資料的字串。長度限制適用於承載大小，並以 UTF-8 編碼表示為位元組。  
類型：字串

name  
執行的名稱。  
類型：字串

output  
執行的 JSON 輸出資料。長度限制適用於承載大小，在 UTF-8 編碼中表示為位元組。  
類型：字串

startDate  
開始執行的日期。  
類型：字串

stateMachineArn  
已執行的指定機器的 ARN。  
類型：字串

status  
當前執行狀態。  
類型：字串

stopDate  
如果執行已經結束，則為執行停止的日期。  
類型：字串

# `aws:invokeWebhook`：叫用 Automation Webhook 整合
<a name="invoke-webhook"></a>

叫用指定的 Automation Webhook 整合。如需有關建立 Automation 整合的詳細資訊，請參閱 [為 Automation 建立 Webhook 整合](creating-webhook-integrations.md)。

**注意**  
`aws:invokeWebhook` 動作支援自動限流重試。如需詳細資訊，請參閱[設定限流操作的自動重試](automation-throttling-retry.md)。

**注意**  
若要使用 `aws:invokeWebhook` 動作，使用者或服務角色必須允許執行以下動作：  
ssm:GetParameter
kms:解密
只有在您使用客戶受管金鑰來加密整合的 參數時，才需要 AWS Key Management Service (AWS KMS) `Decrypt`操作的許可。

**Input**  
提供要叫用的 Automation 整合的資訊。

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

```
action: "aws:invokeWebhook"
inputs: 
 IntegrationName: "exampleIntegration"
 Body: "Request body"
```

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

```
{
    "action": "aws:invokeWebhook",
    "inputs": {
        "IntegrationName": "exampleIntegration",
        "Body": "Request body"
    }
}
```

------

IntegrationName  
Automation 整合的名稱。例如 `exampleIntegration`。您指定的整合必須已經存在。  
類型：字串  
必要：是

Body  
叫用 Webhook 整合時要傳送的承載。  
類型：字串  
必要：否Output

回應  
從 Webhook 提供者回應中收到的文字。

ResponseCode  
從 Webhook 提供者回應中收到的 HTTP 狀態碼。

# `aws:invokeLambdaFunction` – 叫用 AWS Lambda 函數
<a name="automation-action-lamb"></a>

叫用指定的 AWS Lambda 函數。

**注意**  
每個 `aws:invokeLambdaFunction` 動作最久可執行 300 秒 (5 分鐘)。您可以透過指定 `aws:invokeLambdaFunction` 步驟的 `timeoutSeconds` 參數來限制逾時。

**注意**  
`aws:invokeLambdaFunction` 動作支援自動限流重試。如需詳細資訊，請參閱[設定限流操作的自動重試](automation-throttling-retry.md)。

**Input**  
此動作支援 Lambda 服務大部分的呼叫參數。如需詳細資訊，請參閱[呼叫](https://docs.aws.amazon.com/lambda/latest/dg/API_Invoke.html)。

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

```
name: invokeMyLambdaFunction
action: aws:invokeLambdaFunction
maxAttempts: 3
timeoutSeconds: 120
onFailure: Abort
inputs:
  FunctionName: MyLambdaFunction
```

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

```
{
    "name": "invokeMyLambdaFunction",
    "action": "aws:invokeLambdaFunction",
    "maxAttempts": 3,
    "timeoutSeconds": 120,
    "onFailure": "Abort",
    "inputs": {
        "FunctionName": "MyLambdaFunction"
    }
}
```

------

FunctionName  
Lambda 函數的名稱。此函數必須存在。  
類型：字串  
必要：是

限定詞  
函數版本或別名名稱。  
類型：字串  
必要：否

InvocationType  
呼叫類型。預設值為 `RequestResponse`。  
類型：字串  
有效值：`Event` \$1 `RequestResponse` \$1 `DryRun`  
必要：否

LogType  
如果預設值為 `Tail`，則叫用類型必須是 `RequestResponse`。Lambda 會傳回由 Lambda 函數產生的最新 4 KB 日誌資料，且為 base64 編碼。  
類型：字串  
有效值：`None` \$1 `Tail`  
必要：否

ClientContext  
用戶端特定的資訊。  
必要：否

InputPayload  
將傳遞給處理常式的第一個參數的 YAML 或 JSON 物件。您可以使用此輸入將資料傳遞到函數。此輸入相比傳統 `Payload` 輸入提供了更多靈活性和支援。如果您為該動作同時定義 `InputPayload` 和 `Payload`，則 `InputPayload` 優先，並且不使用 `Payload` 值。  
類型：StringMap  
必要：否

酬載  
將傳遞給處理常式的第一個參數的 JSON 字串。這可以用來將輸入資料傳遞到函數。建議您使用 `InputPayload` 輸入，因為已新增其功能。  
類型：字串  
必要：否Output

StatusCode  
HTTP 狀態碼

FunctionError  
如果存在，則表示函數執行期間發生錯誤。錯誤詳細資訊包含在回應承載中。

LogResult  
Lambda 函數呼叫的 base64 編碼日誌。日誌僅在呼叫類型為 `RequestResponse` 時才會出現，且日誌經過請求。

酬載  
由 Lambda 函數傳回之物件的 JSON 表示法。承載僅在呼叫類型為 `RequestResponse` 時才會出現。

以下節錄自 `AWS-PatchInstanceWithRollback` Runbook，示範如何從 `aws:invokeLambdaFunction` 動作參照輸出。

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

```
- name: IdentifyRootVolume
  action: aws:invokeLambdaFunction
  inputs:
    FunctionName: "IdentifyRootVolumeLambda-{{automation:EXECUTION_ID}}"
    Payload: '{"InstanceId": "{{InstanceId}}"}'
- name: PrePatchSnapshot
  action: aws:executeAutomation
  inputs:
    DocumentName: "AWS-CreateSnapshot"
    RuntimeParameters:
      VolumeId: "{{IdentifyRootVolume.Payload}}"
      Description: "ApplyPatchBaseline restoration case contingency"
```

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

```
{
    "name": "IdentifyRootVolume",
    "action": "aws:invokeLambdaFunction",
    "inputs": {
      "FunctionName": "IdentifyRootVolumeLambda-{{automation:EXECUTION_ID}}",
      "Payload": "{\"InstanceId\": \"{{InstanceId}}\"}"
    }
  },
  {
    "name": "PrePatchSnapshot",
    "action": "aws:executeAutomation",
    "inputs": {
      "DocumentName": "AWS-CreateSnapshot",
      "RuntimeParameters": {
        "VolumeId": "{{IdentifyRootVolume.Payload}}",
        "Description": "ApplyPatchBaseline restoration case contingency"
      }
    }
  }
```

------

# `aws:loop` - 迭代自動化中的步驟
<a name="automation-action-loop"></a>

此動作會迭代自動化執行手冊中的步驟子集。您可以選擇 `do while` 或 `for each` 樣式迴圈。若要建構 `do while` 迴圈，請使用 `LoopCondition` 輸入參數。若要建構 `for each` 迴圈，請使用 `Iterators` 和 `IteratorDataType` 輸入參數。使用 `aws:loop` 動作時，僅指定 `Iterators` 或 `LoopCondition` 輸入參數。迭代的數量的上限為 100。

`onCancel` 屬性只能針對迴圈內定義的步驟。`aws:loop` 動作不支援 `onCancel` 屬性。`onFailure` 屬性可用於 `aws:loop` 動作，但只有在發生意外錯誤導致步驟失敗時，才會使用該此屬性。如果您定義迴圈中步驟的 `onFailure` 屬性，則 `aws:loop` 動作會繼承這些屬性，並在發生故障時做出相應反應。

**範例**  
下列是如何建構不同類型迴圈動作的範例。

------
#### [ do while ]

```
name: RepeatMyLambdaFunctionUntilOutputIsReturned
action: aws:loop
inputs:
    Steps:
    - name: invokeMyLambda
        action: aws:invokeLambdaFunction
        inputs:
        FunctionName: LambdaFunctionName
        outputs:
        - Name: ShouldRetry
            Selector: $.Retry
            Type: Boolean
    LoopCondition:
        Variable: "{{ invokeMyLambda.ShouldRetry }}"
        BooleanEquals: true
    MaxIterations: 3
```

------
#### [ for each ]

```
name: stopAllInstancesWithWaitTime
action: aws:loop
inputs:
    Iterators: "{{ DescribeInstancesStep.InstanceIds }}"
    IteratorDataType: "String"
    Steps:
    - name: stopOneInstance
        action: aws:changeInstanceState
        inputs:
        InstanceIds:
            - "{{stopAllInstancesWithWaitTime.CurrentIteratorValue}}"
        CheckStateOnly: false
        DesiredState: stopped
    - name: wait10Seconds
        action: aws:sleep
        inputs:
        Duration: PT10S
```

------

**Input**  
輸入如下。

迭代器  
要重複執行的步驟的項目清單。迭代器的數量的上限為 100。  
類型：StringList  
必要：否

迭代器資料類型  
用來指定 `Iterators` 的資料類型的選用參數。此參數的值可與 `Iterators` 輸入參數一起提供。如果您不指定此參數和 `Iterators` 的值，則您必須指定 `LoopCondition` 參數的值。  
類型：字串  
有效值：布林值 \$1 整數 \$1 字串 \$1 StringMap  
預設：字串  
必要：否

LoopCondition  
包含 `Variable` 和要評估的運算子條件。如果您不指定此參數的值，則您必須指定 `Iterators` 和 `IteratorDataType` 參數的值。您可以透過 `And`、`Not` 和 `Or` 運算子的組合來使用複雜的運算子評估。在迴圈中的步驟完成後，就會評估條件。如果條件為 `true` 且尚未達到 `MaxIterations` 值，則迴圈中的步驟會再次執行。運算子條件如下：  

**字串運算**
+ StringEquals
+ EqualsIgnoreCase
+ StartsWith
+ EndsWith
+ Contains

**數值運算**
+ NumericEquals
+ NumericGreater
+ NumericLesser
+ NumericGreaterOrEquals
+ NumericLesser
+ NumericLesserOrEquals

**布林運算**
+ BooleanEquals
類型：StringMap  
必要：否

MaxIterations  
迴圈中步驟執行的最大次數。達到此輸入指定的值後，即使 `LoopCondition` 仍然 `true`，或 `Iterators` 參數中仍有剩餘物件，迴圈也會停止執行。  
類型：整數  
有效值：1 - 100  
必要：否

步驟  
在迴圈中執行的步驟清單。這些函數就像一個巢狀的執行手冊。在這些步驟中，您可以使用語法 `for each`，存取 `{{loopStepName.CurrentIteratorValue}}` 迴圈的目前迭代器值。您還可以使用語法 `{{loopStepName.CurrentIteration}}`，存取這兩個迴圈類型的目前迭代的整數值。  
類型：步驟清單  
必要：是Output

CurrentIteration  
將目前迴圈迭代作為整數。迭代值從 1 開始。  
類型：整數

CurrentIteratorValue  
做為字串的目前迭代器的值。此輸出僅存在於 `for each` 迴圈中。  
類型：字串

# `aws:pause` – 暫停自動化
<a name="automation-action-pause"></a>

此動作會暫停自動化。一旦暫停，自動化狀態就會是 *Waiting* (等待)。若要繼續自動化，請使用具 `Resume` 訊號類型的 [SendAutomationSignal](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_SendAutomationSignal.html) API 操作。我們建議使用 `aws:sleep` 或者 `aws:approve` 操作，以更精細地控制您的工作流程。

**注意**  
此動作的預設逾時時間為 7 天 (604800 秒)，最大值為 30 天 (2592000 秒)。您可以透過指定 `aws:pause` 步驟的 `timeoutSeconds` 參數來限制或延長逾時。

**Input**  
輸入如下。

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

```
name: pauseThis
action: aws:pause
timeoutSeconds: 1209600
inputs: {}
```

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

```
{
    "name": "pauseThis",
    "action": "aws:pause",
    "timeoutSeconds": "1209600",
    "inputs": {}
}
```

------Output

無  


# `aws:runCommand` – 在受管執行個體上執行命令
<a name="automation-action-runcommand"></a>

執行指定的命令。

**注意**  
自動化僅支援一個 AWS Systems Manager Run Command動作的*output*。Runbook 可以包含多個 Run Command 動作，但一次僅一個動作支援output。

**Input**  
此動作支援大部分的傳送命令參數。如需詳細資訊，請參閱 [SendCommand](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_SendCommand.html)。

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

```
- name: checkMembership
  action: 'aws:runCommand'
  inputs:
    DocumentName: AWS-RunPowerShellScript
    InstanceIds:
      - '{{InstanceIds}}'
    Parameters:
      commands:
        - (Get-WmiObject -Class Win32_ComputerSystem).PartOfDomain
```

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

```
{
    "name": "checkMembership",
    "action": "aws:runCommand",
    "inputs": {
        "DocumentName": "AWS-RunPowerShellScript",
        "InstanceIds": [
            "{{InstanceIds}}"
        ],
        "Parameters": {
            "commands": [
                "(Get-WmiObject -Class Win32_ComputerSystem).PartOfDomain"
            ]
        }
    }
}
```

------

DocumentName  
如果您擁有 或 命令類型文件 AWS，請指定文件的名稱。如果您使用的文件是由不同 AWS 帳戶共用，則請指定文件的 Amazon Resource Name (ARN)。如需使用共用文件的詳細資訊，請參閱 [使用共用的 SSM 文件](documents-ssm-sharing.md#using-shared-documents)。  
類型：字串  
必要：是

InstanceIds  
您想要命令執行的執行個體 ID。您最多可以指定 50 個 ID。  
您也可以使用虛擬參數 `{{RESOURCE_ID}}` 取代執行個體 ID，在目標群組中的所有執行個體上執行命令。如需這些虛擬參數的詳細資訊，請參閱[註冊維護時段任務時使用虛擬參數](maintenance-window-tasks-pseudo-parameters.md)。  
另一種方法是使用 `Targets` 參數將命令傳送到執行個體機群。`Targets` 參數接受 Amazon Elastic Compute Cloud (Amazon EC2) 標籤。如需使用 `Targets` 參數的詳細資訊，請參閱 [大規模執行命令](send-commands-multiple.md)。  
類型：StringList  
必要：否 (如果您未指定 InstanceIds 或使用 `{{RESOURCE_ID}}` 虛擬參數，則必須指定 `Targets` 參數。)

Targets  
一系列的搜尋條件，使用您指定的鍵值組合將執行個體設為目標。若您沒有在呼叫中提供一或多個執行個體 ID，則 `Targets` 為必要項目。如需使用 `Targets` 參數的詳細資訊，請參閱 [大規模執行命令](send-commands-multiple.md)。  
類型：MapList (清單中的對應結構描述必須符合物件。) 如需詳細資訊，請參閱《AWS Systems Manager API 參考**》中的 [Target](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_Target.html)。  
必要：否 (如果您未指定 `Targets`，則必須指定 InstanceIds 或使用 `{{RESOURCE_ID}}` 虛擬參數)。  
以下是範例。  

```
- name: checkMembership
  action: aws:runCommand
  inputs:
    DocumentName: AWS-RunPowerShellScript
    Targets:
      - Key: tag:Stage
        Values:
          - Gamma
          - Beta
      - Key: tag-key
        Values:
          - Suite
    Parameters:
      commands:
        - (Get-WmiObject -Class Win32_ComputerSystem).PartOfDomain
```

```
{
    "name": "checkMembership",
    "action": "aws:runCommand",
    "inputs": {
        "DocumentName": "AWS-RunPowerShellScript",
        "Targets": [                   
            {
                "Key": "tag:Stage",
                "Values": [
                    "Gamma", "Beta"
                ]
            },
            {
                "Key": "tag:Application",
                "Values": [
                    "Suite"
                ]
            }
        ],
        "Parameters": {
            "commands": [
                "(Get-WmiObject -Class Win32_ComputerSystem).PartOfDomain"
            ]
        }
    }
}
```

Parameters  
文件中指定的必要和選用參數。  
類型：映射  
必要：否

CloudWatchOutputConfig  
用於傳送命令輸出至 Amazon CloudWatch Logs 的組態選項。如需傳送命令輸出至 CloudWatch Logs 的詳細資訊，請參閱 [設定 Run Command 的 Amazon CloudWatch Logs](sysman-rc-setting-up-cwlogs.md)。  
類型：StringMap (映射的結構描述必須與物件相符。如需詳細資訊，請參閱《*AWS Systems Manager API 參考*》中的 [CloudWatchOutputConfig](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_CloudWatchOutputConfig.html)。  
必要：否  
以下是範例。  

```
- name: checkMembership
  action: aws:runCommand
  inputs:
    DocumentName: AWS-RunPowerShellScript
    InstanceIds:
      - "{{InstanceIds}}"
    Parameters:
      commands:
        - "(Get-WmiObject -Class Win32_ComputerSystem).PartOfDomain"
    CloudWatchOutputConfig:
      CloudWatchLogGroupName: CloudWatchGroupForSSMAutomationService
      CloudWatchOutputEnabled: true
```

```
{
    "name": "checkMembership",
    "action": "aws:runCommand",
    "inputs": {
        "DocumentName": "AWS-RunPowerShellScript",
        "InstanceIds": [
            "{{InstanceIds}}"
        ],
        "Parameters": {
            "commands": [
                "(Get-WmiObject -Class Win32_ComputerSystem).PartOfDomain"
            ]
        },
        "CloudWatchOutputConfig" : { 
                "CloudWatchLogGroupName": "CloudWatchGroupForSSMAutomationService",
                "CloudWatchOutputEnabled": true
        }
    }
}
```

Comment  
關於命令，由使用者定義的資訊。  
類型：字串  
必要：否

DocumentHash  
文件的雜湊。  
類型：字串  
必要：否

DocumentHashType  
雜湊的類型。  
類型：字串  
有效值：`Sha256` \$1 `Sha1`  
必要：否

NotificationConfig  
傳送通知的組態。  
必要：否

OutputS3BucketName  
用於命令輸出回應的 S3 儲存貯體名稱。您的受管節點必須具有 S3 儲存貯體許可，才能成功記錄輸出。  
類型：字串  
必要：否

OutputS3KeyPrefix  
字首。  
類型：字串  
必要：否

ServiceRoleArn  
 AWS Identity and Access Management (IAM) 角色的 ARN。  
類型：字串  
必要：否

TimeoutSeconds  
在執行個體 AWS Systems Manager SSM Agent上等待命令交付至 的時間，以秒為單位。如果在指定的值到達之前執行個體上的 SSM Agent 沒有收到命令，則命令的狀態會變更為 `Delivery Timed Out`。  
類型：整數  
必要：否  
有效值：30-2592000Output

CommandId  
命令的 ID。

狀態  
命令的狀態。

ResponseCode  
命令的回應代碼。如果執行的文件有 1 個以上步驟，則不會傳回此輸出的值。

Output  
命令的輸出。如果您使用命令將標籤或多個執行個體設為目標，則不會傳回 output 值。您可以使用 `GetCommandInvocation` 和 `ListCommandInvocations` API 操作來擷取個別執行個體的輸出。

# `aws:runInstances` – 啟動 Amazon EC2 執行個體。
<a name="automation-action-runinstance"></a>

啟動新的 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體。

**注意**  
`aws:runInstances` 動作支援自動限流重試。如需詳細資訊，請參閱[設定限流操作的自動重試](automation-throttling-retry.md)。

**Input**  
動作支援大部分的 API 參數。如需詳細資訊，請參閱 [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) API 文件。

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

```
name: launchInstance
action: aws:runInstances
maxAttempts: 3
timeoutSeconds: 1200
onFailure: Abort
inputs:
  ImageId: ami-12345678
  InstanceType: t2.micro
  MinInstanceCount: 1
  MaxInstanceCount: 1
  IamInstanceProfileName: myRunCmdRole
  TagSpecifications:
  - ResourceType: instance
    Tags:
    - Key: LaunchedBy
      Value: SSMAutomation
    - Key: Category
      Value: HighAvailabilityFleetHost
```

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

```
{
   "name":"launchInstance",
   "action":"aws:runInstances",
   "maxAttempts":3,
   "timeoutSeconds":1200,
   "onFailure":"Abort",
   "inputs":{
      "ImageId":"ami-12345678",
      "InstanceType":"t2.micro",
      "MinInstanceCount":1,
      "MaxInstanceCount":1,
      "IamInstanceProfileName":"myRunCmdRole",
      "TagSpecifications":[
         {
            "ResourceType":"instance",
            "Tags":[
               {
                  "Key":"LaunchedBy",
                  "Value":"SSMAutomation"
               },
               {
                  "Key":"Category",
                  "Value":"HighAvailabilityFleetHost"
               }
            ]
         }
      ]
   }
}
```

------

AdditionalInfo  
預訂.  
類型：字串  
必要：否

BlockDeviceMappings  
執行個體的區塊型儲存設備。  
類型：MapList  
必要：否

ClientToken  
用於確保請求之冪等的識別符。  
類型：字串  
必要：否

DisableApiTermination  
開啟或關閉執行個體 API 終止。  
類型：布林值  
必要：否

EbsOptimized  
開啟或關閉 Amazon Elastic Block Store (Amazon EBS) 最佳化。  
類型：布林值  
必要：否

IamInstanceProfileArn  
執行個體 (IAM) 執行個體描述檔的 Amazon Resource Name AWS Identity and Access Management (ARN)。  
類型：字串  
必要：否

IamInstanceProfileName  
執行個體之 IAM 執行個體設定檔的名稱。  
類型：字串  
必要：否

ImageId  
Amazon Machine Image (AMI) 的 ID。  
類型：字串  
必要：是

InstanceInitiatedShutdownBehavior  
指示執行個體在系統關機時停止或終止。  
類型：字串  
必要：否

InstanceType  
執行個體類型。  
如果不提供執行個體類型價值，則會使用 m1.small 執行個體類型。
類型：字串  
必要：否

KernelId  
核心的 ID。  
類型：字串  
必要：否

KeyName  
金鑰對的名稱。  
類型：字串  
必要：否

MaxInstanceCount  
要啟動的執行個體數量上限。  
類型：字串  
必要：否

MetadataOptions  
執行個體的中繼資料選項。如需詳細資訊，請參閱 [InstanceMetadataOptionsRequest](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_InstanceMetadataOptionsRequest.html)。  
類型：StringMap  
必要：否

MinInstanceCount  
要啟動的執行個體數量下限。  
類型：字串  
必要：否

監控  
打開或關閉詳細監控。  
類型：布林值  
必要：否

NetworkInterfaces  
網路界面。  
類型：MapList  
必要：否

配置  
執行個體的配置。  
類型：StringMap  
必要：否

PrivateIpAddress  
主要 IPv4 地址。  
類型：字串  
必要：否

RamdiskId  
RAM 磁碟的 ID。  
類型：字串  
必要：否

SecurityGroupIds  
執行個體安全群組的 ID。  
類型：StringList  
必要：否

SecurityGroups  
執行個體安全群組的名稱。  
類型：StringList  
必要：否

SubnetId  
子網路 ID。  
類型：字串  
必要：否

TagSpecifications  
要在啟動期間套用到資源的標籤。您只能在啟動時標記執行個體和磁碟區。指定的標籤會套用至所有於啟動期間建立的執行個體或磁碟區。若要在執行個體啟動後將其標記，請使用 [`aws:createTags` – 建立 AWS 資源的標籤](automation-action-createtag.md) 動作。  
類型：MapList (如需詳細資訊，請參閱 [TagSpecification](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_TagSpecification.html)。)  
必要：否

UserData  
做為字串常值提供的指令碼。如果輸入常值，則其必須為 Base64 編碼。  
類型：字串  
必要：否Output

InstanceIds  
執行個體的 ID。

InstanceStates  
執行個體目前的狀態。

# `aws:sleep` – 延遲自動化
<a name="automation-action-sleep"></a>

將自動化延遲一段指定的時間。此動作採用國際標準組織 (ISO) 8601 日期和時間格式。如需此日期和時間格式的詳細資訊，請參閱 [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html)。

**Input**  
您可以將自動化延遲一段指定的持續時間。

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

```
name: sleep
action: aws:sleep
inputs:
  Duration: PT10M
```

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

```
{
   "name":"sleep",
   "action":"aws:sleep",
   "inputs":{
      "Duration":"PT10M"
   }
}
```

------

您也可以延遲自動化直到指定的日期和時間。如果超過指定日期和時間，動作會立即執行。

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

```
name: sleep
action: aws:sleep
inputs:
  Timestamp: '2020-01-01T01:00:00Z'
```

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

```
{
    "name": "sleep",
    "action": "aws:sleep",
    "inputs": {
        "Timestamp": "2020-01-01T01:00:00Z"
    }
}
```

------

**注意**  
自動化支援的延遲上限為 604799 秒 (7 天)。

持續時間  
ISO 8601 持續時間。您無法指定負數的持續時間。  
類型：字串  
必要：否

時間戳記  
ISO 8601 時間戳記。如果您不指定此參數的值，則您必須指定 `Duration` 參數的值。  
類型：字串  
必要：否Output

無  


# `aws:updateVariable` - 更新執行手冊變數的值
<a name="automation-action-update-variable"></a>

此動作會更新執行手冊變數的值。值的資料類型必須符合您希望更新的變數的資料類型。不支援資料類型轉換。`aws:updateVariable` 動作不支援 `onCancel` 屬性。

**Input**  
輸入如下。

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

```
name: updateStringList
action: aws:updateVariable
inputs:
    Name: variable:variable name
    Value:
    - "1"
    - "2"
```

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

```
{
    "name": "updateStringList",
    "action": "aws:updateVariable",
    "inputs": {
        "Name": "variable:variable name",
        "Value": ["1","2"]
    }
}
```

------

名稱  
您希望更新其值的變數名稱。您必須使用格式 `variable:variable name`  
類型：字串  
必要：是

Value  
要指派給變數的新值。該值必須與變數的資料類型相符。不支援資料類型轉換。  
類型：布林值 \$1 整數 \$1 MapList \$1 字串 \$1 StringList \$1 StringMap  
必要：是  
限制條件：  
+ MapList 最多可包含 200 個項目。
+ 鍵的長度最短可以是 1，最長可以是 50。
+ StringList 最少可以是 0 個項目，最多可以是 50 個項目。
+ 字串的長度最短可以是 1，最長可以是 512。Output

無  


# `aws:waitForAwsResourceProperty` – 等待 AWS 資源屬性
<a name="automation-action-waitForAwsResourceProperty"></a>

`aws:waitForAwsResourceProperty` 動作可讓您的自動化在繼續自動化之前等待特定的資源狀態或事件狀態。如需有關如何使用此動作的更多範例，請參閱 [其他執行手冊範例](automation-document-examples.md)。

**注意**  
此動作的預設逾時值為 3600 秒 (1 小時)。您可以透過指定 `aws:waitForAwsResourceProperty` 步驟的 `timeoutSeconds` 參數來限制或延長逾時。如需使用此動作的詳細資訊和範例，請參閱 [處理 Runbook 中的逾時](automation-handling-timeouts.md)。

**注意**  
`aws:waitForAwsResourceProperty` 動作支援自動限流重試。如需詳細資訊，請參閱[設定限流操作的自動重試](automation-throttling-retry.md)。

**Input**  
輸入是由您選擇的 API 操作定義。

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

```
action: aws:waitForAwsResourceProperty
inputs:
  Service: The official namespace of the service
  Api: The API operation or method name
  API operation inputs or parameters: A value
  PropertySelector: Response object
  DesiredValues:
  - Desired property value
```

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

```
{
  "action": "aws:waitForAwsResourceProperty",
  "inputs": {
    "Service":"The official namespace of the service",
    "Api":"The API operation or method name",
    "API operation inputs or parameters":"A value",
    "PropertySelector": "Response object",
    "DesiredValues": [
      "Desired property value"
    ]
  }
}
```

------

服務  
包含您要執行之 API 操作的 AWS 服務 命名空間。例如， 的命名空間 AWS Systems Manager 為 `ssm`。Amazon Elastic Compute Cloud (Amazon EC2) 的命名空間為 `ec2`。您可以在 *AWS CLI 命令參考*的[可用服務](https://docs.aws.amazon.com/cli/latest/reference/#available-services)區段中檢視支援的 AWS 服務 命名空間清單。  
類型：字串  
必要：是

Api  
您想要執行的 API 操作之名稱。您可以檢視 API 操作 (也稱為方法)，方式是在以下[服務參考](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html)頁面的左側導覽中選擇一項服務。在您想要呼叫之服務的 **Client (用戶端)** 部分選擇一個方法。例如，Amazon Relational Database Service (Amazon RDS) 的所有 API 操作 (方法) 均列於以下頁面：[Amazon RDS 方法](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html)。  
類型：字串  
必要：是

API 操作輸入  
一個或多個 API 操作輸入。您可以檢視可用的輸入 (也稱為參數)，方式是在以下[服務參考](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html)頁面的左側導覽中選擇一項服務。在您想要呼叫之服務的 **Client (用戶端)** 部分選擇一個方法。例如，Amazon RDS 的所有方法均列於以下頁面：[Amazon RDS 方法](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html)。選擇 [describe\$1db\$1instances](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html#RDS.Client.describe_db_instances) 方法並向下捲動以查看可用的參數，例如 **DBInstanceIdentifier**、**Name**、**Values**。  

```
inputs:
  Service: The official namespace of the service
  Api: The API operation name
  API input 1: A value
  API Input 2: A value
  API Input 3: A value
```

```
"inputs":{
      "Service":"The official namespace of the service",
      "Api":"The API operation name",
      "API input 1":"A value",
      "API Input 2":"A value",
      "API Input 3":"A value"
}
```
類型：由所選的 API 操作決定  
必要：是

PropertySelector  
回應物件中特定屬性的 JSONPath。您可以檢視回應物件，方式是在以下[服務參考](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html)頁面的左側導覽中選擇一項服務。在您想要呼叫之服務的 **Client (用戶端)** 部分選擇一個方法。例如，Amazon RDS 的所有方法均列於以下頁面：[Amazon RDS 方法](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html)。選擇 [describe\$1db\$1instances](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html#RDS.Client.describe_db_instances) 方法並向下捲動至 **Response Structure (回應結構)** 區段。**DBInstances** 列為回應物件。  
類型：字串  
必要：是

DesiredValues  
讓自動化繼續的預期狀態。  
類型：MapList、StringList  
必要：是

# 自動化系統變數
<a name="automation-variables"></a>

AWS Systems Manager Automation Runbook 使用以下變數。如需這些變數的使用範例，請檢視 `AWS-UpdateWindowsAmi` Runbook 的 JSON 來源。

**檢視 `AWS-UpdateWindowsAmi` Runbook 的 JSON 來源**

1. 開啟位於 AWS Systems Managerhttps://console.aws.amazon.com/systems-manager/ 的主控台。[https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/)

1. 在導覽窗格中，選擇 **Documents (文件)**。

1. 在文件清單中，使用搜尋列或搜尋列右側的號碼選擇 Runbook `AWS-UpdateWindowsAmi`。

1. 選擇 **Content (內容)** 索引標籤。

**系統變數**  
Automation Runbook 目前支援以下系統變數。


****  

| 變數 | 詳細資訊 | 
| --- | --- | 
|  `global:ACCOUNT_ID`  |  執行 Automation 的使用者或角色之 AWS 帳戶 ID。  | 
|  `global:DATE`  |  (在執行時間的) 日期格式為 yyyy-MM-dd。  | 
|  `global:DATE_TIME`  |  (在執行時間的) 日期和時間格式為 yyyy-MM-dd\$1HH.mm.ss。  | 
|  `global:AWS_PARTITION`  |  資源所在的分割區。對於標準 AWS 區域，分割區為 `aws`。如果資源處於其他分割區，則會傳回 `aws-partitionname` 分割區。例如，AWS GovCloud (US-West) 區域的資源分割區為 `aws-us-gov`。  | 
|  `global:REGION`  |  Runbook 執行的區域。例如 us-east-2。  | 

**自動化變數**  
Runbook 支援以下自動化變數。


****  

| 變數 | 詳細資訊 | 
| --- | --- | 
|  `automation:EXECUTION_ID`  |  指派給目前自動化的唯一識別符。例如 `1a2b3c-1a2b3c-1a2b3c-1a2b3c1a2b3c1a2b3c`。  | 

**Topics**
+ [術語](#automation-terms)
+ [支援的案例](#automation-variables-support)
+ [不支援的案例](#automation-variables-unsupported)

## 術語
<a name="automation-terms"></a>

以下術語說明如何解決變數和參數。


****  

| 術語 | 定義 | 範例 | 
| --- | --- | --- | 
|  Constant ARN (常數 ARN)  |  不含變數的有效 Amazon Resource Name (ARN)。  |  `arn:aws:iam::123456789012:role/roleName`  | 
|  Runbook 參數  |  在 Runbook 層級定義的參數 (例如，`instanceId`)。此參數用於基本的字串替換。此值會在 Start Execution (開始執行) 時間提供。  |  <pre>{ <br />   "description": "Create Image Demo",<br />   "version": "0.3",<br />   "assumeRole": "Your_Automation_Assume_Role_ARN",<br />   "parameters":{ <br />      "instanceId": { <br />         "type": "String",<br />         "description": "Instance to create image from"<br />   }<br />}</pre>  | 
|  System variable (系統變數)  |  在 Runbook 任何部分評估時替換到 Runbook 的一般變數。  |  <pre>"activities": [ <br />   { <br />      "id": "copyImage",<br />      "activityType": "AWS-CopyImage",<br />      "maxAttempts": 1,<br />      "onFailure": "Continue",<br />      "inputs": { <br />         "ImageName": "{{imageName}}",<br />         "SourceImageId": "{{sourceImageId}}",<br />         "SourceRegion": "{{sourceRegion}}",<br />         "Encrypted": true,<br />         "ImageDescription": "Test CopyImage Description created on {{global:DATE}}"<br />      }<br />   }<br />]</pre>  | 
|  Automation variable (自動化變數)  |  在文件任何部分評估時替換到 Runbook 且與自動化相關的變數。  |  <pre>{ <br />   "name": "runFixedCmds",<br />   "action": "aws:runCommand",<br />   "maxAttempts": 1,<br />   "onFailure": "Continue",<br />   "inputs": { <br />      "DocumentName": "AWS-RunPowerShellScript",<br />      "InstanceIds": [ <br />         "{{LaunchInstance.InstanceIds}}"<br />      ],<br />      "Parameters": { <br />         "commands": [ <br />            "dir",<br />            "date",<br />            "“{{outputFormat}}” -f “left”,”right”,”{{global:DATE}}”,”{{automation:EXECUTION_ID}}”<br />         ]<br />      }<br />   }<br />}</pre>  | 
|  Systems Manager 參數  |  AWS Systems Manager Parameter Store 內定義的變數。無法在步驟輸入中直接參考它。存取參數可能需要許可。  |  <pre><br />description: Launch new Windows test instance<br />schemaVersion: '0.3'<br />assumeRole: '{{AutomationAssumeRole}}'<br />parameters:<br />  AutomationAssumeRole:<br />    type: String<br />    default: ''<br />    description: >-<br />      (Required) The ARN of the role that allows Automation to perform the<br />      actions on your behalf. If no role is specified, Systems Manager<br />      Automation uses your IAM permissions to run this runbook.<br />  LatestAmi:<br />    type: String<br />    default: >-<br />      {{ssm:/aws/service/ami-windows-latest/Windows_Server-2016-English-Full-Base}}<br />    description: The latest Windows Server 2016 AMI queried from the public parameter.<br />mainSteps:<br />  - name: launchInstance<br />    action: 'aws:runInstances'<br />    maxAttempts: 3<br />    timeoutSeconds: 1200<br />    onFailure: Abort<br />    inputs:<br />      ImageId: '{{LatestAmi}}'<br />...</pre>  | 

## 支援的案例
<a name="automation-variables-support"></a>


****  

| 案例 | 說明 | 範例 | 
| --- | --- | --- | 
|  建立時的常數 ARN `assumeRole`。  |  將會執行授權檢查，以確認呼叫的使用者許可傳遞指定的`assumeRole`。  |  <pre>{<br />  "description": "Test all Automation resolvable parameters",<br />  "schemaVersion": "0.3",<br />  "assumeRole": "arn:aws:iam::123456789012:role/roleName",<br />  "parameters": { <br />  ...</pre>  | 
|  自動化啟動時，為 `AssumeRole` 提供的 Runbook 參數。  |  必須在 Runbook 的參數清單中定義。  |  <pre>{<br />  "description": "Test all Automation resolvable parameters",<br />  "schemaVersion": "0.3",<br />  "assumeRole": "{{dynamicARN}}",<br />  "parameters": {<br /> ...</pre>  | 
|  在開始時提供給 Runbook 參數的值。  |  客戶提供用於參數的值。在開始時間提供的任何輸入都必須在 Runbook 的參數清單中定義。  |  <pre>...<br />"parameters": {<br />    "amiId": {<br />      "type": "String",<br />      "default": "ami-12345678",<br />      "description": "list of commands to run as part of first step"<br />    },<br />...</pre> 啟動自動執行的輸入包含：`{"amiId" : ["ami-12345678"] }`  | 
|  Runbook 內容中參考的 Systems Manager 參數。  |  變數存在於客戶帳戶內，或是可公開存取的參數，而且 Runbook 的 `AssumeRole` 可以存取變數。檢查會於建立時間執行，以確認 `AssumeRole` 可存取。無法在步驟輸入中直接參考參數。  |  <pre><br />...<br />parameters:<br />    LatestAmi:<br />    type: String<br />    default: >-<br />      {{ssm:/aws/service/ami-windows-latest/Windows_Server-2016-English-Full-Base}}<br />    description: The latest Windows Server 2016 AMI queried from the public parameter.<br />mainSteps:<br />  - name: launchInstance<br />    action: 'aws:runInstances'<br />    maxAttempts: 3<br />    timeoutSeconds: 1200<br />    onFailure: Abort<br />    inputs:<br />      ImageId: '{{LatestAmi}}'<br />...</pre>  | 
|  在步驟定義中參考的系統變數  |  當自動化啟動時，系統變數會替換至 Runbook。插入 Runbook 的值與替換發生的時間相關。例如，由於執行步驟之間耗費的時間，因此在步驟 1 插入的時間變數值會不同於在步驟 3 插入的值。系統變數不必在 Runbook 的參數清單中設定。  |  <pre>...<br />  "mainSteps": [<br />    {<br />      "name": "RunSomeCommands",<br />      "action": "aws:runCommand",<br />      "maxAttempts": 1,<br />      "onFailure": "Continue",<br />      "inputs": {<br />        "DocumentName": "AWS:RunPowerShell",<br />        "InstanceIds": ["{{LaunchInstance.InstanceIds}}"],<br />        "Parameters": {<br />            "commands" : [<br />                "echo {The time is now {{global:DATE_TIME}}}"<br />            ]<br />        }<br />    }<br />}, ... </pre>  | 
|  在步驟定義中參考的自動化變數。  |  自動化變數不必在 Runbook 的參數清單中設定。唯一支援的自動化變數為 **automation:EXECUTION\$1ID**。  |  <pre>...<br />"mainSteps": [<br />    {<br />      "name": "invokeLambdaFunction",<br />      "action": "aws:invokeLambdaFunction",<br />      "maxAttempts": 1,<br />      "onFailure": "Continue",<br />      "inputs": {<br />        "FunctionName": "Hello-World-LambdaFunction",<br /><br />"Payload" : "{ "executionId" : "{{automation:EXECUTION_ID}}" }"<br />      }<br />    }<br />... </pre>  | 
|  請在下一個步驟定義中參閱前一個步驟的輸出。  |  此為參數重新導向。參考先前步驟的輸出時會使用語法 `{{stepName.OutputName}}`。客戶無法在 Runbook 參數使用此語法。在參照步驟執行時，會解決此問題。此參數不列於 Runbook 參數中。  |  <pre>...<br />"mainSteps": [<br />    {<br />      "name": "LaunchInstance",<br />      "action": "aws:runInstances",<br />      "maxAttempts": 1,<br />      "onFailure": "Continue",<br />      "inputs": {<br />        "ImageId": "{{amiId}}",<br />        "MinInstanceCount": 1,<br />        "MaxInstanceCount": 2<br />      }<br />    },<br />    {<br />      "name":"changeState",<br />      "action": "aws:changeInstanceState",<br />      "maxAttempts": 1,<br />      "onFailure": "Continue",<br />      "inputs": {<br />        "InstanceIds": ["{{LaunchInstance.InstanceIds}}"],<br />        "DesiredState": "terminated"<br />      }<br />    }<br /><br />... </pre>  | 

## 不支援的案例
<a name="automation-variables-unsupported"></a>


****  

| 案例 | 註解 | 範例 | 
| --- | --- | --- | 
|  建立時，為 `assumeRole` 提供的 Systems Manager 參數  |  不支援。  |  <pre>...<br /><br />{<br />  "description": "Test all Automation resolvable parameters",<br />  "schemaVersion": "0.3",<br />  "assumeRole": "{{ssm:administratorRoleARN}}",<br />  "parameters": {<br /><br />... </pre>  | 
|  直接在步驟輸入中參考的 Systems Manager 參數。  |  建立時傳回 `InvalidDocumentContent` 例外狀況。  |  <pre><br />...<br />mainSteps:<br />  - name: launchInstance<br />    action: 'aws:runInstances'<br />    maxAttempts: 3<br />    timeoutSeconds: 1200<br />    onFailure: Abort<br />    inputs:<br />      ImageId: '{{ssm:/aws/service/ami-windows-latest/Windows_Server-2016-English-Full-Base}}'<br />...</pre>  | 
|  變數步驟定義  |  Runbook 步驟的定義是由變數建構。  |  <pre>...<br /><br />"mainSteps": [<br />    {<br />      "name": "LaunchInstance",<br />      "action": "aws:runInstances",<br />      "{{attemptModel}}": 1,<br />      "onFailure": "Continue",<br />      "inputs": {<br />        "ImageId": "ami-12345678",<br />        "MinInstanceCount": 1,<br />        "MaxInstanceCount": 2<br />      }<br /><br />...<br /><br />User supplies input : { "attemptModel" : "minAttempts" } </pre>  | 
|  交互參照 Runbook 參數  |  使用者會在開始時間提供輸入參數，而這是 Runbook 中另一個參數的參考。  |  <pre>...<br />"parameters": {<br />    "amiId": {<br />      "type": "String",<br />      "default": "ami-7f2e6015",<br />      "description": "list of commands to run as part of first step"<br />    },<br />    "alternateAmiId": {<br />      "type": "String",<br />      "description": "The alternate AMI to try if this first fails".<br /><br />"default" : "{{amiId}}"<br />    },<br /><br />... </pre>  | 
|  多層級擴展  |  Runbook 會定義一個評估變數名稱的變數。這位於變數分隔符號內 (即 *\$1\$1 \$1\$1*)，且會擴展至該變數/參數的值。  |  <pre>...<br />  "parameters": {<br />    "firstParameter": {<br />      "type": "String",<br />      "default": "param2",<br />      "description": "The parameter to reference"<br />    },<br />    "secondParameter": {<br />      "type": "String",<br />      "default" : "echo {Hello world}",<br />      "description": "What to run"<br />    }<br />  },<br />  "mainSteps": [{<br />      "name": "runFixedCmds",<br />      "action": "aws:runCommand",<br />      "maxAttempts": 1,<br />      "onFailure": "Continue",<br />      "inputs": {<br />        "DocumentName": "AWS-RunPowerShellScript",<br /><br />"InstanceIds" : "{{LaunchInstance.InstanceIds}}",<br />        "Parameters": {<br />          "commands": [ "{{ {{firstParameter}} }}"]<br /><br />}<br /><br />...<br /><br />Note: The customer intention here would be to run a command of "echo {Hello world}" </pre>  | 
|  參考 Runbook 步驟的輸出，其為不同的變數類型  |  使用者參考後續步驟內先前 Runbook 步驟的輸出。輸出為不符合後續步驟中動作需求的變數類型。  |  <pre>...<br />mainSteps:<br />- name: getImageId<br />  action: aws:executeAwsApi<br />  inputs:<br />    Service: ec2<br />    Api: DescribeImages<br />    Filters:  <br />    - Name: "name"<br />      Values: <br />      - "{{ImageName}}"<br />  outputs:<br />  - Name: ImageIdList<br />    Selector: "$.Images"<br />    Type: "StringList"<br />- name: copyMyImages<br />  action: aws:copyImage<br />  maxAttempts: 3<br />  onFailure: Abort<br />  inputs:<br />    SourceImageId: {{getImageId.ImageIdList}}<br />    SourceRegion: ap-northeast-2<br />    ImageName: Encrypted Copies of LAMP base AMI in ap-northeast-2<br />    Encrypted: true <br />... <br />Note: You must provide the type required by the Automation action. <br />In this case, aws:copyImage requires a "String" type variable but the preceding step outputs a "StringList" type variable.<br />                                        </pre>  | 