Including AWS Step Functions definitions in AWS SAM templates
When defining AWS Step Function in AWS Serverless Application Model (SAM), it’s common to have a template like:
# sam.yaml
# ...
MyStepFunctionsStateMachine:
Type: AWS::StepFunctions::StateMachine
Properties:
RoleArn: !GetAtt MyStepFunctionsRole.Arn
DefinitionString: !Sub |-
{
"StartAt": "HelloWorld",
"Comment": "Say hello world",
"States": {
"HelloWorld": {
"Type": "Task",
"Resource": "${HelloWorldFunction.Arn}",
"Comment": "Run the HelloWorld Lambda function",
"End": true
}
}
}
# ...
The JSON provided to DefinitionString inline can easily get long and make it
harder to maintain the CloudFormation template. Thankfully, as described in
this GitHub issue, it’s possible to use the macro AWS::Include
to include an external template file as the definition of Step Functions.
# sam.yaml
# ...
MyStepFunctionsStateMachine:
Type: AWS::StepFunctions::StateMachine
Properties:
RoleArn: !GetAtt MyStepFunctionsRole.Arn
Fn::Transform:
Name: AWS::Include
Parameters:
Location:
Fn::Sub: s3://${BucketName}/state-functions-definition.yaml
# ...
# state-functions-definition.yaml
DefinitionString:
Fn::Sub: |-
{
"StartAt": "HelloWorld",
"Comment": "Say hello world",
"States": {
"HelloWorld": {
"Type": "Task",
"Resource": "${HelloWorldFunction.Arn}",
"Comment": "Run the HelloWorld Lambda function",
"End": true
}
}
}
Please note that the template file state-functions-definition.yaml would have
to be copied to the S3 bucket refered by BucketName in the sam.yaml pior to
creating/updating the CloudFormation stack.