In Gen 2, you can use CDK to create a Step Function in amplify/backend.ts.
First import:
import * as sfn from 'aws-cdk-lib/aws-stepfunctions'
import * as tasks from 'aws-cdk-lib/aws-stepfunctions-tasks'
You can create a state machine in four steps:
Step 1: Define one or more task states. Each task is a single unit of work for the state machine to perform.
Let say you want to create a task state for invoking a Lambda function:
const function1Task = new tasks.LambdaInvoke(stack, 'Function1', {
lambdaFunction: task1LambdaFunction,
outputPath: '$.Payload.body',
})
task1LambdaFunction is defined using the defineFunction() in the resource.ts.
If you need the state machine's flow such as Succeed, Fail, etc., you can use new sfn.Succeed(), new sfn.Fail().
More in the CDK doc: https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_stepfunctions-readme.html
// Succeed state
const jobCompleted = new sfn.Succeed(stack, 'JobCompleted', {
comment: 'Task1 job completed',
})
Step 2: Chain these task states together in a definitionBody.
// Step function definition
const definition = function1Task.next(function2Task)
.next(otherServiceTask)
)
In the above definition, the state machine will perform function1Task, then function2Task, and lastly otherServiceTask.
Step 3: Create a StateMachine instance.
// Create a new state machine
const sm = new sfn.StateMachine(stack, 'MyStateMachine', {
definitionBody: sfn.DefinitionBody.fromChainable(definition),
comment: 'Run hourly until the account is deactivated or deleted',
})
Step 4: Grant the state machine necessary permissions.
In this example, you want the state machine to invoke task1LambdaFunction Lambda function:
// Grant state machine to invoke Lambda function
task1LambdaFunction.grantInvoke(sm)
Alternatively, you can use sm.addToRolePolicy() or someKindOfPolicy.attachToRole(sm.role).