

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

# Systems Manager 自动化操作参考
自动化操作参考

此参考介绍可在自动化运行手册中指定的自动化操作。Automation 是 Amazon Systems Manager 中的一项工具。这些操作不能用于其他类型的 Systems Manager (SSM) 文档。有关其他 SSM 文档类型插件的信息，请参阅 [命令文档插件参考](documents-command-ssm-plugin-reference.md)。

Systems Manager 自动化会运行自动化运行手册中定义的步骤。每个步骤都与特定操作关联。此操作确定本步的输入、行为和输出。在运行手册的 `mainSteps` 部分定义步骤。

您无需指定操作或步骤的输出。由与本步关联的操作预先确定输出。当您在运行手册中指定步骤输入时，可以引用前面某步中的一个或多个输出。例如，您可以使 `aws:runInstances` 的输出可用于后续的 `aws:runCommand` 操作。还可以在运行手册的 `Output` 部分引用前面步骤中的输出。

**重要**  
如果您运行使用 Amazon Identity and Access Management (IAM) 服务角色调用其他服务的自动化工作流程，请注意必须使用权限将该服务角色配置为调用这些服务。该要求适用于所有 Amazon 自动化运行手册（`AWS-*` 运行手册），例如 `AWS-ConfigureS3BucketLogging`、`AWS-CreateDynamoDBBackup` 和 `AWS-RestartEC2Instance` 运行手册等。对于您创建的任何自定义自动化运行手册，如果这些文档使用调用其他服务的操作来调用其他 Amazon Web Services 服务，则此要求同样适用。例如，如果使用 `aws:executeAwsApi`、`aws:createStack` 或 `aws:copyImage` 操作，则您必须配置具有权限的服务角色来调用这些服务。您可以将 IAM 内联策略添加到该角色，从而向其他 Amazon Web Services 服务授予权限。有关更多信息，请参阅 [（可选）添加自动化内联策略或客户管理型策略来调用其他 Amazon Web Services 服务](automation-setup-iam.md#add-inline-policy)。

**Topics**
+ [

## 所有操作共享的属性
](#automation-common)
+ [

# `aws:approve` – 暂停自动化以进行手动批准
](automation-action-approve.md)
+ [

# `aws:assertAwsResourceProperty` - 断言 Amazon 资源状态或事件状态
](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` – 创建亚马逊机器映像
](automation-action-create.md)
+ [

# `aws:createStack` – 创建 Amazon CloudFormation 堆栈。
](automation-action-createstack.md)
+ [

# `aws:createTags` - 为 Amazon 资源创建标签
](automation-action-createtag.md)
+ [

# `aws:deleteImage` – 删除亚马逊机器映像
](automation-action-delete.md)
+ [

# `aws:deleteStack` - 删除 Amazon CloudFormation 堆栈。
](automation-action-deletestack.md)
+ [

# `aws:executeAutomation` - 运行另一个自动化
](automation-action-executeAutomation.md)
+ [

# `aws:executeAwsApi` - 调用并运行 Amazon API 操作
](automation-action-executeAwsApi.md)
+ [

# `aws:executeScript` - 运行脚本
](automation-action-executeScript.md)
+ [

# `aws:executeStateMachine` - 运行 Amazon Step Functions 状态机。
](automation-action-executeStateMachine.md)
+ [

# `aws:invokeWebhook` – 调用 Automation Webhook 集成
](invoke-webhook.md)
+ [

# `aws:invokeLambdaFunction` – 调用 Amazon 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` - 等待 Amazon 资源属性
](automation-action-waitForAwsResourceProperty.md)
+ [

# 自动化系统变量
](automation-variables.md)

## 所有操作共享的属性


通用属性是位于所有操作中的参数或选项。一些选项定义了步骤的行为，例如，等待步骤完成的时间以及在步骤失败时采取的措施。以下属性是所有操作的通用属性。

[description](#descriptProp)  
您提供的描述运行手册或步骤目的的信息。  
类型：字符串  
必需：否

[name](#nameProp)  
在运行手册的所有步骤名称中必须唯一的标识符。  
类型：字符串  
允许的模式：[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)  
将一个步骤指定为成功完成自动化的关键步骤。如果具有此分派的步骤失败，自动化会将自动化的最终状态报告为失败。仅当您在步骤中明确定义此属性时，才会计算该属性。如果 `onFailure` 属性在某个步骤中设定为 `Continue`，则此值默认为 False。否则，该选项的默认值为 True。  
类型：布尔值  
有效值：true \$1 false  
必需：否

[inputs](#inProp)  
特定于操作的属性。  
类型：映射  
必需：是

### 示例


```
---
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` – 暂停自动化以进行手动批准


临时暂停自动化，直至指定委托人批准或拒绝操作。在达到所需批准数后，自动化执行将恢复。您可以将批准步骤插入到运行手册的 `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://console.aws.amazon.com/systems-manager/](https://console.amazonaws.cn/systems-manager/)，打开 Amazon Systems Manager 控制台。

1. 在导航窗格中，选择 **自动化**。

1. 选择状态为**正在等待**的自动化旁边的选项。  
![\[访问批准/拒绝自动化页面\]](http://docs.amazonaws.cn/systems-manager/latest/userguide/images/automation-approve-action-aws.png)

1. 选择**批准/拒绝**。

1. 查看自动化的详细信息。

1. 选择**批准**或**拒绝**，键入评论（可选），然后选择**提交**。

**输入示例**

------
#### [ 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  
用于批准自动化的 Amazon Resource Name (即 ARN，属于 Amazon Simple Notification Service (Amazon SNS)) 的主题。当您在运行手册中指定 `aws:approve` 步骤时，自动化 将向此主题发送消息，以让委托人知道必须批准或拒绝自动化步骤。Amazon SNS 主题的标题必须使用前缀“自动化”。  
类型：字符串  
必需：否

消息  
发送批准请求时要包含在 Amazon SNS 主题中的信息。最大消息长度为 4096 个字符。  
类型：字符串  
必需：否

MinRequiredApprovals  
恢复自动化所需的最小批准数。如果您未指定值，系统将默认为 1。此参数的值必须为正数。此参数的值不能超过 `Approvers` 参数定义的审批者数。  
类型：整数  
必需：否

Approvers  
能够批准或拒绝操作的经 Amazon 身份验证的委托人的列表。最大审批者数量为 10。您可使用以下任意格式指定委托人：  
+ 一个用户名称
+ 用户 ARN
+ IAM 角色 ARN
+ IAM 担任角色 ARN
类型：StringList  
是否必需：是

EnhancedApprovals  
此输入仅用于 Change Manager 模板。能够批准或拒绝操作的经过 Amazon 身份验证的主体、IAM 主体的类型以及最少批准者数量的列表。以下是示例：  

```
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  
步骤的批准状态。状态可以为下列状态之一：已批准、已拒绝或正在等待。“正在等待”意味着自动化正在等待来自审批者的输入。  
类型：字符串

ApproverDecisions  
包括每位审批者的批准决定的 JSON 映射。  
类型：MapList

# `aws:assertAwsResourceProperty` - 断言 Amazon 资源状态或事件状态


`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 操作的 Amazon Web Services 服务命名空间。例如，Systems Manager 的命名空间为 `ssm`。Amazon EC2 的命名空间为 `ec2`。您可以在《Amazon CLI 命令参考》的[可用服务](https://docs.amazonaws.cn/cli/latest/reference/#available-services)部分查看支持的 Amazon Web Services 服务命名空间列表。  
类型：字符串  
是否必需：是

API  
要运行的 API 操作的名称。您可以在以下[服务参考](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html)页面的左侧导航栏中选择服务来查看 API 操作（也称为方法）。在要调用的服务的**客户端**部分中选择一种方法。例如，下面的 [Amazon RDS 方法](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html)页面中列出了 Amazon Relational Database Service (Amazon RDS) 的所有 API 操作（方法）。  
类型：字符串  
是否必需：是

API 操作输入  
一个或多个 API 操作输入。您可以在以下[服务参考](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html)页面的左侧导航栏中选择服务来查看可用的输入（也称为参数）。在要调用的服务的**客户端**部分中选择一种方法。例如，下面的 [Amazon RDS 方法](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html)页面中列出了 Amazon RDS 的所有方法。选择 [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)页面的左侧导航栏中选择服务来查看响应对象。在要调用的服务的**客户端**部分中选择一种方法。例如，下面的 [Amazon RDS 方法](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html)页面中列出了 Amazon RDS 的所有方法：选择 [describe\$1db\$1instances](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html#RDS.Client.describe_db_instances) 方法，然后向下滚动到**响应结构**部分。**DBInstances** 被列为响应对象。  
类型：字符串  
是否必需：是

DesiredValues  
要继续自动化的预期状态。如果指定布尔值，则必须使用大写字母，例如 True 或 False。  
类型：StringList  
是否必需：是

# `aws:branch` – 运行条件自动化步骤


`aws:branch` 操作让您能够创建一个动态自动化，该自动化在一个步骤中评估不同选择，然后根据评估结果跳转到运行手册中的另一个步骤。

在为步骤指定 `aws:branch` 操作时，请指定自动化必须评估的 `Choices`。`Choices` 可以基于您在运行手册的 `Parameters` 部分中指定的值，也可以基于上一步的输出生成的动态值。自动化使用布尔表达式评估每个选择。如果第一个选择为真，则自动化跳转到为此选择指定的步骤。如果第一个选择为假，则自动化评估下一个选择。自动化继续评估每个选择，直到遇到结果为真的选择。然后，自动化跳转到为结果为真的选择指定的步骤。

如果所有选择都为假，则自动化检查该步骤是否包含 `default` 值。默认值定义当所有选择都为假时自动化应跳转到的步骤。如果没有为该步骤指定 `default` 值，则自动化处理运行手册中的下一个步骤。

`aws:branch` 操作通过组合使用 `And`、`Not` 和 `Or` 运算符来支持复杂的选择评估。有关如何使用 `aws:branch` 的更多信息，包括使用不同运算符的示例运行手册和示例，请参阅 [在运行手册中使用条件语句](automation-branch-condition.md)。

**Input**  
在步骤中指定一个或多个 `Choices`。`Choices` 可以基于您在运行手册的 `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
```

Choices  
自动化 在确定下一个要处理的步骤时应评估的一个或多个表达式。通过使用布尔表达式对选择进行评估。每个选择都必须定义以下选项：  
+ **NextStep**：当指定的选择为真时，要处理的运行手册中的下一个步骤。
+ **变量**：指定在运行手册的 `Parameters` 部分中定义的参数名称。或指定来自运行手册中上一步的输出对象。有关为 `aws:branch` 创建变量的更多信息，请参阅 [关于创建输出变量](automation-branch-condition.md#branch-action-output)。
+ **运算**：用于评估选择的标准。`aws:branch` 操作支持以下运算：

**字符串运算**
  + 字符串等于
  + EqualsIgnoreCase
  + StartsWith
  + EndsWith
  + 包含

**数值运算**
  + NumericEquals
  + NumericGreater
  + NumericLesser
  + NumericGreaterOrEquals
  + NumericLesser
  + NumericLesserOrEquals

**布尔运算**
  + BooleanEquals
**重要**  
创建运行手册时，系统将验证运行手册中的每个操作。在尝试创建运行手册时，如果某个操作不受支持，系统会返回错误。

默认  
当所有 `Choices` 都为假时，自动化应跳转到的步骤的名称。  
类型：字符串  
必需：否

**注意**  
`aws:branch` 操作支持 `And`、`Or` 和 `Not` 运算符。有关使用运算符的 `aws:branch` 的示例，请参阅 [在运行手册中使用条件语句](automation-branch-condition.md)。

# `aws:changeInstanceState` – 更改或声明实例状态


更改或断言实例的状态。

此操作可在断言模式下使用（不要运行 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


将 Amazon Machine Image (AMI) 从任何 Amazon Web Services 区域 复制到当前区域中。此操作还可以对新的 AMI 进行加密。

**注意**  
`aws:copyImage` 操作支持自动节流重试。有关更多信息，请参阅 [为节流的操作配置自动重试](automation-throttling-retry.md)。

**Input**  
此操作支持大多数 `CopyImage` 参数。有关更多信息，请参阅 [CopyImage](https://docs.amazonaws.cn/AWSEC2/latest/APIReference/API_CopyImage.html)。

以下示例是在首尔地区创建 AMI 的副本（`SourceImageID`：ami-0fe10819。`SourceRegion`：ap-northeast-2）。新的 AMI 将复制到您启动自动化操作的区域。将对复制的 AMI 进行加密，因为可选 `Encrypted` 标记将设置为 `true`。

------
#### [ 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  
在复制操作期间对映像快照进行加密时要使用的 Amazon KMS key 的完整 Amazon Resource Name (ARN)。有关更多信息，请参阅 [CopyImage](https://docs.amazonaws.cn/AWSEC2/latest/APIReference/api_copyimage.html)。  
类型：字符串  
必需：否

ClientToken  
您为确保请求幂等性而提供的唯一、区分大小写的标识符。有关更多信息，请参阅 [CopyImage](https://docs.amazonaws.cn/AWSEC2/latest/APIReference/api_copyimage.html)。  
类型：字符串  
必需：否Output

ImageId  
已复制映像的 ID。

ImageState  
已复制映像的状态。  
有效值：`available` \$1`pending` \$1`failed`

# `aws:createImage` – 创建亚马逊机器映像


从正在运行、正在停止或已停止的实例创建 Amazon Machine Image（AMI），并轮询 `ImageState` 是否为 `available`。

**注意**  
`aws:createImage` 操作支持自动节流重试。有关更多信息，请参阅 [为节流的操作配置自动重试](automation-throttling-retry.md)。

**Input**  
此操作支持以下 `CreateImage` 参数。有关更多信息，请参阅 [CreateImage](https://docs.amazonaws.cn/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) 会尝试关闭并重新启动实例，然后再创建映像。如果**不重启**选项设置为 `true`，则 Amazon EC2 在创建映像前不会关闭实例。如果使用此选项，则无法保证所创建映像上的文件系统的完整性。  
如果您希望在从实例创建 AMI 映像后，该实例不运行，请先使用 [`aws:changeInstanceState` – 更改或声明实例状态](automation-action-changestate.md) 插件停止实例，然后在 **NoReboot** 选项设置为 `true` 的情况下使用此 `aws:createImage` 操作。  
类型：布尔值  
必需：否

BlockDeviceMappings  
适用于实例的块储存设备。  
类型：映射  
必需：否Output

ImageId  
新建映像的 ID。  
类型：字符串

ImageState  
映像的当前状态。如果状态为可用，则表示映像已成功注册，并且可用于启动实例。  
类型：字符串

# `aws:createStack` – 创建 Amazon CloudFormation 堆栈。


从模板创建 Amazon CloudFormation 堆栈。

**注意**  
`aws:createStack` 操作支持自动节流重试。有关更多信息，请参阅 [为节流的操作配置自动重试](automation-throttling-retry.md)。

有关创建 CloudFormation 堆栈的补充信息，请参阅 *Amazon CloudFormationAPI 参考*中的 [CreateStack](https://docs.amazonaws.cn/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}}"
          }
    }
}
```

------

功能  
必须在 CloudFormatio 可以创建某些堆栈之前指定的值列表。一些堆栈模板中包含的资源会影响您的 Amazon Web Services 账户中的权限。对于这些堆栈，您必须通过指定此参数来明确确认它们的功能。  
有效值包括 `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.amazonaws.cn/AWSCloudFormation/latest/UserGuide/aws-properties-iam-accesskey.html](https://docs.amazonaws.cn/AWSCloudFormation/latest/UserGuide/aws-properties-iam-accesskey.html)
+ [https://docs.amazonaws.cn/AWSCloudFormation/latest/UserGuide/aws-properties-iam-group.html](https://docs.amazonaws.cn/AWSCloudFormation/latest/UserGuide/aws-properties-iam-group.html)
+ [https://docs.amazonaws.cn/AWSCloudFormation/latest/UserGuide/aws-resource-iam-instanceprofile.html](https://docs.amazonaws.cn/AWSCloudFormation/latest/UserGuide/aws-resource-iam-instanceprofile.html)
+ [https://docs.amazonaws.cn/AWSCloudFormation/latest/UserGuide/aws-properties-iam-policy.html](https://docs.amazonaws.cn/AWSCloudFormation/latest/UserGuide/aws-properties-iam-policy.html)
+ [https://docs.amazonaws.cn/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html](https://docs.amazonaws.cn/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html)
+ [https://docs.amazonaws.cn/AWSCloudFormation/latest/UserGuide/aws-properties-iam-user.html](https://docs.amazonaws.cn/AWSCloudFormation/latest/UserGuide/aws-properties-iam-user.html)
+ [https://docs.amazonaws.cn/AWSCloudFormation/latest/UserGuide/aws-properties-iam-addusertogroup.html](https://docs.amazonaws.cn/AWSCloudFormation/latest/UserGuide/aws-properties-iam-addusertogroup.html)
如果您的堆栈模板包含这些资源，我们建议您查看与之关联的所有权限并在必要时编辑其权限。  
有关更多信息，请参阅[确认 Amazon CloudFormation 模板中的 IAM 资源](https://docs.amazonaws.cn/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities)。  
**CAPABILITY\$1AUTO\$1EXPAND**  
某些模板包含宏。宏对模板执行自定义处理，包括查找并替换等简单操作，以及整个模板的大幅转换。因此，用户通常会从已处理的模板创建更改集，这样他们便能在实际创建堆栈之前查看宏导致的更改。如果堆栈模板包含一个或多个宏，并且您选择直接从已处理的模板创建堆栈，而不首先查看更改集中生成的更改，则必须确认此功能。
有关更多信息，请参阅 *Amazon CloudFormation用户指南*中的[使用 Amazon CloudFormation 宏对模板执行自定义处理](https://docs.amazonaws.cn/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` 以关闭堆栈回滚。  
Conditional：您可以指定 `DisableRollback` 参数或 `OnFailure` 参数，但不能同时指定。  
默认值：`false`  
类型：布尔值  
必需：否

NotificationARNs  
用于发布堆栈相关事件的 Amazon Simple Notification Service (Amazon SNS) 主题 ARN。您可以使用 Amazon SNS 控制台 [https://console.aws.amazon.com/sns/v3/home](https://console.amazonaws.cn/sns/v3/home) 查找 SNS 主题 ARN。  
类型：字符串的数组  
数组成员：最多 5 项。  
必需：否

OnFailure  
如果堆栈创建失败，确定要执行的操作。您必须指定 `DO_NOTHING`、`ROLLBACK` 或 `DELETE`。  
Conditional：您可以指定 `OnFailure` 参数或 `DisableRollback` 参数，但不能同时指定。  
默认值：`ROLLBACK`  
类型：字符串  
有效值:` DO_NOTHING | ROLLBACK | DELETE`  
必需：否

参数  
指定堆栈输入参数的 `Parameter` 结构列表。有关更多信息，请参阅[参数](https://docs.amazonaws.cn/AWSCloudFormation/latest/APIReference/API_Parameter.html)数据类型。  
类型：[参数](https://docs.amazonaws.cn/AWSCloudFormation/latest/APIReference/API_Parameter.html)对象数组   
必需：否

ResourceTypes  
您有权用于此创建堆栈操作的模板资源类型。例如，`AWS::EC2::Instance`、`AWS::EC2::*` 或 `Custom::MyCustomInstance`。使用以下语法描述模板资源类型。  
+ 对于所有 Amazon 资源：

  ```
  AWS::*
  ```
+ 对于所有自定义资源：

  ```
  Custom::*
  ```
+ 对于指定自定义资源：

  ```
  Custom::logical_ID
  ```
+ 对于特定 Amazon Web Services 服务的所有资源：

  ```
  AWS::service_name::*
  ```
+ 对于特定的 Amazon 资源：

  ```
  AWS::service_name::resource_logical_ID
  ```
如果资源类型列表不包括您创建的资源，那么堆栈创建将会失败。默认情况下，CloudFormation 授予对所有资源类型的权限。IAM 将此参数用于 IAM policy 中特定于云的条件密钥。有关更多信息，请参阅[使用 Amazon Identity and Access Management 控制访问](https://docs.amazonaws.cn/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.amazonaws.cn/AWSCloudFormation/latest/UserGuide/protect-stack-resources.html)。  
Conditional：您可以指定 `StackPolicyBody` 参数或 `StackPolicyURL` 参数，但不能同时指定。  
类型：字符串  
长度限制：最小长度为 1。长度上限为 16384。  
必需：否

StackPolicyURL  
包含堆栈策略的文件的位置。URL 指向的策略必须位于与堆栈处于同一区域的 S3 存储桶中。堆栈策略允许的最大文件大小为 16 KB。  
Conditional：您可以指定 `StackPolicyBody` 参数或 `StackPolicyURL` 参数，但不能同时指定。  
类型：字符串  
长度限制：最小长度为 1。长度上限为 1350。  
必需：否

Tags  
与此堆栈关联的键值对。CloudFormation 还可以将这些标签传播到堆栈中创建的资源。您可以指定最多 10 个标签。  
类型：[标签](https://docs.amazonaws.cn/AWSCloudFormation/latest/APIReference/API_Tag.html)对象数组   
必需：否

TemplateBody  
包含最小长度为 1 字节、最大长度为 51200 字节的模板正文的结构。有关更多信息，请参阅[模板剖析](https://docs.amazonaws.cn/AWSCloudFormation/latest/UserGuide/template-anatomy.html)。  
Conditional：您可以指定 `TemplateBody` 参数或 `TemplateURL` 参数，但不能同时指定。  
类型：字符串  
长度限制：最小长度为 1。  
必需：否

TemplateURL  
包含模板正文的文件的位置。URL 必须指向一个位于 S3 存储桶中的模板。模板允许的最大大小为 460800 字节。有关更多信息，请参阅[模板剖析](https://docs.amazonaws.cn/AWSCloudFormation/latest/UserGuide/template-anatomy.html)。  
Conditional：您可以指定 `TemplateBody` 参数或 `TemplateURL` 参数，但不能同时指定。  
类型：字符串  
长度限制：最小长度为 1。最大长度为 1024。  
必需：否

TimeoutInMinutes  
堆栈状态变为 `CREATE_FAILED` 前允许经过的时间。如果未设置 `DisableRollback` 或将其设置为 `false`，堆栈将被回滚。  
类型：整数  
有效范围：最小值为 1。  
必需：否

## 输出


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.amazonaws.cn/AWSCloudFormation/latest/APIReference/API_CreateStack.html)。

## 安全注意事项


您必须将以下策略分配给 IAM 自动化担任角色，才可以使用 `aws:createStack` 操作。有关担任角色的更多信息，请参阅 [任务 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` - 为 Amazon 资源创建标签


为 Amazon Elastic Compute Cloud (Amazon EC2) 实例或 Amazon Systems Manager 托管实例创建新标签。

**注意**  
`aws:createTags` 操作支持自动节流重试。有关更多信息，请参阅 [为节流的操作配置自动重试](automation-throttling-retry.md)。

**Input**  
此操作支持大多数 Amazon EC2 `CreateTags` 和 Systems Manager `AddTagsToResource` 参数。有关更多信息，请参阅 [CreateTags](https://docs.amazonaws.cn/AWSEC2/latest/APIReference/api_createtags.html) 和 [AddTagsToResource](https://docs.amazonaws.cn/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”，则此字段只能包含单个项目。  
类型：字符串列表  
是否必需：是

标签  
要与资源关联的标签。  
类型：映射列表  
是否必需：是

ResourceType  
要为其添加标签的资源的类型。如果未提供，则使用默认值“EC2”。  
类型：字符串  
必需：否  
有效值: `EC2` \$1 `ManagedInstance` \$1 `MaintenanceWindow` \$1 `Parameter`

**Output**  
无

# `aws:deleteImage` – 删除亚马逊机器映像


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

**注意**  
`aws:deleteImage` 操作支持自动节流重试。有关更多信息，请参阅 [为节流的操作配置自动重试](automation-throttling-retry.md)。

**Input**  
此操作仅支持一个参数。有关更多信息，请参阅 [DeregisterImage](https://docs.amazonaws.cn/AWSEC2/latest/APIReference/API_DeregisterImage.html) 和 [DeleteSnapshot](https://docs.amazonaws.cn/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` - 删除 Amazon CloudFormation 堆栈。


删除 Amazon 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 用于创建堆栈的 Amazon Identity and Access Management (IAM) 角色的 Amazon Resource Name (ARN)。CloudFormation 使用角色的凭证代表您进行调用。CloudFormation 始终将此角色用于堆栈上的所有未来操作。只要用户有权对堆栈进行操作，CloudFormation 会使用此角色，即使用户无权传递它。确保该角色授予最少的权限。  
如果您不指定值，则 CloudFormation 会使用之前与堆栈关联的角色。如果角色不可用，则 CloudFormation 会使用您的用户凭证生成的一个临时会话。  
类型：字符串  
长度约束：最小长度为 20。最大长度为 2048。  
必需：否

StackName  
与堆栈关联的名称或唯一堆栈 ID。  
类型：字符串  
是否必需：是

## 安全注意事项


您必须将以下策略分配给 IAM 自动化担任角色，才可以使用 `aws:deleteStack` 操作。有关担任角色的更多信息，请参阅 [任务 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` - 运行另一个自动化


通过调用辅助运行手册运行辅助自动化。借助此操作，您可以为最常见的操作创建运行手册，并在自动化过程中引用这些运行手册。因为无需跨类似运行手册复制步骤，此操作可以简化您的运行手册。

辅助自动化将在启动主自动化的用户环境中运行。这意味着第二个自动化将使用与启动第一个自动化的用户相同的 Amazon Identity and Access Management（IAM）角色或用户。

**重要**  
如果您在使用担任角色（使用 iam:passRole 策略的角色）的辅助自动化中指定参数，则启动主要自动化的用户或角色必须具有在辅助自动化中传递指定的担任角色的权限。有关为自动化设置担任角色的更多信息，请参阅 [使用控制台为 Automation 创建服务角色](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  
要在步骤中运行的辅助运行手册的名称。对于相同 Amazon Web Services 账户中的运行手册，指定运行手册名称。对于从其他 Amazon Web Services 账户分享的运行手册，指定运行手册的 Amazon Resource Name (ARN)。有关使用共享运行手册的信息，请参阅 [使用共享 SSM 文档](documents-ssm-sharing.md#using-shared-documents)。  
类型：字符串  
是否必需：是

DocumentVersion  
要运行的辅助运行手册的版本。如果未指定，自动化将运行默认运行手册版本。  
类型：字符串  
必需：否

MaxConcurrency  
此任务可以并行运行的最大目标数。您可以指定一个数字或一个百分比（如 10 或 10%）。  
类型：字符串  
必需：否

MaxErrors  
系统停止在其他目标上运行自动化之前允许的错误数。您可以指定绝对数量的错误（如 10），也可以指定目标集百分比（如 10%）。例如，如果您指定 3，系统将在收到第四个错误时停止运行自动化。如果指定 0，则系统会在返回第一个错误结果后停止在其他资源上运行自动化。如果您在 50 个资源上运行自动化并将 `MaxErrors` 设置为 10%，则系统在收到第六个错误时停止在其他目标上运行自动化。  
当达到 `MaxErrors` 阈值时，允许完成已经运行的自动化，但是其中一些自动化也可能失败。如果您需要确保失败的自动化不会超过指定的 `MaxErrors`，将 `MaxConcurrency` 设置为 1，因此一次进行一个自动化。  
类型：字符串  
必需：否

RuntimeParameters  
辅助运行手册所需的参数。映射使用以下格式：\$1"parameter1" : "value1", "parameter2" : "value2" \$1  
类型：映射  
必需：否

Tags  
分配给资源的可选元数据。您最多可以为自动化指定 5 个标签。  
类型：MapList  
必需：否

TargetLocations  
位置是要在其中运行自动化的 Amazon Web Services 区域 和/或 Amazon Web Services 账户 的组合。必须指定至少 1 个项目，最多可以指定 100 个项目。为此参数指定值时，输出不会返回到父自动化。如果需要，则必须后续调用 API 操作，以检索子自动化的输出。  
类型：MapList  
必需：否

TargetMaps  
运行手册参数到目标资源的键-值映射列表。`Targets` 和 `TargetMaps` 不能一起指定。  
类型：MapList  
必需：否

TargetParameterName  
用作速率控制自动化目标资源的参数的名称。当您指定 `Targets` 时需要  
类型：字符串  
必需：否

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。  
类型：字符串

Status  
辅助自动化的状态。  
类型：字符串

# `aws:executeAwsApi` - 调用并运行 Amazon API 操作


调用并运行 Amazon API 操作。支持大多数 API 操作，但某些 API 操作未经过测试。不支持流式处理 API 操作，例如 [GetObject](https://docs.amazonaws.cn/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 操作的 Amazon Web Services 服务命名空间。您可以在 适用于 Python (Boto3) 的 Amazon SDK 的[可用服务](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html)中查看支持的 Amazon Web Services 服务命名空间列表。可以在**客户端**部分找到此命名空间。例如，Systems Manager 的命名空间为 `ssm`。Amazon Elastic Compute Cloud (Amazon EC2) 的命名空间为 `ec2`。  
类型：字符串  
是否必需：是

API  
要运行的 API 操作的名称。您可以在以下[服务参考](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html)页面的左侧导航栏中选择服务来查看 API 操作（也称为方法）。在要调用的服务的**客户端**部分中选择一种方法。例如，下面的 [Amazon RDS 方法](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html)页面中列出了 Amazon Relational Database Service (Amazon RDS) 的所有 API 操作（方法）。  
类型：字符串  
是否必需：是

API 操作输入  
一个或多个 API 操作输入。您可以在以下[服务参考](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html)页面的左侧导航栏中选择服务来查看可用的输入（也称为参数）。在要调用的服务的**客户端**部分中选择一种方法。例如，下面的 [Amazon RDS 方法](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html)页面中列出了 Amazon RDS 的所有方法。选择 [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)页面的左侧导航栏中选择服务来查看响应对象。在要调用的服务的**客户端**部分中选择一种方法。例如，下面的 [Amazon RDS 方法](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html)页面中列出了 Amazon RDS 的所有方法：选择 [describe\$1db\$1instances](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html#RDS.Client.describe_db_instances) 方法，然后向下滚动到**响应结构**部分。**DBInstances** 被列为响应对象。  
类型：Integer、Boolean、String、StringList、StringMap 或 MapList  
是否必需：是

Type  
响应元素的数据类型。  
类型：可变  
是否必需：是

# `aws:executeScript` - 运行脚本


使用指定的运行时和处理程序提供的 Python 或 PowerShell 脚本。每个 `aws:executeScript` 操作最多可以运行 600 秒（10 分钟）时间。您可以通过指定 `aws:executeScript` 步骤的 `timeoutSeconds` 参数来限制超时。

在函数中使用 return 语句将输出添加到输出有效负载中。有关为您的 `aws:executeScript` 操作定义输出的示例，请参阅[示例 2：脚本化运行手册](automation-authoring-runbooks-scripted-example.md)。您还可以将运行手册中 `aws:executeScript` 操作的输出发送到您指定的 Amazon CloudWatch Logs 日志组。有关更多信息，请参阅 [使用 CloudWatch Logs 记录自动化操作输出](automation-action-logging.md)。

如果想要将 `aws:executeScript` 操作的输出发送到 CloudWatch Logs，或者如果您为 `aws:executeScript` 操作指定的脚本调用 Amazon API 操作，则始终需要 Amazon Identity and Access Management (IAM) 服务角色（或承担角色）运行运行手册。

**注意**  
`aws:executeScript` 操作不支持自动节流重试。如果您的脚本发出的 Amazon API 调用可能会受到节流，则必须在脚本代码中实现自己的重试逻辑。

`aws:executeScript` 操作包含以下预安装的 PowerShell 核心模块。
+ Microsoft.PowerShell.Host
+ Microsoft.PowerShell.Management
+ Microsoft.PowerShell.Security
+ Microsoft.PowerShell.Utility
+ PackageManagement
+ PowerShellGet

要使用未预装的 PowerShell 核心模块，脚本必须安装带有 `-Force` 标志的模块，如以下命令所示。不支持 `AWSPowerShell.NetCore` 模块。用您想要安装的模块替换 *ModuleName*。

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

要在脚本中使用 PowerShell 核心 cmdlet，我们建议您使用 `AWS.Tools` 模块，如以下命令所示。将每个*示例资源占位符*替换为您自己的信息。
+ 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
  ```
+ 通用或独立于服务的 Amazon Tools for Windows PowerShell cmdlet。

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

如果脚本除了使用 PowerShell 核心 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
```

有关安装和导入 `AWS.Tools` 模块以及在运行手册中使用 PowerShell 核心 cmdlet 的示例，请参阅 [自动化运行手册的视觉对象设计体验](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.amazonaws.cn/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
```

Script  
要在自动化期间运行的嵌入式脚本。  
类型：字符串  
必需：否 (Python) \$1 是 (PowerShell)

附件  
可以由操作调用的单独脚本文件或 .zip 文件的名称。指定与您在 `Attachments` 请求参数中指定的文档附件文件的 `Name` 相同的值。有关更多信息，请参阅 *Amazon Systems Manager API 参考*中的[附件](https://docs.amazonaws.cn/systems-manager/latest/APIReference/API_CreateDocument.html#systemsmanager-CreateDocument-request-Attachments)。如果您使用附件提供脚本，还必须在您的运行手册的顶级元素部分中定义一个 `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 表示形式。返回最多 100KB 的数据。如果输出列表，则最多返回 100 个项目。

## 通过 aws:executeScript 使用附件


附件提供了一种强大的方法，可以将复杂的脚本、多个模块和外部依赖项打包并重复用于 `aws:executeScript` 操作。在您需要执行以下操作时，请使用附件：
+ 将多个 Python 模块或 PowerShell 脚本打包在一起。
+ 在多个运行手册中重复使用相同的脚本逻辑。
+ 在脚本中包含外部库或依赖项。
+ 通过分离复杂的脚本逻辑，保持运行手册定义简洁。
+ 在团队或自动化工作流之间共享脚本包。

### 附件结构和打包


您可以附加单个文件或包含多个文件的 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
```

### 创建带附件的运行手册


请按照以下步骤创建带附件的运行手册：

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` 部分以引用附件：

   ```
   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 附件示例


以下示例演示了使用附件和 `aws:executeScript` 操作的不同方法。

### 示例 1：单个文件附件


此示例展示如何使用单个 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：多模块包


此示例演示如何使用包含多个 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 附件故障排除


使用以下指导来解决 `aws:executeScript` 附件的常见问题：

**模块导入错误**  
如果在使用多模块包时收到导入错误：
+ 确保在包含 Python 模块的每个目录中都包含一个空的 `__init__.py` 文件。
+ 验证导入语句是否与 zip 包中的实际文件和目录结构相匹配。
+ 始终使用相对导入（例如 `from .utils import helper`）或绝对导入（例如 `from utils import helper`）。

**未找到附件错误**  
如果自动化未能找到附件：
+ 验证 `Attachment` 参数值是否与 `files` 部分中的键完全匹配。
+ 在 `files` 部分中检查 S3 存储桶路径和文件名是否正确。
+ 确保自动化角色对附件 S3 位置具有 `s3:GetObject` 权限。
+ 验证运行手册中的校验和是否与实际文件校验和匹配。

**处理程序函数错误**  
如果收到与处理程序相关的错误：
+ 对于 Python：在 `Handler` 参数中使用格式 `filename.function_name`（例如 `main.process_data`）。
+ 确保处理程序函数只接受两个参数：`events` 和 `context`。
+ 对于 PowerShell：请勿指定 `Handler` 参数；脚本将直接运行。

**脚本执行失败**  
如果脚本在执行过程中失败：
+ 检查自动化执行历史记录，获取详细的错误消息和堆栈跟踪。
+ 使用 `print()` 语句 (Python) 或 `Write-Information` (PowerShell) 添加调试输出。
+ 验证自动化角色是否已被授予所有必需的 Amazon 权限。
+ 在将脚本逻辑打包为附件之前，请在本地测试脚本逻辑。

**退出代码和错误处理**  
要正确处理错误并返回退出代码：
+ 在 Python 中：使用 `raise Exception("error message")` 指示脚本失败。
+ 在 PowerShell 中：使用 `throw "error message"` 或 `Write-Error` 指示失败。
+ 从函数返回结构化数据以提供详细的成功/失败信息。
+ 使用 try-catch 块优雅地处理异常并提供有意义的错误消息。

# `aws:executeStateMachine` - 运行 Amazon Step Functions 状态机。


运行 Amazon Step Functions 状态机。

**注意**  
`aws:executeStateMachine` 操作支持自动节流重试。有关更多信息，请参阅 [为节流的操作配置自动重试](automation-throttling-retry.md)。

**输入**

此操作支持 Step Functions [StartExecution](https://docs.amazonaws.cn/step-functions/latest/apireference/API_StartExecution.html) API 操作的大多数参数。

**所需的 Amazon 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 输入数据的字符串。  
类型：字符串  
必需：否

**输出**  
此操作预定义了以下输出。

执行 Arn  
执行的 ARN。  
类型：字符串

input  
包含执行的 JSON 输入数据的字符串。长度限制适用于有效负载大小，在 UTF-8 编码中以字节表示。  
类型：字符串

name  
执行的名称。  
类型：字符串

output  
执行的 JSON 输出数据。长度限制适用于有效负载大小，在 UTF-8 编码中以字节表示。  
类型：字符串

startDate  
开始执行的日期。  
类型：字符串

stateMachineArn  
状态机的执行的 ARN。  
类型：字符串

status  
执行的当前状态。  
类型：字符串

停止日期  
如果执行已经结束，则为执行停止的日期。  
类型：字符串

# `aws:invokeWebhook` – 调用 Automation Webhook 集成


调用指定的自动化 Webhook 集成。有关创建 Automation 集成的信息，请参阅 [为 Automation 创建 Webhook 集成](creating-webhook-integrations.md)。

**注意**  
`aws:invokeWebhook` 操作支持自动节流重试。有关更多信息，请参阅 [为节流的操作配置自动重试](automation-throttling-retry.md)。

**注意**  
要使用 `aws:invokeWebhook` 操作，您的用户或服务角色必须允许以下操作：  
ssm:GetParameter
kms:Decrypt
只有当您使用客户托管密钥加密集成的参数时，才需要 Amazon Key Management Service (Amazon 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` – 调用 Amazon Lambda 函数


调用指定的 Amazon Lambda 函数。

**注意**  
每个 `aws:invokeLambdaFunction` 操作最多可以运行 300 秒（5 分钟）。您可以通过指定 `aws:invokeLambdaFunction` 步骤的 `timeoutSeconds` 参数来限制超时。

**注意**  
`aws:invokeLambdaFunction` 操作支持自动节流重试。有关更多信息，请参阅 [为节流的操作配置自动重试](automation-throttling-retry.md)。

**Input**  
此操作支持 Lambda 服务的大多数调用参数。有关更多信息，请参阅[调用](https://docs.amazonaws.cn/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 函数生成的最后 4KB 日志数据，采用 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` 运行手册的部分，演示了如何引用来自 `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` – 迭代自动化中的步骤


此操作在自动化运行手册中的步骤子集上进行迭代。您可以选择 `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  
必需：否

IteratorDataType  
用于指定 `Iterators` 数据类型的可选参数。可将此参数的值与 `Iterators` 输入参数一起提供。如果您没有为此参数和 `Iterators` 指定值，则必须为 `LoopCondition` 参数指定值。  
类型：字符串  
有效值：Boolean \$1 Integer \$1 String \$1 StringMap  
默认：字符串  
必需：否

LoopCondition  
由 `Variable` 和要评估的运算符条件组成。如果您没有为此参数指定值，则必须为 `Iterators` 和 `IteratorDataType` 参数指定值。您可以通过组合使用 `And`、`Not` 和 `Or` 运算符来使用复杂的运算符评估。循环中的步骤完成后会对条件进行评估。如果条件为 `true` 并且尚未达到 `MaxIterations` 值，则循环中的步骤将再次运行。运算符条件如下：  

**字符串运算**
+ 字符串等于
+ EqualsIgnoreCase
+ StartsWith
+ EndsWith
+ 包含

**数值运算**
+ NumericEquals
+ NumericGreater
+ NumericLesser
+ NumericGreaterOrEquals
+ NumericLesser
+ NumericLesserOrEquals

**布尔运算**
+ BooleanEquals
类型：StringMap  
必需：否

MaxIterations  
循环中步骤运行的最大次数。一旦达到为此输入指定的值，即使 `LoopCondition` 仍是 `true`，或者 `Iterators` 参数中仍然存在对象，循环也会停止运行。  
类型：整数  
有效值：1-100  
必需：否

Steps  
要在循环中运行的步骤列表。这些功能类似于嵌套运行手册。在这些步骤中，您可以使用语法 `{{loopStepName.CurrentIteratorValue}}` 访问 `for each` 循环的当前迭代器值。您还可以使用语法 `{{loopStepName.CurrentIteration}}` 访问两种循环类型的当前迭代的整数值。  
类型：步骤列表  
是否必需：是Output

CurrentIteration  
当前循环迭代为整数。迭代值从 1 开始。  
类型：整数

CurrentIteratorValue  
当前迭代器的值为字符串。此输出仅存在于 `for each` 循环中。  
类型：字符串

# `aws:pause` - 暂停自动化


此操作会暂停自动化。暂停后的自动化状态为*正在等待*。要继续自动化，请使用信号类型为 `Resume` 的 [SendAutomationSignal](https://docs.amazonaws.cn/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` - 在托管实例上运行命令


运行指定的命令。

**注意**  
自动化仅支持 Amazon Systems Manager Run Command 操作的一个*output*。一个运行手册可以包括多个 Run Command 操作，但一次仅一个操作支持 output。

**Input**  
此操作支持大多数 send command 参数。有关更多信息，请参阅 [SendCommand](https://docs.amazonaws.cn/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  
如果命令类型文档属于您或 Amazon，请指定文档的名称。如果您使用的是另一个 Amazon Web Services 账户与您共享的文档，指定文档的 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  
必需：否（如果未指定实例 ID 或使用 `{{RESOURCE_ID}}` 虚拟参数，则必须指定 `Targets` 参数。）

Targets  
一组搜索条件，使用您指定的键/值组合来设置实例目标。如果未在调用中提供一个或多个实例 ID，则 `Targets` 为必需。有关如何使用 `Targets` 参数的更多信息，请参阅 [大规模运行命令](send-commands-multiple.md)。  
类型：MapList（列表中 map 的架构必须与对象匹配。） 有关更多信息，请参阅 *Amazon Systems ManagerAPI 参考*中的[目标](https://docs.amazonaws.cn/systems-manager/latest/APIReference/API_Target.html)。  
必需：否（如果未指定 `Targets`，则必须指定实例 ID 或使用 `{{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（映射的架构必须与对象匹配。有关更多信息，请参阅 *Amazon Systems ManagerAPI 参考* 中的 [CloudWatchOutputConfig](https://docs.amazonaws.cn/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  
Amazon Identity and Access Management (IAM) 角色的 ARN。  
类型：字符串  
必需：否

TimeoutSeconds  
等待命令传递到实例上的 Amazon Systems Manager SSM Agent 的时间（单位：秒）。如果在达到指定的值之前，命令未被实例上的 SSM Agent 接收，则命令的状态将更改为 `Delivery Timed Out`。  
类型：整数  
必需：否  
有效值：30-2592000Output

CommandId  
命令的 ID。

Status  
命令的状态。

ResponseCode  
命令的响应代码。如果运行的文档有多个步骤，则不会为此输出返回值。

Output  
命令的输出。如果您使用命令定位一个标记或多个实例，则不会返回 output 值。您可以使用 `GetCommandInvocation` 和 `ListCommandInvocations` API 操作来检索单个实例的输出。

# `aws:runInstances` – 启动 Amazon EC2 实例


启动新的 Amazon Elastic Compute Cloud (Amazon EC2) 实例。

**注意**  
`aws:runInstances` 操作支持自动节流重试。有关更多信息，请参阅 [为节流的操作配置自动重试](automation-throttling-retry.md)。

**Input**  
此操作支持大多数 API 参数。有关更多信息，请参阅 [RunInstances](https://docs.amazonaws.cn/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  
针对实例的 Amazon Identity and Access Management (IAM) 实例配置文件的 Amazon Resource Name (ARN)。  
类型：字符串  
必需：否

IamInstanceProfileName  
实例的 IAM 实例配置文件的名称。  
类型：字符串  
必需：否

ImageId  
Amazon Machine Image (AMI) 的 ID。  
类型：字符串  
是否必需：是

InstanceInitiatedShutdownBehavior  
指示此实例是否在系统关闭时停止或终止。  
类型：字符串  
必需：否

InstanceType  
实例类型。  
如果未提供实例类型值，则使用 m1.小型实例类型。
类型：字符串  
必需：否

KernelId  
内核的 ID。  
类型：字符串  
必需：否

KeyName  
密钥对的名称。  
类型：字符串  
必需：否

MaxInstanceCount  
要启动的实例的最大数量。  
类型：字符串  
必需：否

MetadataOptions  
实例的元数据选项。有关更多信息，请参阅 [InstanceMetadataOptionsRequest](https://docs.amazonaws.cn/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` - 为 Amazon 资源创建标签](automation-action-createtag.md) 操作。  
类型：MapList（有关更多信息，请参阅 [TagSpecification](https://docs.amazonaws.cn/AWSEC2/latest/APIReference/API_TagSpecification.html)。）  
必需：否

UserData  
作为字符串文本值提供的脚本。如果输入文本值，则必须为 Base64 编码。  
类型：字符串  
必需：否Output

InstanceIds  
实例的 ID。

InstanceState  
实例的当前状态。

# `aws:sleep` - 延迟自动化


将自动化延迟指定的时间。此操作使用国际标准化组织 (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 天）。

Duration  
ISO 8601 持续时间。您不能指定负数持续时间。  
类型：字符串  
必需：否

Timestamp  
ISO 8601 时间戳。如果您没有为此参数指定值，那么必须为 `Duration` 参数指定一个值。  
类型：字符串  
必需：否Output

无  


# `aws:updateVariable` – 更新运行手册变量的值


此操作会更新运行手册变量的值。值的数据类型必须与要更新的变量的数据类型相匹配。不支持数据类型转换。`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`  
类型：字符串  
是否必需：是

值  
要分配给变量的新值。值必须与变量的数据类型相匹配。不支持数据类型转换。  
类型：Boolean \$1 Integer \$1 MapList \$1 String \$1 StringList \$1 StringMap  
是否必需：是  
约束：  
+ MapList 最多可以包含 200 个项目。
+ 密钥长度的最小长度可以为 1，最大长度可以为 50。
+ StringList 最少可以为 0 项，最多可以为 50 项。
+ 字符串长度的最小长度可以为 1，最大长度可以为 512。Output

无  


# `aws:waitForAwsResourceProperty` - 等待 Amazon 资源属性


`aws:waitForAwsResourceProperty` 操作可以让自动化等待特定的资源状态或事件状态，然后才继续自动化。有关如何使用此操作的更多示例，请参阅 [其他运行手册示例](automation-document-examples.md)。

**注意**  
此操作的默认超时值为 3600 秒（1 小时）。您可以通过指定 `aws:waitForAwsResourceProperty` 步骤的 `timeoutSeconds` 参数来限制或延长超时。有关如何使用此操作的更多信息和示例，请参阅 [处理运行手册中的超时](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 操作的 Amazon Web Services 服务命名空间。例如，Amazon Systems Manager 的命名空间为 `ssm`。Amazon Elastic Compute Cloud (Amazon EC2) 的命名空间为 `ec2`。您可以在《Amazon CLI 命令参考》的[可用服务](https://docs.amazonaws.cn/cli/latest/reference/#available-services)部分查看支持的 Amazon Web Services 服务命名空间列表。  
类型：字符串  
是否必需：是

API  
要运行的 API 操作的名称。您可以在以下[服务参考](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html)页面的左侧导航栏中选择服务来查看 API 操作（也称为方法）。在要调用的服务的**客户端**部分中选择一种方法。例如，下面的 [Amazon RDS 方法](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html)页面中列出了 Amazon Relational Database Service (Amazon RDS) 的所有 API 操作（方法）。  
类型：字符串  
是否必需：是

API 操作输入  
一个或多个 API 操作输入。您可以在以下[服务参考](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html)页面的左侧导航栏中选择服务来查看可用的输入（也称为参数）。在要调用的服务的**客户端**部分中选择一种方法。例如，下面的 [Amazon RDS 方法](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html)页面中列出了 Amazon RDS 的所有方法。选择 [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)页面的左侧导航栏中选择服务来查看响应对象。在要调用的服务的**客户端**部分中选择一种方法。例如，下面的 [Amazon RDS 方法](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html)页面中列出了 Amazon RDS 的所有方法：选择 [describe\$1db\$1instances](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html#RDS.Client.describe_db_instances) 方法，然后向下滚动到**响应结构**部分。**DBInstances** 被列为响应对象。  
类型：字符串  
是否必需：是

DesiredValues  
要继续自动化的预期状态。  
类型：MapList、StringList  
是否必需：是

# 自动化系统变量


Amazon Systems Manager 自动化运行手册使用以下变量。有关如何使用这些变量的示例，请查看 `AWS-UpdateWindowsAmi` 运行手册的 JSON 源。

**查看 `AWS-UpdateWindowsAmi` 运行手册的 JSON 源**

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

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

1. 在文档列表中，使用“搜索栏”或“搜索栏”右侧的数字选择运行手册 `AWS-UpdateWindowsAmi`。

1. 选择**内容**选项卡。

**系统变量**  
自动化运行手册目前支持以下系统变量。


****  

| Variable | 详细信息 | 
| --- | --- | 
|  `global:ACCOUNT_ID`  |  在其中运行自动化的用户或角色的 Amazon Web Services 账户 ID。  | 
|  `global:DATE`  |  格式为 yyyy-MM-dd 的日期（运行时间）。  | 
|  `global:DATE_TIME`  |  格式为 yyyy-MM-dd\$1HH.mm.ss 的日期和时间（运行时间）。  | 
|  `global:AWS_PARTITION`  |  资源所处的分区。对于标准 Amazon Web Services 区域，分区是 `aws`。对于位于其他分区中的资源，则分区是 `aws-partitionname`。例如，Amazon GovCloud (US-West) 区域中资源的区域为 `aws-us-gov`。  | 
|  `global:REGION`  |  运行手册在其中运行的区域。例如，us-east-2。  | 

**自动化变量**  
自动化运行手册支持以下自动化变量。


****  

| Variable | 详细信息 | 
| --- | --- | 
|  `automation:EXECUTION_ID`  |  分配给当前自动化的唯一标识符。例如，`1a2b3c-1a2b3c-1a2b3c-1a2b3c1a2b3c1a2b3c`。  | 

**Topics**
+ [

## 术语
](#automation-terms)
+ [

## 支持的场景
](#automation-variables-support)
+ [

## 不支持的场景
](#automation-variables-unsupported)

## 术语


以下术语描述了如何解析变量和参数。


****  

| 租期 | 定义 | 示例 | 
| --- | --- | --- | 
|  常量 ARN  |  无变量的有效 Amazon Resource Name (ARN)。  |  `arn:aws:iam::123456789012:role/roleName`  | 
|  运行手册参数  |  在运行手册级别定义的参数（例如 `instanceId`）。可在替换基本字符串时使用该参数。系统会在启动执行时间提供该参数的值。  |  <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>  | 
|  系统变量  |  在评估运行手册的任何部分时，被替换到运行手册中的常规变量。  |  <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>  | 
|  自动化变量  |  在评估运行手册的任何部分时，被替换到运行手册中且与自动化执行相关的变量。  |  <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 参数  |  在 Amazon 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>  | 

## 支持的场景



****  

| 场景 | 注释 | 示例 | 
| --- | --- | --- | 
|  创建时的常量 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` 提供的运行手册参数。  |  必须在运行手册的参数列表中定义。  |  <pre>{<br />  "description": "Test all Automation resolvable parameters",<br />  "schemaVersion": "0.3",<br />  "assumeRole": "{{dynamicARN}}",<br />  "parameters": {<br /> ...</pre>  | 
|  启动时为运行手册参数提供的值。  |  客户提供要用于参数的值。需在运行手册的参数列表中定义在启动时提供的所有输入。  |  <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"] }`  | 
|  在运行手册内容中引用的 Systems Manager 参数。  |  变量存在于客户账户中，或者是公开访问的参数，并且运行手册的 `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>  | 
|  在步骤定义中引用的系统变量  |  启动自动化时被替换到运行手册中的系统变量。注入到运行手册中的值与替换发生的时间相关。换言之，由于在运行步骤之间需要花费一定时间，因此在步骤 1 中注入的时间变量的值将与在步骤 3 中注入的值不同。无需在运行手册的参数列表中设置系统变量。  |  <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>  | 
|  在步骤定义中引用的自动化变量。  |  无需在运行手册的参数列表中设置自动化变量。唯一的受支持自动化变量是 **自动化: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}}` 引用上一步的输出。客户不能将该语法用于运行手册参数。在引用步骤运行时解决此问题。运行手册的参数中未列出该参数。  |  <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>  | 

## 不支持的场景



****  

| 场景 | 注释 | 示例 | 
| --- | --- | --- | 
|  为 `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>  | 
|  变量步骤定义  |  运行手册中步骤的定义由变量构建而成。  |  <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>  | 
|  交叉引用运行手册参数  |  用户在启动时提供了输入参数，而该参数引用了运行手册中的另一参数。  |  <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>  | 
|  多层扩展  |  运行手册定义了评估变量名称的变量。它位于变量分隔符（即 *\$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>  | 
|  引用属于不同变量类型的运行手册步骤的输出  |  用户在后续步骤中引用前面运行手册步骤的输出。输出是一个不符合后续步骤中的操作要求的变量类型。  |  <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>  | 