

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

# 使用 Step Functions 开发工作流程
<a name="developing-workflows"></a>

我们建议在 Step Functions 控制台和工作流程工作室可视化编辑器中开始构建工作流程。可以从空白画布开始，也可以为常见场景选择初学者模板。

构建工作流程需要执行以下任务：
+ 定义工作流程
+ 运行和调试工作流程
+ 部署工作流程

您使用 Amazon States Language 定义状态机。可以手动创建 Amazon States Language 定义，但教程中将采用工作流程工作室。使用工作流程工作室，可以在 Step Functions 控制台中定义机器定义、可视化和编辑步骤、运行和调试工作流程以及查看结果。

**在 Visual Studio Code 中使用 Workflow Studio**  
借助该 AWS 工具包，您可以在 VS Code 中使用 Workflow Studio 来可视化、构建甚至测试状态机中的各个状态。提供状态输入和设置变量，开始测试，然后就可以看到如何转换数据。您可以调整工作流并重新测试。完成后可以应用更改来更新状态机。有关更多信息，请参阅 AWS Toolkit for Visual Studio Code中的 [Working with Workflow Studio](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/stepfunctions-workflowstudio.html)。

您还可以使用 AWS Command Line Interface (AWS CLI) 中的许多 Step Functions 功能。例如，可以创建状态机并列出现有的状态机。您可以使用中的 Step Functions 命令 AWS CLI 来启动和管理执行、轮询活动、记录任务心跳等。有关 Step Functions 命令的完整列表、可用参数的说明以及展示它们使用方法的示例，请参阅 *AWS CLI 命令参考*。[AWS CLI Command Reference](https://docs.aws.amazon.com/cli/latest/reference/)

AWS CLI 命令严格遵循亚马逊州立大学的语言，因此您可以使用 AWS CLI 来了解 Step Functions API 操作。您还可以使用现有 API 知识创建代码原型，或者从命令行执行 Step Functions 操作。

**验证状态机定义**  
在创建工作流程之前，可以使用 API 来**验证**状态机并发现潜在问题。  
要了解有关验证工作流程的更多信息，请参阅 Step Functions API 参考[ValidateStateMachineDefinition](https://docs.aws.amazon.com/step-functions/latest/apireference/API_ValidateStateMachineDefinition.html)中的。

要从最小的设置开始，可以按照[创建 Lambda 状态机](tutorial-creating-lambda-state-machine.md)教程进行操作，该教程向您展示了如何通过调用 Lambda 函数的单个步骤来定义工作流程，然后运行工作流程并查看结果。

## 定义工作流程
<a name="development-define"></a>

开发工作流程的第一步是使用 Amazon States Language 定义步骤。根据您的偏好和工具，可以使用 JSON、YAML 或字符串化的 Amazon States Language（ASL）定义来定义 Step Functions 状态机。

下表按工具显示了基于 ASL 的定义格式支持。


| AWS 工具 | 支持的格式 | 
| --- | --- | 
| Step Functions 控制台 | JSON | 
| HTTPS 服务 API | 字符串化的 ASL | 
| AWS CLI | 字符串化的 ASL | 
| Step Functions Local | 字符串化的 ASL | 
| AWS Toolkit for Visual Studio Code | JSON、YAML | 
| AWS SAM | JSON、YAML | 
| CloudFormation | JSON、YAML、字符串化的 ASL | 

模板的状态机定义中的 YAML 单行注释将不会延续到所创建资源的定义中。如果您需要保留注释，则应使用状态机定义中的 `Comment` 属性。有关信息，请参阅[状态机结构](statemachine-structure.md)。

使用 CloudFormation 和 AWS SAM，您可以将状态机定义上传到 Amazon S3（JSON 或 YAML 格式），并在模板中提供定义的 Amazon S3 位置。有关信息，请参阅 [AWS::StepFunctions::StateMachine S3Location 页面](https://docs.aws.amazon.com//AWSCloudFormation/latest/UserGuide/aws-properties-stepfunctions-statemachine-s3location.html)。

以下示例 CloudFormation 模板展示了如何使用不同的输入格式提供相同的状态机定义。

------
#### [ JSON with Definition ]

```
{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Description": "AWS Step Functions sample template.",
  "Resources": {
    "MyStateMachine": {
      "Type": "AWS::StepFunctions::StateMachine",
      "Properties": {
        "RoleArn": {
          "Fn::GetAtt": [ "StateMachineRole", "Arn" ]
        },
        "TracingConfiguration": {
          "Enabled": true
        },
        "Definition": {
          "StartAt": "HelloWorld",
          "States": {
            "HelloWorld": {
              "Type": "Pass",
              "End": true
            }
          }
        }
      }
    },
    "StateMachineRole": {
      "Type": "AWS::IAM::Role",
      "Properties": {
        "AssumeRolePolicyDocument": {
          "Version": "2012-10-17",		 	 	 
          "Statement": [
            {
              "Action": [
                "sts:AssumeRole"
              ],
              "Effect": "Allow",
              "Principal": {
                "Service": [
                  "states.amazonaws.com"
                ]
              }
            }
          ]
        },
        "ManagedPolicyArns": [],
        "Policies": [
          {
            "PolicyName": "StateMachineRolePolicy",
            "PolicyDocument": {
              "Statement": [
                {
                  "Action": [
                    "lambda:InvokeFunction"
                  ],
                  "Resource": "*",
                  "Effect": "Allow"
                }
              ]
            }
          }
        ]
      }
    }
  },
  "Outputs": {
    "StateMachineArn": {
      "Value": {
        "Ref": "MyStateMachine"
      }
    }
  }
}
```

------
#### [ JSON with DefinitionString ]

```
{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Description": "AWS Step Functions sample template.",
  "Resources": {
    "MyStateMachine": {
      "Type": "AWS::StepFunctions::StateMachine",
      "Properties": {
        "RoleArn": {
          "Fn::GetAtt": [ "StateMachineRole", "Arn" ]
        },
        "TracingConfiguration": {
          "Enabled": true
        },
        "DefinitionString": "{\n  \"StartAt\": \"HelloWorld\",\n  \"States\": {\n    \"HelloWorld\": {\n      \"Type\": \"Pass\",\n      \"End\": true\n    }\n  }\n}"
      }
    },
    "StateMachineRole": {
      "Type": "AWS::IAM::Role",
      "Properties": {
        "AssumeRolePolicyDocument": {
          "Version": "2012-10-17",		 	 	 
          "Statement": [
            {
              "Action": [
                "sts:AssumeRole"
              ],
              "Effect": "Allow",
              "Principal": {
                "Service": [
                  "states.amazonaws.com"
                ]
              }
            }
          ]
        },
        "ManagedPolicyArns": [],
        "Policies": [
          {
            "PolicyName": "StateMachineRolePolicy",
            "PolicyDocument": {
              "Statement": [
                {
                  "Action": [
                    "lambda:InvokeFunction"
                  ],
                  "Resource": "*",
                  "Effect": "Allow"
                }
              ]
            }
          }
        ]
      }
    }
  },
  "Outputs": {
    "StateMachineArn": {
      "Value": {
        "Ref": "MyStateMachine"
      }
    }
  }
}
```

------
#### [ YAML with Definition ]

```
AWSTemplateFormatVersion: 2010-09-09
Description: AWS Step Functions sample template.
Resources:
  MyStateMachine:
    Type: 'AWS::StepFunctions::StateMachine'
    Properties:
      RoleArn: !GetAtt
        - StateMachineRole
        - Arn
      TracingConfiguration:
        Enabled: true
      Definition:
        # This is a YAML comment. This will not be preserved in the state machine resource's definition.
        Comment: This is an ASL comment. This will be preserved in the state machine resource's definition.
        StartAt: HelloWorld
        States:
          HelloWorld:
            Type: Pass
            End: true
  StateMachineRole:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Action:
              - 'sts:AssumeRole'
            Effect: Allow
            Principal:
              Service:
                - states.amazonaws.com
      ManagedPolicyArns: []
      Policies:
        - PolicyName: StateMachineRolePolicy
          PolicyDocument:
            Statement:
              - Action:
                  - 'lambda:InvokeFunction'
                Resource: "*"
                Effect: Allow

Outputs:
  StateMachineArn:
    Value:
      Ref: MyStateMachine
```

------
#### [ YAML with DefinitionString ]

```
AWSTemplateFormatVersion: 2010-09-09
Description: AWS Step Functions sample template.
Resources:
  MyStateMachine:
    Type: 'AWS::StepFunctions::StateMachine'
    Properties:
      RoleArn: !GetAtt
        - StateMachineRole
        - Arn
      TracingConfiguration:
        Enabled: true
      DefinitionString: |
        {
            "StartAt": "HelloWorld",
            "States": {
                "HelloWorld": {
                    "Type": "Pass",
                    "End": true
                }
            }
        }
  StateMachineRole:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Action:
              - 'sts:AssumeRole'
            Effect: Allow
            Principal:
              Service:
                - states.amazonaws.com
      ManagedPolicyArns: []
      Policies:
        - PolicyName: StateMachineRolePolicy
          PolicyDocument:
            Statement:
              - Action:
                  - 'lambda:InvokeFunction'
                Resource: "*"
                Effect: Allow

Outputs:
  StateMachineArn:
    Value:
      Ref: MyStateMachinele
```

------

**使用开发工作流程 AWS SDKs**  
 AWS SDKs 适用于 Java、.NET、Ruby、PHP、Python（Boto 3） JavaScript、Go 和 C\$1\$1 的 Step Functions 支持。它们 SDKs 提供了一种在多种编程语言中使用 Step Functions HTTPS API 操作的便捷方式。您可以利用这些开发工具包库提供的 API 操作开发状态机、活动或状态机启动器。您还可以使用这些库访问可见性操作，以开发您自己的 Step Functions 监控和报告工具。参阅最新版本的参考文档 AWS SDKs 和适用于 [Amazon Web Services 的工具](https://aws.amazon.com/tools/)。

**通过 HTTPS 请求开发工作流程**  
Step Functions 提供可通过 HTTPS 请求访问的服务操作。可以使用这些操作直接与您自己库中的 Step Functions 通信。您可以使用服务 API 操作开发状态机、工作线程或状态机启动器。您还可以通过 API 操作访问可见性操作，以开发您自己的监控和报告工具。有关详细信息，请参阅 [AWS Step Functions API Reference](https://docs.aws.amazon.com/step-functions/latest/apireference/)。

**使用 AWS Step Functions 数据科学 SDK 开发工作流程**  
数据科学家可以使用 SageMaker AI 和 Step Functions 创建处理和发布机器学习模型的工作流程。也可以在 Python 中创建多步骤机器学习工作流程，以便大规模地编排 AWS 基础设施。 AWS Step Functions 数据科学 SDK 提供了一个 Python API，可以创建和调用 Step Functions 工作流程。您可以直接在 Python 和 Jupyter 笔记本中管理和执行这些工作流。欲了解更多信息，请参阅：[Github 上的AWS Step Functions 数据科学项目](https://github.com/aws/aws-step-functions-data-science-sdk-python)[、数据科学 SDK 文档](https://aws-step-functions-data-science-sdk.readthedocs.io/)以及上的 [Jupyter 笔记本](https://docs.aws.amazon.com/sagemaker/latest/dg/howitworks-nbexamples.html)和[SageMaker 人工智能示例](https://github.com/awslabs/amazon-sagemaker-examples/tree/master/step-functions-data-science-sdk)。 GitHub

## 运行和调试工作流程
<a name="development-run-debug"></a>

您可以通过多种方式启动工作流程，包括从控制台、API 调用（例如，来自 Lambda 函数）、Amazon EventBridge 和 S EventBridge cheduler、从另一台 Step Functions 状态机启动工作流程。运行的工作流程可以在运行时连接到第三方服务 AWS SDKs、使用和操作数据。可以通过各种工具来运行和调试执行步骤和流经状态机的数据。以下各节提供了用于运行和调试工作流程的更多资源。

要了解有关启动状态机执行的方法的更多信息，请参阅[在 Step Functions 中启动状态机执行](statemachine-starting.md)。

**选择用于运行工作流程的端点**  
为了减少延迟并将数据存储在符合您要求的位置，Step Functions 提供了不同 AWS 区域的终端节点。Step Functions 中的每个端点都完全独立。一个状态机或活动仅存在于创建它的区域中。在一个区域中创建的任意状态机或活动，不会与在其它区域中创建的状态机或活动共享任何数据或属性。例如，您可以在两个不同区域中注册名为 `STATES-Flows-1` 的状态机。一个区域中的 `STATES-Flows-1` 状态机不会与另一个区域的 `STATES-Flow-1` 状态机共享数据或属性。有关 Step Functions 端点的列表，请参阅《AWS 一般参考》**中的[AWS Step Functions 区域和端点](https://docs.aws.amazon.com/general/latest/gr/step-functions.html)。

**使用 VS Code 进行开发**  
借助该 AWS 工具包，您可以在 VS Code 中使用 Workflow Studio 来可视化、构建甚至测试状态机中的各个状态。您也可以使用 SAM 和 CloudFormation 定义替换。提供状态输入和设置变量，开始测试，然后就可以看到如何转换数据。在“状态定义”选项卡中，您可以调整工作流并重新测试。完成后可以应用更改来更新状态机。有关更多信息，请参阅 AWS Toolkit for Visual Studio Code中的 [Working with Step Functions](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/bulding-stepfunctions.html) 和 [Working with Workflow Studio](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/stepfunctions-workflowstudio.html)。

## 部署工作流程
<a name="development-deploy"></a>

定义和调试工作流程后，可能需要使用“基础设施即代码”框架进行部署。您可以选择使用各种 IaC 选项来部署状态机，包括：、 AWS Serverless Application Model CloudFormation AWS CDK、和 Terraform。

**AWS Serverless Application Model**  
您可以 AWS Serverless Application Model 与 Step Functions 一起使用来构建工作流程和部署所需的基础架构，包括 Lambda 函数 APIs 和事件，以创建无服务器应用程序。您也可以将 AWS SAM CLI 与结合使用 AWS Toolkit for Visual Studio Code ，作为集成体验的一部分。  
有关更多信息，请参阅 [AWS SAM 用于构建 Step Functions 工作流程](concepts-sam-sfn.md)。

**CloudFormation**  
您可以直接在 CloudFormation 模板中使用状态机定义。  
有关更多信息，请参阅 [用于在 St CloudFormation ep Functions 中创建工作流程](tutorial-lambda-state-machine-cloudformation.md)。

**AWS CDK**  
您可以使用构建标准和快速状态机 AWS CDK。  
要构建标准工作流程，请参阅[使用 CDK 创建标准工作流程](tutorial-lambda-state-machine-cdk.md)。  
要构建快速工作流程，请参阅[使用 CDK 创建快速工作流程](tutorial-step-functions-rest-api-integration-cdk.md)。

**Terraform**  
[Terraform](https://www.terraform.io/intro/) by HashiCorp 是一个使用基础设施即代码 (IaC) 构建应用程序的框架。借助 Terraform，您可以创建状态机并使用特征，例如预览基础架构部署和创建可重复使用的模板。Terraform 模板通过将代码分解为多个较小的块来帮助您维护和重用代码。  
有关更多信息，请参阅 [使用 Terraform 在 Step Functions 中部署状态机](terraform-sfn.md)。