Skip navigation links

@Stability(value=Experimental)

Package software.amazon.awscdk.services.stepfunctions.tasks

Tasks for AWS Step Functions

See: Description

Package software.amazon.awscdk.services.stepfunctions.tasks Description

Tasks for AWS Step Functions

---

cdk-constructs: Experimental

The APIs of higher level constructs in this module are experimental and under active development. They are subject to non-backward compatible changes or removal in any future version. These are not subject to the Semantic Versioning model and breaking changes will be announced in the release notes. This means that while you may use them, you may need to update your source code when upgrading to a newer version of this package.


AWS Step Functions is a web service that enables you to coordinate the components of distributed applications and microservices using visual workflows. You build applications from individual components that each perform a discrete function, or task, allowing you to scale and change applications quickly.

A Task state represents a single unit of work performed by a state machine. All work in your state machine is performed by tasks.

This module is part of the AWS Cloud Development Kit project.

Table Of Contents

Task

A Task state represents a single unit of work performed by a state machine. In the CDK, the exact work to be In the CDK, the exact work to be done is determined by a class that implements IStepFunctionsTask.

AWS Step Functions integrates with some AWS services so that you can call API actions, and coordinate executions directly from the Amazon States Language in Step Functions. You can directly call and pass parameters to the APIs of those services.

Paths

In the Amazon States Language, a path is a string beginning with $ that you can use to identify components within JSON text.

Learn more about input and output processing in Step Functions here

InputPath

Both InputPath and Parameters fields provide a way to manipulate JSON as it moves through your workflow. AWS Step Functions applies the InputPath field first, and then the Parameters field. You can first filter your raw input to a selection you want using InputPath, and then apply Parameters to manipulate that input further, or add new values. If you don't specify an InputPath, a default value of $ will be used.

The following example provides the field named input as the input to the Task state that runs a Lambda function.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 var submitJob = Task.Builder.create(stack, "Invoke Handler")
         .task(new RunLambdaTask(submitJobLambda))
         .inputPath("$.input")
         .build();
 

OutputPath

Tasks also allow you to select a portion of the state output to pass to the next state. This enables you to filter out unwanted information, and pass only the portion of the JSON that you care about. If you don't specify an OutputPath, a default value of $ will be used. This passes the entire JSON node to the next state.

The response from a Lambda function includes the response from the function as well as other metadata.

The following example assigns the output from the Task to a field named result

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 var submitJob = Task.Builder.create(stack, "Invoke Handler")
         .task(new RunLambdaTask(submitJobLambda))
         .outputPath("$.Payload.result")
         .build();
 

ResultPath

The output of a state can be a copy of its input, the result it produces (for example, output from a Task state’s Lambda function), or a combination of its input and result. Use ResultPath to control which combination of these is passed to the state output. If you don't specify an ResultPath, a default value of $ will be used.

The following example adds the item from calling DynamoDB's getItem API to the state input and passes it to the next state.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Task.Builder.create(this, "PutItem")
         .task(tasks.CallDynamoDB.getItem(Map.of(
                 "item", Map.of(
                         "MessageId", new tasks.DynamoAttributeValue().withS("12345")),
                 "tableName", "my-table")))
         .resultPath("$.Item")
         .build();
 

⚠️ The OutputPath is computed after applying ResultPath. All service integrations return metadata as part of their response. When using ResultPath, it's not possible to merge a subset of the task output to the input.

Task parameters from the state JSON

Most tasks take parameters. Parameter values can either be static, supplied directly in the workflow definition (by specifying their values), or a value available at runtime in the state machine's execution (either as its input or an output of a prior state). Parameter values available at runtime can be specified via the Data class, using methods such as Data.stringAt().

The following example provides the field named input as the input to the Lambda function and invokes it asynchronously.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 var submitJob = Task.Builder.create(stack, "Invoke Handler")
         .task(RunLambdaTask.Builder.create(submitJobLambda)
                 .payload(sfn.Data.StringAt("$.input"))
                 .invocationType(tasks.InvocationType.getEVENT())
                 .build())
         .build();
 

Each service integration has its own set of parameters that can be supplied.

Evaluate Expression

Use the EvaluateExpression to perform simple operations referencing state paths. The expression referenced in the task will be evaluated in a Lambda function (eval()). This allows you to not have to write Lambda code for simple operations.

Example: convert a wait time from milliseconds to seconds, concat this in a message and wait:

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 var convertToSeconds = Task.Builder.create(this, "Convert to seconds")
         .task(EvaluateExpression.Builder.create().expression("$.waitMilliseconds / 1000").build())
         .resultPath("$.waitSeconds")
         .build();
 
 var createMessage = Task.Builder.create(this, "Create message")
         // Note: this is a string inside a string.
         .task(EvaluateExpression.Builder.create()
                 .expression("`Now waiting ${$.waitSeconds} seconds...`")
                 .runtime(lambda.Runtime.getNODEJS_10_X())
                 .build())
         .resultPath("$.message")
         .build();
 
 var publishMessage = Task.Builder.create(this, "Publish message")
         .task(PublishToTopic.Builder.create(topic)
                 .message(sfn.TaskInput.fromDataAt("$.message"))
                 .build())
         .resultPath("$.sns")
         .build();
 
 var wait = Wait.Builder.create(this, "Wait")
         .time(sfn.WaitTime.secondsPath("$.waitSeconds"))
         .build();
 
 StateMachine.Builder.create(this, "StateMachine")
         .definition(convertToSeconds
             .next(createMessage)
             .next(publishMessage).next(wait))
         .build();
 

The EvaluateExpression supports a runtime prop to specify the Lambda runtime to use to evaluate the expression. Currently, the only runtime supported is lambda.Runtime.NODEJS_10_X.

Batch

Step Functions supports Batch through the service integration pattern.

SubmitJob

The SubmitJob API submits an AWS Batch job from a job definition.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 import software.amazon.awscdk.services.batch.*;
 
 JobQueue batchQueue = new JobQueue(this, "JobQueue", new JobQueueProps()
         .computeEnvironments(asList(new JobQueueComputeEnvironment()
                 .order(1)
                 .computeEnvironment(new ComputeEnvironment(this, "ComputeEnv", new ComputeEnvironmentProps()
                         .computeResources(new ComputeResources().vpc(vpc)))))));
 
 JobDefinition batchJobDefinition = new JobDefinition(this, "JobDefinition", new JobDefinitionProps()
         .container(new JobDefinitionContainer()
                 .image(ecs.ContainerImage.fromAsset(path.resolve(__dirname, "batchjob-image")))));
 
 var task = Task.Builder.create(this, "Submit Job")
         .task(RunBatchJob.Builder.create()
                 .jobDefinition(batchJobDefinition)
                 .jobName("MyJob")
                 .jobQueue(batchQueue)
                 .build())
         .build();
 

DynamoDB

You can call DynamoDB APIs from a Task state. Read more about calling DynamoDB APIs here

GetItem

The GetItem operation returns a set of attributes for the item with the given primary key.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Task.Builder.create(this, "Get Item")
         .task(tasks.CallDynamoDB.getItem(Map.of(
                 "partitionKey", Map.of(
                         "name", "messageId",
                         "value", new tasks.DynamoAttributeValue().withS("message-007")),
                 "tableName", "my-table")))
         .build();
 

PutItem

The PutItem operation creates a new item, or replaces an old item with a new item.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Task.Builder.create(this, "PutItem")
         .task(tasks.CallDynamoDB.putItem(Map.of(
                 "item", Map.of(
                         "MessageId", new tasks.DynamoAttributeValue().withS("message-007"),
                         "Text", new tasks.DynamoAttributeValue().withS(sfn.Data.stringAt("$.bar")),
                         "TotalCount", new tasks.DynamoAttributeValue().withN("10")),
                 "tableName", "my-table")))
         .build();
 

DeleteItem

The DeleteItem operation deletes a single item in a table by primary key.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Task.Builder.create(this, "DeleteItem")
         .task(tasks.CallDynamoDB.deleteItem(Map.of(
                 "partitionKey", Map.of(
                         "name", "MessageId",
                         "value", new tasks.DynamoAttributeValue().withS("message-007")),
                 "tableName", "my-table")))
         .resultPath("DISCARD")
         .build();
 

UpdateItem

The UpdateItem operation edits an existing item's attributes, or adds a new item to the table if it does not already exist.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 var updateItemTask = Task.Builder.create(this, "UpdateItem")
         .task(tasks.CallDynamoDB.updateItem(Map.of(
                 "partitionKey", Map.of(
                         "name", "MessageId",
                         "value", new tasks.DynamoAttributeValue().withS("message-007")),
                 "tableName", "my-table",
                 "expressionAttributeValues", Map.of(
                         ":val", new tasks.DynamoAttributeValue().withN(sfn.Data.stringAt("$.Item.TotalCount.N")),
                         ":rand", new tasks.DynamoAttributeValue().withN("20")),
                 "updateExpression", "SET TotalCount = :val + :rand")))
         .build();
 

ECS

Step Functions supports ECS/Fargate through the service integration pattern.

RunTask

RunTask starts a new task using the specified task definition.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 import software.amazon.awscdk.services.ecs.*;
 
 // See examples in ECS library for initialization of 'cluster' and 'taskDefinition'
 
 // See examples in ECS library for initialization of 'cluster' and 'taskDefinition'
 RunEcsFargateTask.Builder.create()
         .cluster(cluster)
         .taskDefinition(taskDefinition)
         .containerOverrides(asList(Map.of(
                 "containerName", "TheContainer",
                 "environment", asList(Map.of(
                         "name", "CONTAINER_INPUT",
                         "value", Data.stringAt("$.valueFromStateData"))))))
         .build();
 
 fargateTask.connections.allowToDefaultPort(rdsCluster, "Read the database");
 
 Task.Builder.create(this, "CallFargate")
         .task(fargateTask)
         .build();
 

EMR

Step Functions supports Amazon EMR through the service integration pattern. The service integration APIs correspond to Amazon EMR APIs but differ in the parameters that are used.

Read more about the differences when using these service integrations.

Create Cluster

Creates and starts running a cluster (job flow). Corresponds to the runJobFlow API in EMR.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 var clusterRole = Role.Builder.create(stack, "ClusterRole")
         .assumedBy(new ServicePrincipal("ec2.amazonaws.com"))
         .build();
 
 var serviceRole = Role.Builder.create(stack, "ServiceRole")
         .assumedBy(new ServicePrincipal("elasticmapreduce.amazonaws.com"))
         .build();
 
 var autoScalingRole = Role.Builder.create(stack, "AutoScalingRole")
         .assumedBy(new ServicePrincipal("elasticmapreduce.amazonaws.com"))
         .build();
 
 autoScalingRole.assumeRolePolicy.addStatements(
 PolicyStatement.Builder.create()
         .effect(iam.Effect.getALLOW())
         .principals(asList(
             new ServicePrincipal("application-autoscaling.amazonaws.com")))
         .actions(asList("sts:AssumeRole"))
         .build());
 
 Task.Builder.create(stack, "Create Cluster")
         .task(EmrCreateCluster.Builder.create()
                 .instances(Map.of())
                 .clusterRole(clusterRole)
                 .name(sfn.TaskInput.fromDataAt('$.ClusterName').getValue())
                 .serviceRole(serviceRole)
                 .autoScalingRole(autoScalingRole)
                 .integrationPattern(sfn.ServiceIntegrationPattern.getFIRE_AND_FORGET())
                 .build())
         .build();
 

Termination Protection

Locks a cluster (job flow) so the EC2 instances in the cluster cannot be terminated by user intervention, an API call, or a job-flow error.

Corresponds to the setTerminationProtection API in EMR.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Task.Builder.create(stack, "Task")
         .task(EmrSetClusterTerminationProtection.Builder.create()
                 .clusterId("ClusterId")
                 .terminationProtected(false)
                 .build())
         .build();
 

Terminate Cluster

Shuts down a cluster (job flow). Corresponds to the terminateJobFlows API in EMR.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Task.Builder.create(stack, "Task")
         .task(EmrTerminateCluster.Builder.create()
                 .clusterId("ClusterId")
                 .build())
         .build();
 

Add Step

Adds a new step to a running cluster. Corresponds to the addJobFlowSteps API in EMR.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Task.Builder.create(stack, "Task")
         .task(EmrAddStep.Builder.create()
                 .clusterId("ClusterId")
                 .name("StepName")
                 .jar("Jar")
                 .actionOnFailure(tasks.ActionOnFailure.getCONTINUE())
                 .build())
         .build();
 

Cancel Step

Cancels a pending step in a running cluster. Corresponds to the cancelSteps API in EMR.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Task.Builder.create(stack, "Task")
         .task(EmrCancelStep.Builder.create()
                 .clusterId("ClusterId")
                 .stepId("StepId")
                 .build())
         .build();
 

Modify Instance Fleet

Modifies the target On-Demand and target Spot capacities for the instance fleet with the specified InstanceFleetName.

Corresponds to the modifyInstanceFleet API in EMR.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Task.Builder.create(stack, "Task")
         .task(EmrModifyInstanceFleetByName.Builder.create()
                 .clusterId("ClusterId")
                 .instanceFleetName("InstanceFleetName")
                 .targetOnDemandCapacity(2)
                 .targetSpotCapacity(0)
                 .build())
         .build();
 

Modify Instance Group

Modifies the number of nodes and configuration settings of an instance group.

Corresponds to the modifyInstanceGroups API in EMR.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Task.Builder.create(stack, "Task")
         .task(EmrModifyInstanceGroupByName.Builder.create()
                 .clusterId("ClusterId")
                 .instanceGroupName(sfn.Data.stringAt("$.InstanceGroupName"))
                 .instanceGroup(Map.of(
                         "instanceCount", 1))
                 .build())
         .build();
 

Glue

Step Functions supports AWS Glue through the service integration pattern.

You can call the StartJobRun API from a Task state.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Task.Builder.create(stack, "Task")
         .task(RunGlueJobTask.Builder.create(jobName)
                 .arguments(Map.of(
                         "key", "value"))
                 .timeout(cdk.Duration.minutes(30))
                 .notifyDelayAfter(cdk.Duration.minutes(5))
                 .build())
         .build();
 

Lambda

Invoke a Lambda function.

You can specify the input to your Lambda function through the payload attribute. By default, Step Functions invokes Lambda function with the state input (JSON path '$') as the input.

The following snippet invokes a Lambda Function with the state input as the payload by referencing the $ path.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 import software.amazon.awscdk.services.lambda.*;
 import software.amazon.awscdk.services.stepfunctions.*;
 import software.amazon.awscdk.services.stepfunctions.tasks.*;
 
 Function myLambda = new Function(this, "my sample lambda", new FunctionProps()
         .code(Code.fromInline("exports.handler = async () => {\n    return {\n      statusCode: '200',\n      body: 'hello, world!'\n    };\n  };"))
         .runtime(Runtime.getNODEJS_12_X())
         .handler("index.handler"));
 
 new LambdaInvoke(this, "Invoke with state input", new LambdaInvokeProps()
         .lambdaFunction(myLambda));
 

When a function is invoked, the Lambda service sends these response elements back.

⚠️ The response from the Lambda function is in an attribute called Payload

The following snippet invokes a Lambda Function by referencing the $.Payload path to reference the output of a Lambda executed before it.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 LambdaInvoke.Builder.create(this, "Invoke with empty object as payload")
         .lambdaFunction(myLambda)
         .payload(sfn.TaskInput.fromObject(Map.of()))
         .build();
 
 // use the output of myLambda as input
 // use the output of myLambda as input
 LambdaInvoke.Builder.create(this, "Invoke with payload field in the state input")
         .lambdaFunction(myOtherLambda)
         .payload(sfn.TaskInput.fromDataAt("$.Payload"))
         .build();
 

The following snippet invokes a Lambda and sets the task output to only include the Lambda function response.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 LambdaInvoke.Builder.create(this, "Invoke and set function response as task output")
         .lambdaFunction(myLambda)
         .payload(sfn.TaskInput.fromDataAt("$"))
         .outputPath("$.Payload")
         .build();
 

You can have Step Functions pause a task, and wait for an external process to return a task token. Read more about the callback pattern

To use the callback pattern, set the token property on the task. Call the Step Functions SendTaskSuccess or SendTaskFailure APIs with the token to indicate that the task has completed and the state machine should resume execution.

The following snippet invokes a Lambda with the task token as part of the input to the Lambda.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 LambdaInvoke.Builder.create(stack, "Invoke with callback")
         .lambdaFunction(myLambda)
         .integrationPattern(sfn.IntegrationPattern.getWAIT_FOR_TASK_TOKEN())
         .payload(sfn.TaskInput.fromObject(Map.of(
                 "token", sfn.Context.getTaskToken(),
                 "input", sfn.Data.stringAt("$.someField"))))
         .build();
 

⚠️ The task will pause until it receives that task token back with a SendTaskSuccess or SendTaskFailure call. Learn more about Callback with the Task Token.

SageMaker

Step Functions supports AWS SageMaker through the service integration pattern.

Create Training Job

You can call the CreateTrainingJob API from a Task state.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Task.Builder.create(stack, "TrainSagemaker")
         .task(SagemakerTrainTask.Builder.create()
                 .trainingJobName(sfn.Data.stringAt("$.JobName"))
                 .role(role)
                 .algorithmSpecification(Map.of(
                         "algorithmName", "BlazingText",
                         "trainingInputMode", tasks.InputMode.getFILE()))
                 .inputDataConfig(asList(Map.of(
                         "channelName", "train",
                         "dataSource", Map.of(
                                 "s3DataSource", Map.of(
                                         "s3DataType", tasks.S3DataType.getS3_PREFIX(),
                                         "s3Location", tasks.S3Location.fromJsonExpression("$.S3Bucket"))))))
                 .outputDataConfig(Map.of(
                         "s3OutputLocation", tasks.S3Location.fromBucket(s3.Bucket.fromBucketName(stack, "Bucket", "mybucket"), "myoutputpath")))
                 .resourceConfig(Map.of(
                         "instanceCount", 1,
                         "instanceType", ec2.InstanceType.of(ec2.InstanceClass.getP3(), ec2.InstanceSize.getXLARGE2()),
                         "volumeSizeInGB", 50))
                 .stoppingCondition(Map.of(
                         "maxRuntime", cdk.Duration.hours(1)))
                 .build())
         .build();
 

Create Transform Job

You can call the CreateTransformJob API from a Task state.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 var transformJob = SagemakerTransformTask.Builder.create(transformJobName, "MyTransformJob", modelName, "MyModelName", role, transformInput, Map.of(
         "transformDataSource", Map.of(
                 "s3DataSource", Map.of(
                         "s3Uri", "s3://inputbucket/train",
                         "s3DataType", S3DataType.getS3Prefix()))), transformOutput, Map.of(
         "s3OutputPath", "s3://outputbucket/TransformJobOutputPath"), transformResources)
         .instanceCount(1)
         .instanceType(ec2.InstanceType.of(ec2.InstanceClass.getM4(), ec2.InstanceSize.getXLarge()))
         .build();
 
 var task = Task.Builder.create(this, "Batch Inference")
         .task(transformJob)
         .build();
 

SNS

Step Functions supports Amazon SNS through the service integration pattern.

You can call the Publish API from a Task state to publish to an SNS topic.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 import software.amazon.awscdk.services.sns.*;
 import software.amazon.awscdk.services.stepfunctions.*;
 import software.amazon.awscdk.services.stepfunctions.tasks.*;
 
 // ...
 
 Topic topic = new Topic(this, "Topic");
 
 // Use a field from the execution data as message.
 SnsPublish task1 = new SnsPublish(this, "Publish1", new SnsPublishProps()
         .topic(topic)
         .integrationPattern(sfn.IntegrationPattern.getREQUEST_RESPONSE())
         .message(sfn.TaskInput.fromDataAt("$.state.message")));
 
 // Combine a field from the execution data with
 // a literal object.
 SnsPublish task2 = new SnsPublish(this, "Publish2", new SnsPublishProps()
         .topic(topic)
         .message(sfn.TaskInput.fromObject(Map.of(
                 "field1", "somedata",
                 "field2", sfn.Data.stringAt("$.field2")))));
 

Step Functions

You can manage AWS Step Functions executions.

AWS Step Functions supports it's own StartExecution API as a service integration.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 // Define a state machine with one Pass state
 var child = StateMachine.Builder.create(stack, "ChildStateMachine")
         .definition(sfn.Chain.start(new Pass(stack, "PassState")))
         .build();
 
 // Include the state machine in a Task state with callback pattern
 var task = Task.Builder.create(stack, "ChildTask")
         .task(ExecuteStateMachine.Builder.create(child)
                 .integrationPattern(sfn.ServiceIntegrationPattern.getWAIT_FOR_TASK_TOKEN())
                 .input(Map.of(
                         "token", sfn.Context.getTaskToken(),
                         "foo", "bar"))
                 .name("MyExecutionName")
                 .build())
         .build();
 
 // Define a second state machine with the Task state above
 // Define a second state machine with the Task state above
 StateMachine.Builder.create(stack, "ParentStateMachine")
         .definition(task)
         .build();
 

SQS

Step Functions supports Amazon SQS

You can call the SendMessage API from a Task state to send a message to an SQS queue.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 import software.amazon.awscdk.services.stepfunctions.*;
 import software.amazon.awscdk.services.stepfunctions.tasks.*;
 import software.amazon.awscdk.services.sqs.*;
 
 // ...
 
 Queue queue = new Queue(this, "Queue");
 
 // Use a field from the execution data as message.
 SqsSendMessage task1 = new SqsSendMessage(this, "Send1", new SqsSendMessageProps()
         .queue(queue)
         .messageBody(sfn.TaskInput.fromDataAt("$.message")));
 
 // Combine a field from the execution data with
 // a literal object.
 SqsSendMessage task2 = new SqsSendMessage(this, "Send2", new SqsSendMessageProps()
         .queue(queue)
         .messageBody(sfn.TaskInput.fromObject(Map.of(
                 "field1", "somedata",
                 "field2", sfn.Data.stringAt("$.field2")))));
 
Skip navigation links

Copyright © 2020. All rights reserved.