

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 在 Step Functions 中使用版本与别名功能管理持续部署
<a name="concepts-cd-aliasing-versioning"></a>

您可以使用 Step Functions 通过状态机*版本* 与*别名* 功能管理工作流的持续部署。*版本* 是您可以运行的状态机快照，带编号且不可变。*别名* 是指向最多两个版本的状态机的指针。

您可以维护状态机的多个版本，并在生产工作流中管理其部署。使用别名，您可以在不同的工作流版本之间路由流量，并逐步将这些工作流部署到生产环境。

此外，您还可以使用版本或别名启动状态机执行。如果您在开始执行状态机时不使用版本或别名，Step Functions 将使用状态机定义的最新版本。

**状态机修订版**  
状态机可以有一个或多个修订版。当您使用 [UpdateStateMachine](https://docs.aws.amazon.com/step-functions/latest/apireference/API_UpdateStateMachine.html)API 操作更新状态机时，它会创建一个新的状态机修订版。*修订版* 是状态机定义和配置的不可变的只读快照。您无法从修订版中开始执行状态机，并且修订版没有 ARN。修订版有一个 `revisionId` 通用唯一标识符 (UUID)。

**Topics**
+ [版本](concepts-state-machine-version.md)
+ [Aliases](concepts-state-machine-alias.md)
+ [版本与别名功能授权](auth-version-alias.md)
+ [将执行与版本或别名关联](execution-alias-version-associate.md)
+ [部署示例](example-alias-version-deployment.md)
+ [版本的逐步部署](version-rolling-deployment.md)

# Step Functions 工作流程中的状态机版本
<a name="concepts-state-machine-version"></a>

*版本* 是状态机的快照，带编号且**不可变**。您可以从该状态机的最新修订版开始发布版本。每个版本都有一个唯一的 Amazon 资源名称（ARN），这是状态机 ARN 和版本号的组合，用冒号（:）分隔。以下示例显示状态机版本 ARN 的格式。

```
arn:partition:states:region:account-id:stateMachine:myStateMachine:1
```

要开始使用状态机版本，必须发布第一个版本。发布版本后，您可以使用版本 ARN 调用 [StartExecution](https://docs.aws.amazon.com/step-functions/latest/apireference/API_StartExecution.html)API 操作。您无法编辑版本，但可以更新状态机并发布新版本。您也可以发布多个状态机版本。

![\[模糊的说明性图表显示了版本如何成为状态机的不可变快照。\]](http://docs.aws.amazon.com/zh_cn/step-functions/latest/dg/images/versioning-concept.png)


发布状态机的新版本时，Step Functions 会为其分配一个版本号。版本号从 1 开始，每个新版本都会单调递增。对于给定的状态机，版本号不会重复使用。如果您删除了状态机的版本 10，然后发布了新版本，Step Functions 会将其发布为版本 11。

状态机的所有版本的以下属性都相同：
+ 状态机的所有版本共享相同的类型[（标准或快速）](choosing-workflow-type.md)。
+ 您无法更改不同版本之间状态机的名称或创建日期。
+ 标签全局适用于状态机。您可以使用[TagResource](https://docs.aws.amazon.com/step-functions/latest/apireference/API_TagResource.html)和 [UntagResource](https://docs.aws.amazon.com/step-functions/latest/apireference/API_UntagResource.html)API 操作管理状态机的标签。

状态机还包含作为每个版本和[revision](concepts-cd-aliasing-versioning.md#statemachinerev)一部分的属性，但这些属性在两个给定版本或修订版之间可能不同。这些属性包括[状态机定义](https://docs.aws.amazon.com/step-functions/latest/apireference/API_UpdateStateMachine.html#StepFunctions-UpdateStateMachine-request-definition)、[IAM 角色](https://docs.aws.amazon.com/step-functions/latest/apireference/API_UpdateStateMachine.html#StepFunctions-UpdateStateMachine-request-roleArn)、[跟踪配置](https://docs.aws.amazon.com/step-functions/latest/apireference/API_UpdateStateMachine.html#StepFunctions-UpdateStateMachine-request-tracingConfiguration)和[日志配置](https://docs.aws.amazon.com/step-functions/latest/apireference/API_UpdateStateMachine.html#StepFunctions-UpdateStateMachine-request-loggingConfiguration)。

## 发布状态机版本（控制台）
<a name="procedure-create-versions"></a>

您最多可以发布 1000 个版本的状态机。要请求提高此软限制，请使用 [AWS 管理控制台](https://docs.aws.amazon.com/servicequotas/latest/userguide/request-quota-increase.html)中的**支持中心**页面。您可以从控制台手动删除未使用的版本，也可以通过调用 [DeleteStateMachineVersion](https://docs.aws.amazon.com/step-functions/latest/apireference/API_DeleteStateMachineVersion.html)API 操作来删除未使用的版本。

**发布状态机版本的操作步骤**

1. 打开 [Step Functions 控制台](https://console.aws.amazon.com/states/home?region=us-east-1#/)，然后选择一个现有的状态机。

1. 在**状态机详细信息**页面上，选择**编辑**。

1. 根据需要编辑状态机定义，然后选择**保存**。

1. 选择**发布版本**。

1. （可选）在出现的对话框的**描述**字段中，输入有关状态机版本的简短描述。

1. 选择**发布**。

**注意**  
发布状态机的新版本时，Step Functions 会为其分配一个版本号。版本号从 1 开始，每个新版本都会单调递增。对于给定的状态机，版本号不会重复使用。如果您删除了状态机的版本 10，然后发布了新版本，Step Functions 会将其发布为版本 11。

## 使用 Step Functions API 操作管理版本
<a name="manage-versions-with-api"></a>

Step Functions 提供了以下 API 操作来发布和管理状态机版本：
+ [PublishStateMachineVersion](https://docs.aws.amazon.com/step-functions/latest/apireference/API_PublishStateMachineVersion.html)— 从状态[revision](concepts-cd-aliasing-versioning.md#statemachinerev)机的当前版本发布一个版本。
+ [UpdateStateMachine](https://docs.aws.amazon.com/step-functions/latest/apireference/API_UpdateStateMachine.html)— 如果您更新状态机并在同一请求`true`中将`publish`参数设置为，则发布新的状态机版本。
+ [CreateStateMachine](https://docs.aws.amazon.com/step-functions/latest/apireference/API_CreateStateMachine.html)— 如果将`publish`参数设置为，则发布状态机的第一个修订版`true`。
+ [ListStateMachineVersions](https://docs.aws.amazon.com/step-functions/latest/apireference/API_ListStateMachineVersions.html)— 列出指定状态机 ARN 的版本。
+ [DescribeStateMachine](https://docs.aws.amazon.com/step-functions/latest/apireference/API_DescribeStateMachine.html)— 返回中指定的版本 ARN 的状态机版本详情。`stateMachineArn`
+ [DeleteStateMachineVersion](https://docs.aws.amazon.com/step-functions/latest/apireference/API_DeleteStateMachineVersion.html)— 删除状态机版本。

要`myStateMachine`使用发布名为的状态机的当前版本中的新版本 AWS Command Line Interface，请使用以下`publish-state-machine-version`命令：

```
aws stepfunctions publish-state-machine-version --state-machine-arn arn:aws:states:region:account-id:stateMachine:myStateMachine
```

该响应返回 `stateMachineVersionArn`。例如，前面的命令返回的响应为 `arn:aws:states:region:account-id:stateMachine:myStateMachine:1`。

**注意**  
发布状态机的新版本时，Step Functions 会为其分配一个版本号。版本号从 1 开始，每个新版本都会单调递增。对于给定的状态机，版本号不会重复使用。如果您删除了状态机的版本 10，然后发布了新版本，Step Functions 会将其发布为版本 11。

## 从控制台运行状态机版本
<a name="procedure-run-version"></a>

要开始使用状态机版本，必须先从当前状态机[revision](concepts-cd-aliasing-versioning.md#statemachinerev)中发布一个版本。要发布版本，请使用 Step Functions 控制台或调用 [PublishStateMachineVersion](https://docs.aws.amazon.com/step-functions/latest/apireference/API_PublishStateMachineVersion.html)API 操作。您还可以使用名为的可选参数来调用 [UpdateStateMachineAlias](https://docs.aws.amazon.com/step-functions/latest/apireference/API_UpdateStateMachineAlias.html)API 操作`publish`来更新状态机并发布其版本。

您可以使用控制台或调用 [StartExecution](https://docs.aws.amazon.com/step-functions/latest/apireference/API_StartExecution.html)API 操作并提供版本 ARN 来开始执行某个版本。您也可以使用[别名](concepts-state-machine-alias.md)开始执行某个版本。别名会根据其[路由配置](concepts-state-machine-alias.md#alias-routing-config)，会将流量路由到特定版本。

如果不使用版本就启动状态机执行，Step Functions 将使用状态机的最新版本进行执行。有关 Step Functions 如何将执行与版本关联的信息，请参阅[将执行与版本或别名关联](execution-alias-version-associate.md)。

**使用一个状态机版本启动执行**

1. 打开 [Step Functions 控制台](https://console.aws.amazon.com/states/home?region=us-east-1#/)，然后选择已为其发布一个或多个版本的现有状态机。要了解如何发布版本，请参阅[发布状态机版本（控制台）](#procedure-create-versions)。

1. 在**状态机详细信息**页面上，选择**版本**选项卡。

1. 在**设置**部分，执行以下操作：

   1. 选择要启动执行的版本。

   1. 选择**启动执行**。

1. （可选）在**启动执行**对话框中，输入执行名称。

1. （可选），输入执行输入，然后选择**启动执行**。

# Step Functions 工作流程中的状态机别名
<a name="concepts-state-machine-alias"></a>

*别名* 是指向同一状态机最多两个版本的指针。您可以为状态机创建多个别名。每个别名都有唯一的 Amazon 资源名称 (ARN)。别名 ARN 是状态机的 ARN 和别名名称的组合，用冒号 (:) 分隔。以下示例显示状态机别名 ARN 的格式。

```
arn:partition:states:region:account-id:stateMachine:myStateMachine:aliasName
```

您可以使用别名在两个状态机版本之一之间[路由流量](#alias-routing-config)。您也可以创建指向单个版本的别名。别名只能指向状态机版本。您不能使用别名指向另一个别名。您也可以更新别名以便指向状态机的其他版本。

![\[该图显示别名将 80% 的请求发送到 v1，而将 20% 的请求发送到 v2。\]](http://docs.aws.amazon.com/zh_cn/step-functions/latest/dg/images/aliases-concept.png)


**Topics**
+ [创建状态机别名（控制台）](#procedure-create-aliases)
+ [使用管理别名 APIs](#manage-aliases-with-api)
+ [别名路由配置](#alias-routing-config)
+ [使用别名运行状态机（控制台）](#procedure-run-exec-with-alias)

## 创建状态机别名（控制台）
<a name="procedure-create-aliases"></a>

您可以使用 Step Functions 控制台或调用 [CreateStateMachineAlias](https://docs.aws.amazon.com/step-functions/latest/apireference/API_CreateStateMachineAlias.html)API 操作为每台状态机创建最多 100 个别名。要请求提高此软限制，请使用 [AWS 管理控制台](https://docs.aws.amazon.com/servicequotas/latest/userguide/request-quota-increase.html)中的**支持中心**页面。从控制台或通过调用 [DeleteStateMachineAlias](https://docs.aws.amazon.com/step-functions/latest/apireference/API_DeleteStateMachineAlias.html)API 操作来删除未使用的别名。

**创建状态机别名的操作步骤**

1. 打开 [Step Functions 控制台](https://console.aws.amazon.com/states/home?region=us-east-1#/)，然后选择一个现有的状态机。

1. 在**状态机详细信息**页面上，选择**别名**选项卡。

1. 选择**创建新别名**。

1. 在**创建别名**页面上，执行以下操作：

   1. 输入**别名名称**。

   1. （可选）输入别名的**描述**。

1. 要在别名上配置路由，请参阅[别名路由配置](#alias-routing-config)。

1. 选择**创建别名**。

## 使用 Step Functions API 操作管理别名
<a name="manage-aliases-with-api"></a>

Step Functions 提供了以下 API 操作，您可以使用这些操作来创建和管理状态机别名或获取有关别名的信息：
+ [CreateStateMachineAlias](https://docs.aws.amazon.com/step-functions/latest/apireference/API_CreateStateMachineAlias.html)— 为状态机创建别名。
+ [DescribeStateMachineAlias](https://docs.aws.amazon.com/step-functions/latest/apireference/API_DescribeStateMachineAlias.html)— 返回有关状态机别名的详细信息。
+ [ListStateMachineAliases](https://docs.aws.amazon.com/step-functions/latest/apireference/API_ListStateMachineAliases.html)— 列出指定状态机 ARN 的别名。
+ [UpdateStateMachineAlias](https://docs.aws.amazon.com/step-functions/latest/apireference/API_UpdateStateMachineAlias.html)— 通过修改现有状态机别名的`description`或来更新其配置`routingConfiguration`。
+ [DeleteStateMachineAlias](https://docs.aws.amazon.com/step-functions/latest/apireference/API_DeleteStateMachineAlias.html)— 删除状态机别名。

要创建`PROD`指向`myStateMachine`使用命名的状态机的版本 1 的别名 AWS Command Line Interface，请使用`create-state-machine-alias`命令。

```
aws stepfunctions create-state-machine-alias --name PROD  --routing-configuration "[{\"stateMachineVersionArn\":\"arn:aws:states:region:account-id:stateMachine:myStateMachine:1\",\"weight\":100}]"
```

## 别名路由配置
<a name="alias-routing-config"></a>

您可以使用别名在状态机的两个版本之间路由执行流量。例如，假设您要启动状态机的一个新版本。通过在别名上配置路由，可以降低部署新版本所涉及的风险。通过配置路由，您可以将大部分流量发送到状态机的早期测试过的版本上。然后，新版本可以接收较小的百分比，直到您可以确认可以安全地推出新版本。

要定义路由配置，请确保已发布别名指向的两个状态机版本。从别名开始执行时，Step Functions 会从路由配置中指定的版本中随机选择要运行的状态机版本。选择的依据是您在别名路由配置中为每个版本分配的流量百分比。



**在别名上配置路由配置的操作步骤**
+ 在**创建别名**页面的**路由配置**下，执行以下操作：

  1. 对于**版本**，选择别名指向的第一个状态机版本。

  1. 选中**在两个版本之间拆分流量**复选框。
**提示**  
要指向单个版本，请取消选中**在两个版本之间拆分流量**复选框。

  1. 对于**版本**，选择别名必须指向的第二个版本。

  1. 在**流量百分比**字段中，指定要路由到每个版本的流量百分比。例如，输入**60** 和 **40** 表示将 60% 的执行流量路由到第一个版本，40% 的流量路由到第二个版本。

     合并流量百分比必须等于 100%。

## 使用别名运行状态机（控制台）
<a name="procedure-run-exec-with-alias"></a>

您可以使用控制台中的别名启动状态机执行，也可以使用别名的 ARN 调用 [StartExecution](https://docs.aws.amazon.com/step-functions/latest/apireference/API_StartExecution.html)API 操作。Step Functions 会运行由别名指定的版本。默认情况下，如果在启动状态机执行时没有指定版本或别名，Step Functions 会使用最新的修订版。

**使用别名启动状态机执行的操作步骤**

1. 打开 [Step Functions 控制台](https://console.aws.amazon.com/states/home?region=us-east-1#/)，然后选择一个已创建别名的现有状态机。有关创建别名的信息，请参阅[创建状态机别名（控制台）](#procedure-create-aliases)。

1. 在**状态机详细信息**页面上，选择**别名**选项卡。

1. 在**别名**部分中，执行以下操作：

   1. 选择要启动执行的别名。

   1. 选择**启动执行**。

1. （可选）在**启动执行**对话框中，输入执行名称。

1. 如果需要，输入执行输入，然后选择**启动执行**。

# Step Functions 工作流程中版本与别名功能的授权
<a name="auth-version-alias"></a>

要使用版本或别名调用 Step Functions API 操作，您需要适当的权限。要授权某个版本或别名调用 API 操作，Step Functions 会使用状态机的 ARN，而不是使用版本 ARN 或别名 ARN。您也可以缩小特定版本或别名的权限范围。有关更多信息，请参阅[缩小权限范围](#auth-scope-permission-version-alias)。

您可以使用以下名为的状态机的 IAM 策略示例`myStateMachine`来调用 [CreateStateMachineAlias](https://docs.aws.amazon.com/step-functions/latest/apireference/API_CreateStateMachineAlias.html)API 操作来创建状态机别名。

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "states:CreateStateMachineAlias",
      "Resource": "arn:aws:states:us-east-1:123456789012:stateMachine:myStateMachine"
    }
  ]
}
```

在设置允许或拒绝访问使用状态机版本或别名的 API 操作权限时，请考虑以下几点：
+ 如果您使用[CreateStateMachine](https://docs.aws.amazon.com/step-functions/latest/apireference/API_CreateStateMachine.html)和 [UpdateStateMachine](https://docs.aws.amazon.com/step-functions/latest/apireference/API_UpdateStateMachine.html)API 操作的`publish`参数来发布新的状态机版本，则还需要具有 [PublishStateMachineVersion](https://docs.aws.amazon.com/step-functions/latest/apireference/API_PublishStateMachineVersion.html)API 操作的`ALLOW`权限。
+ [DeleteStateMachine](https://docs.aws.amazon.com/step-functions/latest/apireference/API_DeleteStateMachine.html)API 操作会删除与状态机关联的所有版本和别名。

## 缩小版本或别名的权限范围
<a name="auth-scope-permission-version-alias"></a>

您可以使用限定符进一步缩小版本或别名所需的授权权限范围。限定符指的是版本号或别名名称。您可以使用限定符来限定状态机。以下示例是使用名为 `PROD` 的别名作为限定符的状态机 ARN。

```
arn:aws:states:region:account-id:stateMachine:myStateMachine:PROD
```

有关合格和不合格的更多信息 ARNs，请参阅[将执行与版本或别名关联](execution-alias-version-associate.md)。

在 IAM 策略的 `Condition` 语句中，使用名为 `states:StateMachineQualifier` 的可选上下文密钥缩小权限范围。例如，以下 IAM 策略适用于名为的状态机，`myStateMachine`拒绝使用别名为 as `PROD` 或版本的 [DescribeStateMachine](https://docs.aws.amazon.com/step-functions/latest/apireference/API_DescribeStateMachine.html)API 操作调用 API 操作`1`。

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Deny",
      "Action": "states:DescribeStateMachine",
      "Resource": "arn:aws:states:us-east-1:123456789012:stateMachine:myStateMachine",
      "Condition": {
        "ForAnyValue:StringEquals": {
          "states:StateMachineQualifier": [
            "PROD",
            "1"
          ]
        }
      }
    }
  ]
}
```

以下列表说明了您可以使用 `StateMachineQualifier` 上下文密钥缩小权限范围的 API 操作。
+ [CreateStateMachineAlias](https://docs.aws.amazon.com/step-functions/latest/apireference/API_CreateStateMachineAlias.html)
+ [DeleteStateMachineAlias](https://docs.aws.amazon.com/step-functions/latest/apireference/API_DeleteStateMachineAlias.html)
+ [DeleteStateMachineVersion](https://docs.aws.amazon.com/step-functions/latest/apireference/API_DeleteStateMachineVersion.html)
+ [DescribeStateMachine](https://docs.aws.amazon.com/step-functions/latest/apireference/API_DescribeStateMachine.html)
+ [DescribeStateMachineAlias](https://docs.aws.amazon.com/step-functions/latest/apireference/API_DescribeStateMachineAlias.html)
+ [ListExecutions](https://docs.aws.amazon.com/step-functions/latest/apireference/API_ListExecutions.html)
+ [ListStateMachineAliases](https://docs.aws.amazon.com/step-functions/latest/apireference/API_ListStateMachineAliases.html)
+ [StartExecution](https://docs.aws.amazon.com/step-functions/latest/apireference/API_StartExecution.html)
+ [StartSyncExecution](https://docs.aws.amazon.com/step-functions/latest/apireference/API_StartSyncExecution.html)
+ [UpdateStateMachineAlias](https://docs.aws.amazon.com/step-functions/latest/apireference/API_UpdateStateMachineAlias.html)

# Step Functions 如何将执行与版本或别名相关联
<a name="execution-alias-version-associate"></a>

Step Functions 会根据用于调用 [StartExecution](https://docs.aws.amazon.com/step-functions/latest/apireference/API_StartExecution.html) API 操作的 Amazon 资源名称 (ARN) 将执行与版本或别名关联起来。Step Functions 在执行开始时进行此操作。

您可以使用限定或非限定的 ARN 来启动状态机。
+ **限定 ARN** – 指状态机 ARN，后缀为版本号或别名。

  以下限定的 ARN 示例指的是名为 `myStateMachine` 的状态机的版本 `3`。

  ```
  arn:aws:states:region:account-id:stateMachine:myStateMachine:3
  ```

  以下限定的 ARN 示例指的是名为 `myStateMachine` 的状态机的 `PROD` 别名。

  ```
  arn:aws:states:region:account-id:stateMachine:myStateMachine:PROD
  ```
+ **非限定 ARN** – 指没有版本号或别名后缀的状态机 ARN。

  ```
  arn:aws:states:region:account-id:stateMachine:myStateMachine
  ```

例如，如果您的限定 ARN 指的是版本 `3`，则 Step Functions 会将执行与该版本相关联。它不会将执行与任何指向版本 `3` 的别名相关联。

如果您的限定 ARN 指的是别名，则 Step Functions 会将执行与该别名以及该别名指向的版本相关联。一次执行只能与一个别名关联。

**注意**  
如果您使用非限定的 ARN 启动执行，即使版本使用相同的状态机[revision](concepts-cd-aliasing-versioning.md#statemachinerev)，Step Functions 也不会将该执行与版本相关联。例如，如果版本 3 使用最新的修订版，但您使用非限定的 ARN 启动执行，则 Step Functions 不会将该执行与版本 3 相关联。

## 查看使用版本或别名启动的执行
<a name="view-version-alias-executions"></a>

Step Functions 提供了以下方式，您可以通过这些方式查看使用版本或别名启动的执行：

### 使用 API 操作
<a name="view-executions-api-actions"></a>

您可以通过调用 [DescribeExecution](https://docs.aws.amazon.com/step-functions/latest/apireference/API_DescribeExecution.html) 和[ListExecutions](https://docs.aws.amazon.com/step-functions/latest/apireference/API_ListExecutions.html) API 操作来查看与版本或别名关联的所有执行。这些 API 操作会返回用于启动执行的版本或别名的 ARN。这些操作还会返回其他详细信息，包括执行的状态和 ARN。

您还可以提供状态机别名 ARN 或版本 ARN，以便列出与特定别名或版本关联的执行。

以下 [ListExecutions](https://docs.aws.amazon.com/step-functions/latest/apireference/API_ListExecutions.html) API 操作的示例响应显示了用于启动名为 *myFirstExecution* 的状态机执行的别名的 ARN。

以下代码段中的*斜体*文本表示特定于资源的信息。

```
{
    "executions": [
        {
            "executionArn": "arn:aws:states:region:account-id:execution:myStateMachine:myFirstExecution",
            "stateMachineArn": "arn:aws:states:region:account-id:stateMachine:myStateMachine",
            "stateMachineAliasArn": "arn:aws:states:region:account-id:stateMachine:myStateMachine:PROD",
            "name": "myFirstExecution",
            "status": "SUCCEEDED",
            "startDate": "2023-04-20T23:07:09.477000+00:00",
            "stopDate": "2023-04-20T23:07:09.732000+00:00"
        }
    ]
}
```

### 使用 Step Functions 控制台
<a name="view-executions-console"></a>

您还可以从 [Step Functions 控制台](https://console.aws.amazon.com/states/home?region=us-east-1#/)中查看由版本或别名启动的执行。以下步骤显示如何查看使用特定版本启动的执行：

1. 打开 [Step Functions 控制台](https://console.aws.amazon.com/states/home?region=us-east-1#/)，然后选择一个已发布[版本](concepts-state-machine-version.md#procedure-create-versions)或创建[别名](concepts-state-machine-alias.md#procedure-create-aliases)的现有状态机。此示例说明如何查看使用特定状态机版本启动的执行。

1. 选择**版本**选项卡，然后从**版本**列表中选择一个版本。
**提示**  
按属性或值框筛选，搜索特定版本。

1. 在*版本详细信息页面*上，您可以看到使用所选版本启动的所有正在进行和过去的状态机执行列表。

下图显示了*版本详细信息* 控制台页面。该页面列出了由名为 `MathAddDemo` 的状态机版本 *4* 启动的执行。此列表还显示由名为 `PROD` 的别名启动的执行。此别名将执行流量路由到版本 *4*。

![\[状态机版本详细信息控制台页面的说明性屏幕截图。\]](http://docs.aws.amazon.com/zh_cn/step-functions/latest/dg/images/view-version-executions.png)


### 使用 CloudWatch 指标
<a name="view-executions-metrics"></a>

对于使用[Qualified ARN](#qualifiedARN) 启动的每个状态机执行，Step Functions 都会发出与当前发出的指标具有相同名称和值的其他指标。这些其他指标包含启动执行时使用的每个版本标识符和别名的维度。利用这些指标，您可以监控版本级别的状态机执行，并确定何时可能需要回滚方案。您也可以根据这些指标[创建 Amazon CloudWatch 警报](procedure-cw-metrics.md#monitoring-using-cloudwatch-console-set-alarm)。

Step Functions 会针对您使用别名或版本启动的执行发出以下指标：
+ `ExecutionTime`
+ `ExecutionsAborted`
+ `ExecutionsFailed`
+ `ExecutionsStarted`
+ `ExecutionsSucceeded`
+ `ExecutionsTimedOut `

如果您使用版本 ARN 启动执行，Step Functions 会发布包含 `StateMachineArn` 的指标以及包含 `StateMachineArn` 和 `Version` 维度的第二个指标。

如果您使用别名 ARN 启动执行，Step Functions 会发出以下指标：
+ 非限定 ARN 和版本的两个指标。
+ 具有 `StateMachineArn` 和 `Alias` 维度的指标。

# 示例：Step Functions 中的版本与别名功能部署
<a name="example-alias-version-deployment"></a>

下面的金丝雀部署技术示例展示了如何使用 AWS Command Line Interface部署新的状态机版本。在此示例中，您创建的别名将 20% 的执行流量路由到新版本。然后将剩余的 80% 路由到早期版本。要部署新的状态机[版本](concepts-state-machine-version.md)并使用[别名](concepts-state-machine-alias.md)转移执行流量，请完成以下步骤：

1. 

**从当前状态机修订版中发布一个版本。**  
使用 AWS CLI 中的 **publish-state-machine-version** 命令，从名为 `myStateMachine:` 的状态机的当前版本中发布一个版本：

   ```
   aws stepfunctions publish-state-machine-version --state-machine-arn arn:aws:states:region:account-id:stateMachine:myStateMachine
   ```

   响应会返回发布版本的 `stateMachineVersionArn`。例如 `arn:aws:states:region:account-id:stateMachine:myStateMachine:1`。

1. 

**创建指向状态机版本的别名。**  
使用 **create-state-machine-alias** 命令创建指向 `myStateMachine` 版本 1 的别名，名为 `PROD`：

   ```
   aws stepfunctions create-state-machine-alias --name PROD --routing-configuration "[{\"stateMachineVersionArn\":\"arn:aws:states:region:account-id:stateMachine:myStateMachine:1\",\"weight\":100}]"
   ```

1. 

**验证由别名启动的执行是否使用正确的已发布版本。**  
通过在 **start-execution** 命令中提供别名 **PROD** 的 ARN 来启动 `myStateMachine` 的新执行：

   ```
   aws stepfunctions start-execution 
     --state-machine-arn arn:aws:states:region:account-id:stateMachineAlias:myStateMachine:PROD
     --input "{}"
   ```

   如果您在[StartExecution](https://docs.aws.amazon.com/step-functions/latest/apireference/API_StartExecution.html)请求中提供了状态机 ARN，则它会使用最新的[revision](concepts-cd-aliasing-versioning.md#statemachinerev)状态机而不是您的别名中指定的版本来开始执行。

1. 

**更新状态机定义并发布新版本。**  
更新 `myStateMachine` 并发布其新版本。为此，请使用 **update-state-machine** 命令的可选 `publish` 参数：

   ```
   aws stepfunctions update-state-machine
       --state-machine-arn arn:aws:states:region:account-id:stateMachine:myStateMachine
       --definition $UPDATED_STATE_MACHINE_DEFINITION
       --publish
   ```

   响应会返回新版本的 `stateMachineVersionArn`。例如 `arn:aws:states:region:account-id:stateMachine:myStateMachine:2`。

1. 

**更新别名以指向两个版本并设置别名的[路由配置](concepts-state-machine-alias.md#alias-routing-config)。**  
使用 **update-state-machine-alias** 命令更新别名 `PROD` 的路由配置。配置别名，使 80% 的执行流量流向版本 1，其余 20% 流向版本 2：

   ```
   aws stepfunctions update-state-machine-alias --state-machine-alias-arn arn:aws:states:region:account-id:stateMachineAlias:myStateMachine:PROD --routing-configuration "[{\"stateMachineVersionArn\":\"arn:aws:states:region:account-id:stateMachine:myStateMachine:1\",\"weight\":80}, {\"stateMachineVersionArn\":\"arn:aws:states:region:account-id:stateMachine:myStateMachine:2\",\"weight\":20}]"
   ```

1. 

**将版本 1 替换为版本 2。**  
在验证新的状态机版本能够正常运行后，您可以部署新的状态机版本。为此，请再次更新别名，将 100% 的执行流量分配给新版本。

   使用 **update-state-machine-alias** 命令设置别名 `PROD` 的路由配置，为版本 2 分配 100% 的流量：

   ```
   aws stepfunctions update-state-machine-alias --state-machine-alias-arn arn:aws:states:region:account-id:stateMachineAlias:myStateMachine:PROD --routing-configuration "[{\"stateMachineVersionArn\":\"arn:aws:states:region:account-id:stateMachine:myStateMachine:2\",\"weight\":100}]"
   ```

**提示**  
要回滚版本 2 的部署，请编辑别名的路由配置，将 100% 的流量转移到新部署的版本。  

```
aws stepfunctions update-state-machine-alias 
  --state-machine-alias-arn arn:aws:states:region:account-id:stateMachineAlias:myStateMachine:PROD 
  --routing-configuration "[{\"stateMachineVersionArn\":\"arn:aws:states:region:account-id:stateMachine:myStateMachine:1\",\"weight\":100}]"
```

您可以使用版本与别名功能来执行其他类型的部署。例如，您可以对状态机的新版本进行*滚动部署*。为此，请在指向新版本的别名的路由配置中，逐渐增加加权百分比。

您也可以使用版本与别名功能来执行*蓝绿部署*。为此，请创建一个名为 `green` 的别名，且该别名运行状态机的当前版本 1。然后，创建另一个名为 `blue` 的别名，运行新版本，例如 `2`。要测试新版本，请向 `blue` 别名发送执行流量。当您确信自己的新版本可以正常运行时，更新 `green` 别名以指向您的新版本。

# 在 Step Functions 中执行状态机版本的逐步部署
<a name="version-rolling-deployment"></a>

滚动部署是一种部署策略，用新版本的应用程序慢慢地替换旧版本的应用程序。要对状态机版本执行滚动部署，可逐渐增加向新版本发送的执行流量。流量大小和增加速度属于一种参数，由用户进行配置。

您可以使用以下选项之一对版本执行滚动部署：
+ [Step Functions 控制台](https://console.aws.amazon.com/states/home?region=us-east-1#/) – 创建指向同一状态机的两个版本的别名。对于此别名，您可以对路由配置进行配置，以便在两个版本之间转移流量。有关使用控制台推出版本的更多信息，请参阅[版本](concepts-state-machine-version.md)和[Aliases](concepts-state-machine-alias.md)。
+ ** AWS CLI 和开发工具包的脚本** – 使用 AWS CLI 或 AWS 开发工具包创建 shell 脚本。有关更多信息，请参阅以下有关使用 AWS CLI CLI 和 AWS 开发工具包的部分。
+ **AWS CloudFormation 模板** – 使用 `[AWS::StepFunctions::StateMachineVersion](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-stepfunctions-statemachine.html)` 和 `[AWS::StepFunctions::StateMachineAlias](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-stepfunctions-statemachine.html)` 资源发布多个状态机版本，并创建指向其中一个或两个版本的别名。

## 使用 AWS CLI 部署新的状态机版本
<a name="version-canary-deploy-cli"></a>

本节中的示例脚本说明了如何使用 AWS CLI 将流量从以前的状态机版本逐渐转移到新的状态机版本。您可以使用此示例脚本，也可以根据需要对其进行更新。

此脚本显示了使用别名部署新状态机版本的金丝雀部署。以下步骤概述了脚本执行的任务：

1. 如果 `publish_revision` 参数设置为 true，则将最新的[revision](concepts-cd-aliasing-versioning.md#statemachinerev)作为状态机的下一个版本发布。如果部署成功，则此版本将成为新的实时版本。

   如果将 `publish_revision` 参数设置为 false，则脚本将部署状态机的上一个已发布版本。

1. 如果别名还不存在，则创建一个别名。如果别名不存在，请将该别名的 100% 流量指向新版本，然后退出脚本。

1. 更新别名的路由配置，将一小部分流量从以前的版本转移到新版本中。您可以使用 `canary_percentage` 参数设置此金丝雀百分比。

1. 默认情况下，每 60 秒监控一次可配置的 CloudWatch 警报。如果其中任何一个警报被触发，请立即回滚部署，将 100% 的流量指向先前的版本。

   在 `alarm_polling_interval` 中以秒为单位定义的每个时间间隔后，继续监控警报。持续监视，直到超过 `canary_interval_seconds` 中定义的时间间隔。

1. 如果在 `canary_interval_seconds` 期间未触发任何警报，则将 100% 的流量转移到新版本。

1. 如果新版本成功部署，则删除任何早于 `history_max` 参数中指定数字的版本。



```
#!/bin/bash
# 
# AWS StepFunctions example showing how to create a canary deployment with a
# State Machine Alias and versions.
# 
# Requirements: AWS CLI installed and credentials configured.
# 
# A canary deployment deploys the new version alongside the old version, while
# routing only a small fraction of the overall traffic to the new version to
# see if there are any errors. Only once the new version has cleared a testing
# period will it start receiving 100% of traffic.
# 
# For a Blue/Green or All at Once style deployment, you can set the
# canary_percentage to 100. The script will immediately shift 100% of traffic
# to the new version, but keep on monitoring the alarms (if any) during the
# canary_interval_seconds time interval. If any alarms raise during this period,
# the script will automatically rollback to the previous version.
# 
# Step Functions allows you to keep a maximum of 1000 versions in version history
# for a state machine. This script has a version history deletion mechanism at
# the end, where it will delete any versions older than the limit specified.
# 
# For an example that also demonstrates linear (or rolling) deployments, see the following: 
# https://github.com/aws-samples/aws-stepfunctions-examples/blob/main/gradual-deploy/sfndeploy.py

set -euo pipefail

# ******************************************************************************
# you can safely change the variables in this block to your values
state_machine_name="my-state-machine"
alias_name="alias-1"
region="us-east-1"

# array of cloudwatch alarms to poll during the test period.
# to disable alarm checking, set alarm_names=()
alarm_names=("alarm1" "alarm name with a space")

# true to publish the current revision as the next version before deploy.
# false to deploy the latest version from the state machine's version history.
publish_revision=true

# true to force routing configuration update even if the current routing
# for the alias does not have a 100% routing config.
# false will abandon deploy attempt if current routing config not 100% to a
# single version.
# Be careful when you combine this flag with publish_revision - if you just
# rerun the script you might deploy the newly published revision from the
# previous run.
force=false

# percentage of traffic to route to the new version during the test period
canary_percentage=10

# how many seconds the canary deployment lasts before full deploy to 100%
canary_interval_seconds=300

# how often to poll the alarms
alarm_polling_interval=60

# how many versions to keep in history. delete versions prior to this.
# set to 0 to disable old version history deletion.
history_max=0
# ******************************************************************************

#######################################
# Update alias routing configuration.
# 
# If you don't specify version 2 details, will only create 1 routing entry. In
# this case the routing entry weight must be 100.
# 
# Globals:
#   alias_arn
# Arguments:
#   1. version 1 arn
#   2. version 1 weight
#   3. version 2 arn (optional)
#   4. version 2 weight (optional)
#######################################
function update_routing() {
  if [[ $# -eq 2 ]]; then
    local routing_config="[{\"stateMachineVersionArn\": \"$1\", \"weight\":$2}]"
  elif [[ $# -eq 4 ]]; then
    local routing_config="[{\"stateMachineVersionArn\": \"$1\", \"weight\":$2}, {\"stateMachineVersionArn\": \"$3\", \"weight\":$4}]"
  else
    echo "You have to call update_routing with either 2 or 4 input arguments." >&2
    exit 1
  fi
  
  ${aws} update-state-machine-alias --state-machine-alias-arn ${alias_arn} --routing-configuration "${routing_config}"
}

# ******************************************************************************
# pre-run validation
if [[ (("${#alarm_names[@]}" -gt 0)) ]]; then
  alarm_exists_count=$(aws cloudwatch describe-alarms --alarm-names "${alarm_names[@]}" --alarm-types "CompositeAlarm" "MetricAlarm" --query "length([MetricAlarms, CompositeAlarms][])" --output text)

  if [[ (("${#alarm_names[@]}" -ne "${alarm_exists_count}")) ]]; then
    echo All of the alarms to monitor do not exist in CloudWatch: $(IFS=,; echo "${alarm_names[*]}") >&2
    echo Only the following alarm names exist in CloudWatch:
    aws cloudwatch describe-alarms --alarm-names "${alarm_names[@]}" --alarm-types "CompositeAlarm" "MetricAlarm" --query "join(', ', [MetricAlarms, CompositeAlarms][].AlarmName)" --output text
    exit 1
  fi
fi

if [[ (("${history_max}" -gt 0)) && (("${history_max}" -lt 2)) ]]; then
  echo The minimum value for history_max is 2. This is the minimum number of older state machine versions to be able to rollback in the future. >&2
  exit 1
fi
# ******************************************************************************
# main block follows

account_id=$(aws sts get-caller-identity --query Account --output text)

sm_arn="arn:aws:states:${region}:${account_id}:stateMachine:${state_machine_name}"

# the aws command we'll be invoking a lot throughout.
aws="aws stepfunctions"

# promote the latest revision to the next version
if [[ "${publish_revision}" = true ]]; then
  new_version=$(${aws} publish-state-machine-version --state-machine-arn=$sm_arn --query stateMachineVersionArn --output text)
  echo Published the current revision of state machine as the next version with arn: ${new_version}
else
  new_version=$(${aws} list-state-machine-versions --state-machine-arn ${sm_arn} --max-results 1 --query "stateMachineVersions[0].stateMachineVersionArn" --output text)
  echo "Since publish_revision is false, using the latest version from the state machine's version history: ${new_version}"
fi

# find the alias if it exists
alias_arn_expected="${sm_arn}:${alias_name}"
alias_arn=$(${aws} list-state-machine-aliases --state-machine-arn ${sm_arn} --query "stateMachineAliases[?stateMachineAliasArn==\`${alias_arn_expected}\`].stateMachineAliasArn" --output text)

if [[ "${alias_arn_expected}" == "${alias_arn}" ]]; then
  echo Found alias ${alias_arn}

  echo Current routing configuration is:
  ${aws} describe-state-machine-alias --state-machine-alias-arn "${alias_arn}" --query routingConfiguration
else
  echo Alias does not exist. Creating alias ${alias_arn_expected} and routing 100% traffic to new version ${new_version}
  
  ${aws} create-state-machine-alias --name "${alias_name}" --routing-configuration "[{\"stateMachineVersionArn\": \"${new_version}\", \"weight\":100}]"

  echo Done!
  exit 0
fi

# find the version to which the alias currently points (the current live version)
old_version=$(${aws} describe-state-machine-alias --state-machine-alias-arn $alias_arn --query "routingConfiguration[?weight==\`100\`].stateMachineVersionArn" --output text)

if [[ -z "${old_version}" ]]; then
  if [[ "${force}" = true ]]; then
    echo Force setting is true. Will force update to routing config for alias to point 100% to new version.
    update_routing "${new_version}" 100
    
    echo Alias ${alias_arn} now pointing 100% to ${new_version}.
    echo Done!
    exit 0
  else
    echo Alias ${alias_arn} does not have a routing config entry with 100% of the traffic. This means there might be a deploy in progress, so not starting another deploy at this time. >&2
    exit 1
  fi
fi

if [[ "${old_version}" == "${new_version}" ]]; then
  echo The alias already points to this version. No update necessary.
  exit 0
fi

echo Switching ${canary_percentage}% to new version ${new_version}
(( old_weight = 100 - ${canary_percentage} ))
update_routing "${new_version}" ${canary_percentage} "${old_version}" ${old_weight}

echo New version receiving ${canary_percentage}% of traffic.
echo Old version ${old_version} is still receiving ${old_weight}%.

if [[ ${#alarm_names[@]} -eq 0 ]]; then
  echo No alarm_names set. Skipping cloudwatch monitoring.
  echo Will sleep for ${canary_interval_seconds} seconds before routing 100% to new version.
  sleep ${canary_interval_seconds}
  echo Canary period complete. Switching 100% of traffic to new version...
else
  echo Checking if alarms fire for the next ${canary_interval_seconds} seconds.

  (( total_wait = canary_interval_seconds + $(date +%s) ))

  now=$(date +%s)
  while [[ ((${now} -lt ${total_wait})) ]]; do
    alarm_result=$(aws cloudwatch describe-alarms --alarm-names "${alarm_names[@]}" --state-value ALARM --alarm-types "CompositeAlarm" "MetricAlarm" --query "join(', ', [MetricAlarms, CompositeAlarms][].AlarmName)" --output text)

    if [[ ! -z "${alarm_result}" ]]; then
      echo The following alarms are in ALARM state: ${alarm_result}. Rolling back deploy. >&2
      update_routing "${old_version}" 100

      echo Rolled back to ${old_version}
      exit 1
    fi
  
    echo Monitoring alarms...no alarms have triggered.
    sleep ${alarm_polling_interval}
    now=$(date +%s)
  done

  echo No alarms detected during canary period. Switching 100% of traffic to new version...
fi

update_routing "${new_version}" 100

echo Version ${new_version} is now receiving 100% of traffic.

if [[ (("${history_max}" -eq 0 ))]]; then
  echo Version History deletion is disabled. Remember to prune your history, the default limit is 1000 versions.
  echo Done!
  exit 0
fi

echo Keep the last ${history_max} versions. Deleting any versions older than that...

# the results are sorted in descending order of the version creation time
version_history=$(${aws} list-state-machine-versions --state-machine-arn ${sm_arn} --max-results 1000 --query "join(\`\"\\n\"\`, stateMachineVersions[].stateMachineVersionArn)" --output text)

counter=0

while read line; do
  ((counter=${counter} + 1))

  if [[ (( ${counter} -gt ${history_max})) ]]; then
    echo Deleting old version ${line}
    ${aws} delete-state-machine-version --state-machine-version-arn ${line}
  fi
done <<< "${version_history}"

echo Done!
```

## 使用 AWS 开发工具包部署新的状态机版本
<a name="version-deploy-sdk"></a>

[aws-stepfunctions-examples](https://github.com/aws-samples/aws-stepfunctions-examples/tree/main/gradual-deploy) 中的示例脚本展示了如何使用适用于 Python 的 AWS 开发工具包将流量从状态机的旧版本逐步转移到新版本。您可以使用此示例脚本，也可以根据需要对其进行更新。

该脚本展示了以下部署策略：
+ **金丝雀** – 流量将通过两次递增进行转移。

  在第一次递增中，将一小部分流量（例如，10％）转移到新版本。在第二次递增中，在指定的时间间隔（以秒为单位）结束之前，将剩余的流量转移到新版本。只有在指定的时间间隔内未触发 CloudWatch 警报时，才会将剩余流量切换到新版本。
+  **线性或滚动** – 以相等的增量将流量转移到新版本中，每个增量之间的间隔秒数相等。

  例如，如果您将增量百分比指定为 **20**，`--interval` 为 **600** 秒，则此部署将每 600 秒增加 20% 的流量，直到新版本接收 100% 的流量。

  如果触发了任何 CloudWatch 警报，此部署会立即回滚新版本。
+ **一次部署全部或蓝/绿** – 立即将 100% 的流量转移到新版本。此部署会监控新版本，并在触发任何 CloudWatch 警报时自动将其回滚到先前版本。

## 使用 AWS CloudFormation 部署新的状态机版本
<a name="version-deploy-cfn"></a>

以下 CloudFormation 模板示例发布了名为 `MyStateMachine` 的状态机的两个版本。它会创建一个名为 `PROD` 的别名，该别名指向这两个版本，然后部署了版本 `2`。

在此示例中，每五分钟将 10% 的流量转移到版本 `2`，直到该版本接收 100% 的流量。此示例还介绍了如何设置 CloudWatch 警报。如果您设置的任何警报进入 `ALARM` 状态，则部署将失败并立即回滚。

```
MyStateMachine:
  Type: AWS::StepFunctions::StateMachine
  Properties:
    Type: STANDARD
    StateMachineName: MyStateMachine
    RoleArn: arn:aws:iam::account-id:role/myIamRole
    Definition:
      StartAt: PassState
      States:
        PassState:
          Type: Pass
          Result: Result
          End: true

MyStateMachineVersionA:
  Type: AWS::StepFunctions::StateMachineVersion
  Properties:
    Description: Version 1
    StateMachineArn: !Ref MyStateMachine

MyStateMachineVersionB:
  Type: AWS::StepFunctions::StateMachineVersion
  Properties:
    Description: Version 2
    StateMachineArn: !Ref MyStateMachine

PROD:
  Type: AWS::StepFunctions::StateMachineAlias
  Properties:
    Name: PROD
    Description: The PROD state machine alias taking production traffic.
    DeploymentPreference:
      StateMachineVersionArn: !Ref MyStateMachineVersionB
      Type: LINEAR
      Percentage: 10
      Interval: 5
      Alarms:
        # A list of alarms that you want to monitor. If any of these alarms trigger, rollback the deployment immediately by pointing 100 percent of traffic to the previous version.
        - !Ref CloudWatchAlarm1
        - !Ref CloudWatchAlarm2
```