Using Amazon SAM to build Step Functions workflows
You can use Amazon Serverless Application Model with Step Functions to build workflows and deploy the infrastructure you need, including Lambda functions, APIs and events, to create serverless applications.
You can also use the Amazon Serverless Application Model CLI in conjunction with the Amazon Toolkit for Visual Studio Code as part of an integrated experience to build and deploy Amazon Step Functions state machines. You can build a serverless application with Amazon SAM, then build out your state machine in the VS Code IDE. Then you can validate, package, and deploy your resources.
Tip
To deploy a sample serverless application that starts a Step Functions workflow using Amazon SAM to your Amazon Web Services account, see Module 11 - Deploy with Amazon SAM
Why use Step Functions with Amazon SAM?
When you use Step Functions with Amazon SAM you can:
-
Get started using a Amazon SAM sample template.
-
Build your state machine into your serverless application.
-
Use variable substitution to substitute ARNs into your state machine at the time of deployment.
Amazon CloudFormation supports
DefinitionSubstitutions
that let you add dynamic references in your workflow definition to a value that you provide in your CloudFormation template. You can add dynamic references by adding substitutions to your workflow definition using the${dollar_sign_brace}
notation. You also need to define these dynamic references in theDefinitionSubstitutions
property for the StateMachine resource in your CloudFormation template. These substitutions are replaced with actual values during the CloudFormation stack creation process. For more information, see DefinitionSubstitutions in Amazon SAM templates. -
Specify your state machine's role using Amazon SAM policy templates.
-
Initiate state machine executions with API Gateway, EventBridge events, or on a schedule within your Amazon SAM template.
Step Functions integration with the Amazon SAM specification
You can use the Amazon SAM Policy Templates to add permissions to your state machine. With these permissions, you can orchestrate Lambda functions and other Amazon resources to form complex and robust workflows.
Step Functions integration with the SAM CLI
Step Functions is integrated with the Amazon SAM CLI. Use this to quickly develop a state machine into your serverless application.
Try the Create a Step Functions state machine using Amazon SAM tutorial to learn how to use Amazon SAM to create state machines.
Supported Amazon SAM CLI functions include:
CLI Command | Description |
---|---|
sam init |
Initializes a Serverless Application with an Amazon SAM template. Can be used with a SAM template for Step Functions. |
sam validate | Validates an Amazon SAM template. |
sam package |
Packages an Amazon SAM application. It creates a ZIP file of your code and dependencies, and then uploads it to Amazon S3. It then returns a copy of your Amazon SAM template, replacing references to local artifacts with the Amazon S3 location where the command uploaded the artifacts. |
sam deploy | Deploys an Amazon SAM application. |
sam publish |
Publish an Amazon SAM application to the Amazon Serverless Application Repository. This command takes a packaged Amazon SAM template and publishes the application to the specified region. |
Note
When using Amazon SAM local, you can emulate Lambda and API Gateway locally. However, you can't emulate Step Functions locally using Amazon SAM.
DefinitionSubstitutions in Amazon SAM templates
You can define state machines using CloudFormation templates with Amazon SAM. Using Amazon SAM, you can define the state machine inline in the template or in a separate file. The following Amazon SAM template includes a state machine that simulates a stock trading workflow. This state machine invokes three Lambda functions to check the price of a stock and determine whether to buy or sell the stock. This transaction is then recorded in an Amazon DynamoDB table. The ARNs for the Lambda functions and DynamoDB table in the following template are specified using DefinitionSubstitutions
.
AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Description: | step-functions-stock-trader Sample SAM Template for step-functions-stock-trader Resources: StockTradingStateMachine: Type: AWS::Serverless::StateMachine Properties: DefinitionSubstitutions: StockCheckerFunctionArn: !GetAtt StockCheckerFunction.Arn StockSellerFunctionArn: !GetAtt StockSellerFunction.Arn StockBuyerFunctionArn: !GetAtt StockBuyerFunction.Arn DDBPutItem: !Sub arn:${AWS::Partition}:states:::dynamodb:putItem DDBTable: !Ref TransactionTable Policies: - DynamoDBWritePolicy: TableName: !Ref TransactionTable - LambdaInvokePolicy: FunctionName: !Ref StockCheckerFunction - LambdaInvokePolicy: FunctionName: !Ref StockBuyerFunction - LambdaInvokePolicy: FunctionName: !Ref StockSellerFunction DefinitionUri: statemachine/stock_trader.asl.json StockCheckerFunction: Type: AWS::Serverless::Function Properties: CodeUri: functions/stock-checker/ Handler: app.lambdaHandler Runtime: nodejs18.x Architectures: - x86_64 StockSellerFunction: Type: AWS::Serverless::Function Properties: CodeUri: functions/stock-seller/ Handler: app.lambdaHandler Runtime: nodejs18.x Architectures: - x86_64 StockBuyerFunction: Type: AWS::Serverless::Function Properties: CodeUri: functions/stock-buyer/ Handler: app.lambdaHandler Runtime: nodejs18.x Architectures: - x86_64 TransactionTable: Type: AWS::DynamoDB::Table Properties: AttributeDefinitions: - AttributeName: id AttributeType: S
The following code is the state machine definition in the file stock_trader.asl.json
which is used in the Create a Step Functions state machine using
Amazon SAM tutorial.This state machine definition contains several DefinitionSubstitutions
denoted by the ${dollar_sign_brace}
notation. For example, instead of specifying a static Lambda function ARN for the Check Stock Value
task, the substitution ${StockCheckerFunctionArn}
is used. This substitution is defined in the DefinitionSubstitutions property of the template. DefinitionSubstitutions
is a map of key-value pairs for the state machine resource. In DefinitionSubstitutions
, ${StockCheckerFunctionArn} maps to the ARN of the StockCheckerFunction
resource using the CloudFormation intrinsic function !GetAtt
. When you deploy the Amazon SAM template, the DefinitionSubstitutions
in the template are replaced with the actual values.
{ "Comment": "A state machine that does mock stock trading.", "StartAt": "Check Stock Value", "States": { "Check Stock Value": { "Type": "Task", "Resource": "arn:aws-cn:states:::lambda:invoke", "OutputPath": "$.Payload", "Parameters": { "Payload.$": "$", "FunctionName": "${StockCheckerFunctionArn}" }, "Next": "Buy or Sell?" }, "Buy or Sell?": { "Type": "Choice", "Choices": [ { "Variable": "$.stock_price", "NumericLessThanEquals": 50, "Next": "Buy Stock" } ], "Default": "Sell Stock" }, "Buy Stock": { "Type": "Task", "Resource": "arn:aws-cn:states:::lambda:invoke", "OutputPath": "$.Payload", "Parameters": { "Payload.$": "$", "FunctionName": "${StockBuyerFunctionArn}" }, "Retry": [ { "ErrorEquals": [ "Lambda.ServiceException", "Lambda.AWSLambdaException", "Lambda.SdkClientException", "Lambda.TooManyRequestsException" ], "IntervalSeconds": 1, "MaxAttempts": 3, "BackoffRate": 2 } ], "Next": "Record Transaction" }, "Sell Stock": { "Type": "Task", "Resource": "arn:aws-cn:states:::lambda:invoke", "OutputPath": "$.Payload", "Parameters": { "Payload.$": "$", "FunctionName": "${StockSellerFunctionArn}" }, "Next": "Record Transaction" }, "Record Transaction": { "Type": "Task", "Resource": "arn:aws-cn:states:::dynamodb:putItem", "Parameters": { "TableName": "${DDBTable}", "Item": { "Id": { "S.$": "$.id" }, "Type": { "S.$": "$.type" }, "Price": { "N.$": "$.price" }, "Quantity": { "N.$": "$.qty" }, "Timestamp": { "S.$": "$.timestamp" } } }, "End": true } } }
Next steps
You can learn more about using Step Functions with Amazon SAM with the following resources:
-
Complete the Create a Step Functions state machine using Amazon SAM tutorial to create a state machine with Amazon SAM.
-
Specify a AWS::Serverless::StateMachine resource.
-
Find Amazon SAM Policy Templates to use.
-
Use Amazon Toolkit for Visual Studio Code with Step Functions.
-
Review the Amazon SAM CLI reference to learn more about the features available in Amazon SAM.
You can also design and build your workflows in infrastructure as code (IaC) using visual builders, such as Workflow Studio in Infrastructure Composer. For more information, see Using Workflow Studio in Infrastructure Composer to build Step Functions workflows.