Metadata-Version: 2.1
Name: aws-cdk.aws-stepfunctions-tasks
Version: 1.121.0
Summary: Task integrations for AWS StepFunctions
Home-page: https://github.com/aws/aws-cdk
Author: Amazon Web Services
License: Apache-2.0
Project-URL: Source, https://github.com/aws/aws-cdk.git
Platform: UNKNOWN
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: JavaScript
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.6
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Typing :: Typed
Classifier: Development Status :: 5 - Production/Stable
Classifier: License :: OSI Approved
Classifier: Framework :: AWS CDK
Classifier: Framework :: AWS CDK :: 1
Requires-Python: >=3.6
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE

# Tasks for AWS Step Functions

<!--BEGIN STABILITY BANNER-->---


![cdk-constructs: Stable](https://img.shields.io/badge/cdk--constructs-stable-success.svg?style=for-the-badge)

---
<!--END STABILITY BANNER-->

[AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html) 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](https://docs.aws.amazon.com/step-functions/latest/dg/amazon-states-language-task-state.html) 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](https://github.com/aws/aws-cdk) project.

## Table Of Contents

* [Tasks for AWS Step Functions](#tasks-for-aws-step-functions)

  * [Table Of Contents](#table-of-contents)
  * [Task](#task)
  * [Paths](#paths)

    * [InputPath](#inputpath)
    * [OutputPath](#outputpath)
    * [ResultPath](#resultpath)
  * [Task parameters from the state JSON](#task-parameters-from-the-state-json)
  * [Evaluate Expression](#evaluate-expression)
  * [API Gateway](#api-gateway)

    * [Call REST API Endpoint](#call-rest-api-endpoint)
    * [Call HTTP API Endpoint](#call-http-api-endpoint)
  * [Athena](#athena)

    * [StartQueryExecution](#startqueryexecution)
    * [GetQueryExecution](#getqueryexecution)
    * [GetQueryResults](#getqueryresults)
    * [StopQueryExecution](#stopqueryexecution)
  * [Batch](#batch)

    * [SubmitJob](#submitjob)
  * [CodeBuild](#codebuild)

    * [StartBuild](#startbuild)
  * [DynamoDB](#dynamodb)

    * [GetItem](#getitem)
    * [PutItem](#putitem)
    * [DeleteItem](#deleteitem)
    * [UpdateItem](#updateitem)
  * [ECS](#ecs)

    * [RunTask](#runtask)

      * [EC2](#ec2)
      * [Fargate](#fargate)
  * [EMR](#emr)

    * [Create Cluster](#create-cluster)
    * [Termination Protection](#termination-protection)
    * [Terminate Cluster](#terminate-cluster)
    * [Add Step](#add-step)
    * [Cancel Step](#cancel-step)
    * [Modify Instance Fleet](#modify-instance-fleet)
    * [Modify Instance Group](#modify-instance-group)
  * [EKS](#eks)

    * [Call](#call)
  * [EventBridge](#eventbridge)

    * [Put Events](#put-events)
  * [Glue](#glue)
  * [Glue DataBrew](#glue-databrew)
  * [Lambda](#lambda)
  * [SageMaker](#sagemaker)

    * [Create Training Job](#create-training-job)
    * [Create Transform Job](#create-transform-job)
    * [Create Endpoint](#create-endpoint)
    * [Create Endpoint Config](#create-endpoint-config)
    * [Create Model](#create-model)
    * [Update Endpoint](#update-endpoint)
  * [SNS](#sns)
  * [Step Functions](#step-functions)

    * [Start Execution](#start-execution)
    * [Invoke Activity](#invoke-activity)
  * [SQS](#sqs)

## Task

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

AWS Step Functions [integrates](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-service-integrations.html) 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](https://docs.aws.amazon.com/step-functions/latest/dg/amazon-states-language-paths.html) 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](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-input-output-filtering.html)

### 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.

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
submit_job = tasks.LambdaInvoke(self, "Invoke Handler",
    lambda_function=fn,
    input_path="$.input"
)
```

### 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](https://docs.aws.amazon.com/lambda/latest/dg/API_Invoke.html#API_Invoke_ResponseSyntax) 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`

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
submit_job = tasks.LambdaInvoke(self, "Invoke Handler",
    lambda_function=fn,
    output_path="$.Payload.result"
)
```

### ResultSelector

You can use [`ResultSelector`](https://docs.aws.amazon.com/step-functions/latest/dg/input-output-inputpath-params.html#input-output-resultselector)
to manipulate the raw result of a Task, Map or Parallel state before it is
passed to [`ResultPath`](###ResultPath). For service integrations, the raw
result contains metadata in addition to the response payload. You can use
ResultSelector to construct a JSON payload that becomes the effective result
using static values or references to the raw result or context object.

The following example extracts the output payload of a Lambda function Task and combines
it with some static values and the state name from the context object.

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
tasks.LambdaInvoke(self, "Invoke Handler",
    lambda_function=fn,
    result_selector={
        "lambda_output": sfn.JsonPath.string_at("$.Payload"),
        "invoke_request_id": sfn.JsonPath.string_at("$.SdkResponseMetadata.RequestId"),
        "static_value": {
            "foo": "bar"
        },
        "state_name": sfn.JsonPath.string_at("$.State.Name")
    }
)
```

### 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`](https://docs.aws.amazon.com/step-functions/latest/dg/input-output-resultpath.html) 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.

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
tasks.DynamoPutItem(self, "PutItem",
    item={
        "MessageId": tasks.DynamoAttributeValue.from_string("message-id")
    },
    table=my_table,
    result_path="$.Item"
)
```

⚠️ 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 `JsonPath` class,
using methods such as `JsonPath.stringAt()`.

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

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
submit_job = tasks.LambdaInvoke(self, "Invoke Handler",
    lambda_function=fn,
    payload=sfn.TaskInput.from_json_path_at("$.input"),
    invocation_type=tasks.LambdaInvocationType.EVENT
)
```

You can also use [intrinsic functions](https://docs.aws.amazon.com/step-functions/latest/dg/amazon-states-language-intrinsic-functions.html) with `JsonPath.stringAt()`.
Here is an example of starting an Athena query that is dynamically created using the task input:

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
start_query_execution_job = tasks.AthenaStartQueryExecution(self, "Athena Start Query",
    query_string=sfn.JsonPath.string_at("States.Format('select contacts where year={};', $.year)"),
    query_execution_context={
        "database_name": "interactions"
    },
    result_configuration={
        "encryption_configuration": {
            "encryption_option": tasks.EncryptionOption.S3_MANAGED
        },
        "output_location": {
            "bucket_name": "mybucket",
            "object_key": "myprefix"
        }
    },
    integration_pattern=sfn.IntegrationPattern.RUN_JOB
)
```

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:

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
convert_to_seconds = tasks.EvaluateExpression(self, "Convert to seconds",
    expression="$.waitMilliseconds / 1000",
    result_path="$.waitSeconds"
)

create_message = tasks.EvaluateExpression(self, "Create message",
    # Note: this is a string inside a string.
    expression="`Now waiting ${$.waitSeconds} seconds...`",
    runtime=lambda_.Runtime.NODEJS_14_X,
    result_path="$.message"
)

publish_message = tasks.SnsPublish(self, "Publish message",
    topic=sns.Topic(self, "cool-topic"),
    message=sfn.TaskInput.from_json_path_at("$.message"),
    result_path="$.sns"
)

wait = sfn.Wait(self, "Wait",
    time=sfn.WaitTime.seconds_path("$.waitSeconds")
)

sfn.StateMachine(self, "StateMachine",
    definition=convert_to_seconds.next(create_message).next(publish_message).next(wait)
)
```

The `EvaluateExpression` supports a `runtime` prop to specify the Lambda
runtime to use to evaluate the expression. Currently, only runtimes
of the Node.js family are supported.

## API Gateway

Step Functions supports [API Gateway](https://docs.aws.amazon.com/step-functions/latest/dg/connect-api-gateway.html) through the service integration pattern.

HTTP APIs are designed for low-latency, cost-effective integrations with AWS services, including AWS Lambda, and HTTP endpoints.
HTTP APIs support OIDC and OAuth 2.0 authorization, and come with built-in support for CORS and automatic deployments.
Previous-generation REST APIs currently offer more features. More details can be found [here](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-vs-rest.html).

### Call REST API Endpoint

The `CallApiGatewayRestApiEndpoint` calls the REST API endpoint.

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import aws_cdk.aws_stepfunctions as sfn
import ??? as tasks


rest_api = apigateway.RestApi(stack, "MyRestApi")

invoke_task = tasks.CallApiGatewayRestApiEndpoint(stack, "Call REST API",
    api=rest_api,
    stage_name="prod",
    method=HttpMethod.GET
)
```

### Call HTTP API Endpoint

The `CallApiGatewayHttpApiEndpoint` calls the HTTP API endpoint.

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import aws_cdk.aws_stepfunctions as sfn
import ??? as tasks


http_api = apigatewayv2.HttpApi(stack, "MyHttpApi")

invoke_task = tasks.CallApiGatewayHttpApiEndpoint(stack, "Call HTTP API",
    api_id=http_api.api_id,
    api_stack=cdk.Stack.of(http_api),
    method=HttpMethod.GET
)
```

## Athena

Step Functions supports [Athena](https://docs.aws.amazon.com/step-functions/latest/dg/connect-athena.html) through the service integration pattern.

### StartQueryExecution

The [StartQueryExecution](https://docs.aws.amazon.com/athena/latest/APIReference/API_StartQueryExecution.html) API runs the SQL query statement.

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
start_query_execution_job = tasks.AthenaStartQueryExecution(self, "Start Athena Query",
    query_string=sfn.JsonPath.string_at("$.queryString"),
    query_execution_context={
        "database_name": "mydatabase"
    },
    result_configuration={
        "encryption_configuration": {
            "encryption_option": tasks.EncryptionOption.S3_MANAGED
        },
        "output_location": {
            "bucket_name": "query-results-bucket",
            "object_key": "folder"
        }
    }
)
```

### GetQueryExecution

The [GetQueryExecution](https://docs.aws.amazon.com/athena/latest/APIReference/API_GetQueryExecution.html) API gets information about a single execution of a query.

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
get_query_execution_job = tasks.AthenaGetQueryExecution(self, "Get Query Execution",
    query_execution_id=sfn.JsonPath.string_at("$.QueryExecutionId")
)
```

### GetQueryResults

The [GetQueryResults](https://docs.aws.amazon.com/athena/latest/APIReference/API_GetQueryResults.html) API that streams the results of a single query execution specified by QueryExecutionId from S3.

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
get_query_results_job = tasks.AthenaGetQueryResults(self, "Get Query Results",
    query_execution_id=sfn.JsonPath.string_at("$.QueryExecutionId")
)
```

### StopQueryExecution

The [StopQueryExecution](https://docs.aws.amazon.com/athena/latest/APIReference/API_StopQueryExecution.html) API that stops a query execution.

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
stop_query_execution_job = tasks.AthenaStopQueryExecution(self, "Stop Query Execution",
    query_execution_id=sfn.JsonPath.string_at("$.QueryExecutionId")
)
```

## Batch

Step Functions supports [Batch](https://docs.aws.amazon.com/step-functions/latest/dg/connect-batch.html) through the service integration pattern.

### SubmitJob

The [SubmitJob](https://docs.aws.amazon.com/batch/latest/APIReference/API_SubmitJob.html) API submits an AWS Batch job from a job definition.

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
task = tasks.BatchSubmitJob(self, "Submit Job",
    job_definition_arn=batch_job_definition_arn,
    job_name="MyJob",
    job_queue_arn=batch_queue_arn
)
```

## CodeBuild

Step Functions supports [CodeBuild](https://docs.aws.amazon.com/step-functions/latest/dg/connect-codebuild.html) through the service integration pattern.

### StartBuild

[StartBuild](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_StartBuild.html) starts a CodeBuild Project by Project Name.

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
import aws_cdk.aws_codebuild as codebuild


codebuild_project = codebuild.Project(self, "Project",
    project_name="MyTestProject",
    build_spec=codebuild.BuildSpec.from_object({
        "version": "0.2",
        "phases": {
            "build": {
                "commands": ["echo \"Hello, CodeBuild!\""
                ]
            }
        }
    })
)

task = tasks.CodeBuildStartBuild(self, "Task",
    project=codebuild_project,
    integration_pattern=sfn.IntegrationPattern.RUN_JOB,
    environment_variables_override={
        "ZONE": BuildEnvironmentVariable(
            type=codebuild.BuildEnvironmentVariableType.PLAINTEXT,
            value=sfn.JsonPath.string_at("$.envVariables.zone")
        )
    }
)
```

## DynamoDB

You can call DynamoDB APIs from a `Task` state.
Read more about calling DynamoDB APIs [here](https://docs.aws.amazon.com/step-functions/latest/dg/connect-ddb.html)

### GetItem

The [GetItem](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_GetItem.html) operation returns a set of attributes for the item with the given primary key.

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
tasks.DynamoGetItem(self, "Get Item",
    key={"message_id": tasks.DynamoAttributeValue.from_string("message-007")},
    table=my_table
)
```

### PutItem

The [PutItem](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_PutItem.html) operation creates a new item, or replaces an old item with a new item.

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
tasks.DynamoPutItem(self, "PutItem",
    item={
        "MessageId": tasks.DynamoAttributeValue.from_string("message-007"),
        "Text": tasks.DynamoAttributeValue.from_string(sfn.JsonPath.string_at("$.bar")),
        "TotalCount": tasks.DynamoAttributeValue.from_number(10)
    },
    table=my_table
)
```

### DeleteItem

The [DeleteItem](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_DeleteItem.html) operation deletes a single item in a table by primary key.

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
tasks.DynamoDeleteItem(self, "DeleteItem",
    key={"MessageId": tasks.DynamoAttributeValue.from_string("message-007")},
    table=my_table,
    result_path=sfn.JsonPath.DISCARD
)
```

### UpdateItem

The [UpdateItem](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_UpdateItem.html) operation edits an existing item's attributes, or adds a new item
to the table if it does not already exist.

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
tasks.DynamoUpdateItem(self, "UpdateItem",
    key={
        "MessageId": tasks.DynamoAttributeValue.from_string("message-007")
    },
    table=my_table,
    expression_attribute_values={
        ":val": tasks.DynamoAttributeValue.number_from_string(sfn.JsonPath.string_at("$.Item.TotalCount.N")),
        ":rand": tasks.DynamoAttributeValue.from_number(20)
    },
    update_expression="SET TotalCount = :val + :rand"
)
```

## ECS

Step Functions supports [ECS/Fargate](https://docs.aws.amazon.com/step-functions/latest/dg/connect-ecs.html) through the service integration pattern.

### RunTask

[RunTask](https://docs.aws.amazon.com/step-functions/latest/dg/connect-ecs.html) starts a new task using the specified task definition.

#### EC2

The EC2 launch type allows you to run your containerized applications on a cluster
of Amazon EC2 instances that you manage.

When a task that uses the EC2 launch type is launched, Amazon ECS must determine where
to place the task based on the requirements specified in the task definition, such as
CPU and memory. Similarly, when you scale down the task count, Amazon ECS must determine
which tasks to terminate. You can apply task placement strategies and constraints to
customize how Amazon ECS places and terminates tasks. Learn more about [task placement](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-placement.html)

The latest ACTIVE revision of the passed task definition is used for running the task.

The following example runs a job from a task definition on EC2

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
import aws_cdk.aws_ecs as ecs


vpc = ec2.Vpc.from_lookup(self, "Vpc",
    is_default=True
)

cluster = ecs.Cluster(self, "Ec2Cluster", vpc=vpc)
cluster.add_capacity("DefaultAutoScalingGroup",
    instance_type=ec2.InstanceType("t2.micro"),
    vpc_subnets=SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC)
)

task_definition = ecs.TaskDefinition(self, "TD",
    compatibility=ecs.Compatibility.EC2
)

task_definition.add_container("TheContainer",
    image=ecs.ContainerImage.from_registry("foo/bar"),
    memory_limit_mi_b=256
)

run_task = tasks.EcsRunTask(self, "Run",
    integration_pattern=sfn.IntegrationPattern.RUN_JOB,
    cluster=cluster,
    task_definition=task_definition,
    launch_target=tasks.EcsEc2LaunchTarget(
        placement_strategies=[
            ecs.PlacementStrategy.spread_across_instances(),
            ecs.PlacementStrategy.packed_by_cpu(),
            ecs.PlacementStrategy.randomly()
        ],
        placement_constraints=[
            ecs.PlacementConstraint.member_of("blieptuut")
        ]
    )
)
```

#### Fargate

AWS Fargate is a serverless compute engine for containers that works with Amazon
Elastic Container Service (ECS). Fargate makes it easy for you to focus on building
your applications. Fargate removes the need to provision and manage servers, lets you
specify and pay for resources per application, and improves security through application
isolation by design. Learn more about [Fargate](https://aws.amazon.com/fargate/)

The Fargate launch type allows you to run your containerized applications without the need
to provision and manage the backend infrastructure. Just register your task definition and
Fargate launches the container for you. The latest ACTIVE revision of the passed
task definition is used for running the task. Learn more about
[Fargate Versioning](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_DescribeTaskDefinition.html)

The following example runs a job from a task definition on Fargate

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
import aws_cdk.aws_ecs as ecs


vpc = ec2.Vpc.from_lookup(self, "Vpc",
    is_default=True
)

cluster = ecs.Cluster(self, "FargateCluster", vpc=vpc)

task_definition = ecs.TaskDefinition(self, "TD",
    memory_mi_b="512",
    cpu="256",
    compatibility=ecs.Compatibility.FARGATE
)

container_definition = task_definition.add_container("TheContainer",
    image=ecs.ContainerImage.from_registry("foo/bar"),
    memory_limit_mi_b=256
)

run_task = tasks.EcsRunTask(self, "RunFargate",
    integration_pattern=sfn.IntegrationPattern.RUN_JOB,
    cluster=cluster,
    task_definition=task_definition,
    assign_public_ip=True,
    container_overrides=[ContainerOverride(
        container_definition=container_definition,
        environment=[TaskEnvironmentVariable(name="SOME_KEY", value=sfn.JsonPath.string_at("$.SomeKey"))]
    )],
    launch_target=tasks.EcsFargateLaunchTarget()
)
```

## 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](https://docs.aws.amazon.com/step-functions/latest/dg/connect-emr.html) about the differences when using these service integrations.

### Create Cluster

Creates and starts running a cluster (job flow).
Corresponds to the [`runJobFlow`](https://docs.aws.amazon.com/emr/latest/APIReference/API_RunJobFlow.html) API in EMR.

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
cluster_role = iam.Role(self, "ClusterRole",
    assumed_by=iam.ServicePrincipal("ec2.amazonaws.com")
)

service_role = iam.Role(self, "ServiceRole",
    assumed_by=iam.ServicePrincipal("elasticmapreduce.amazonaws.com")
)

auto_scaling_role = iam.Role(self, "AutoScalingRole",
    assumed_by=iam.ServicePrincipal("elasticmapreduce.amazonaws.com")
)

auto_scaling_role.assume_role_policy.add_statements(
    iam.PolicyStatement(
        effect=iam.Effect.ALLOW,
        principals=[
            iam.ServicePrincipal("application-autoscaling.amazonaws.com")
        ],
        actions=["sts:AssumeRole"
        ]
    ))

tasks.EmrCreateCluster(self, "Create Cluster",
    instances={},
    cluster_role=cluster_role,
    name=sfn.TaskInput.from_json_path_at("$.ClusterName").value,
    service_role=service_role,
    auto_scaling_role=auto_scaling_role
)
```

### 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`](https://docs.aws.amazon.com/step-functions/latest/dg/connect-emr.html) API in EMR.

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
tasks.EmrSetClusterTerminationProtection(self, "Task",
    cluster_id="ClusterId",
    termination_protected=False
)
```

### Terminate Cluster

Shuts down a cluster (job flow).
Corresponds to the [`terminateJobFlows`](https://docs.aws.amazon.com/emr/latest/APIReference/API_TerminateJobFlows.html) API in EMR.

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
tasks.EmrTerminateCluster(self, "Task",
    cluster_id="ClusterId"
)
```

### Add Step

Adds a new step to a running cluster.
Corresponds to the [`addJobFlowSteps`](https://docs.aws.amazon.com/emr/latest/APIReference/API_AddJobFlowSteps.html) API in EMR.

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
tasks.EmrAddStep(self, "Task",
    cluster_id="ClusterId",
    name="StepName",
    jar="Jar",
    action_on_failure=tasks.ActionOnFailure.CONTINUE
)
```

### Cancel Step

Cancels a pending step in a running cluster.
Corresponds to the [`cancelSteps`](https://docs.aws.amazon.com/emr/latest/APIReference/API_CancelSteps.html) API in EMR.

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
tasks.EmrCancelStep(self, "Task",
    cluster_id="ClusterId",
    step_id="StepId"
)
```

### Modify Instance Fleet

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

Corresponds to the [`modifyInstanceFleet`](https://docs.aws.amazon.com/emr/latest/APIReference/API_ModifyInstanceFleet.html) API in EMR.

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
tasks.EmrModifyInstanceFleetByName(self, "Task",
    cluster_id="ClusterId",
    instance_fleet_name="InstanceFleetName",
    target_on_demand_capacity=2,
    target_spot_capacity=0
)
```

### Modify Instance Group

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

Corresponds to the [`modifyInstanceGroups`](https://docs.aws.amazon.com/emr/latest/APIReference/API_ModifyInstanceGroups.html) API in EMR.

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
tasks.EmrModifyInstanceGroupByName(self, "Task",
    cluster_id="ClusterId",
    instance_group_name=sfn.JsonPath.string_at("$.InstanceGroupName"),
    instance_group={
        "instance_count": 1
    }
)
```

## EKS

Step Functions supports Amazon EKS through the service integration pattern.
The service integration APIs correspond to Amazon EKS APIs.

[Read more](https://docs.aws.amazon.com/step-functions/latest/dg/connect-eks.html) about the differences when using these service integrations.

### Call

Read and write Kubernetes resource objects via a Kubernetes API endpoint.
Corresponds to the [`call`](https://docs.aws.amazon.com/step-functions/latest/dg/connect-eks.html) API in Step Functions Connector.

The following code snippet includes a Task state that uses eks:call to list the pods.

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import aws_cdk.aws_eks as eks
import aws_cdk.aws_stepfunctions as sfn
import aws_cdk.aws_stepfunctions_tasks as tasks


my_eks_cluster = eks.Cluster(self, "my sample cluster",
    version=eks.KubernetesVersion.V1_18,
    cluster_name="myEksCluster"
)

tasks.EksCall(stack, "Call a EKS Endpoint",
    cluster=my_eks_cluster,
    http_method=MethodType.GET,
    http_path="/api/v1/namespaces/default/pods"
)
```

## EventBridge

Step Functions supports Amazon EventBridge through the service integration pattern.
The service integration APIs correspond to Amazon EventBridge APIs.

[Read more](https://docs.aws.amazon.com/step-functions/latest/dg/connect-eventbridge.html) about the differences when using these service integrations.

### Put Events

Send events to an EventBridge bus.
Corresponds to the [`put-events`](https://docs.aws.amazon.com/step-functions/latest/dg/connect-eventbridge.html) API in Step Functions Connector.

The following code snippet includes a Task state that uses events:putevents to send an event to the default bus.

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import aws_cdk.aws_events as events
import aws_cdk.aws_stepfunctions as sfn
import aws_cdk.aws_stepfunctions_tasks as tasks


my_event_bus = events.EventBus(stack, "EventBus",
    event_bus_name="MyEventBus1"
)

tasks.EventBridgePutEvents(stack, "Send an event to EventBridge",
    entries=[EventBridgePutEventsEntry(
        detail=sfn.TaskInput.from_object({
            "Message": "Hello from Step Functions!"
        }),
        event_bus=my_event_bus,
        detail_type="MessageFromStepFunctions",
        source="step.functions"
    )]
)
```

## Glue

Step Functions supports [AWS Glue](https://docs.aws.amazon.com/step-functions/latest/dg/connect-glue.html) through the service integration pattern.

You can call the [`StartJobRun`](https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-runs.html#aws-glue-api-jobs-runs-StartJobRun) API from a `Task` state.

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
tasks.GlueStartJobRun(self, "Task",
    glue_job_name="my-glue-job",
    arguments=sfn.TaskInput.from_object(
        key="value"
    ),
    timeout=cdk.Duration.minutes(30),
    notify_delay_after=cdk.Duration.minutes(5)
)
```

## Glue DataBrew

Step Functions supports [AWS Glue DataBrew](https://docs.aws.amazon.com/step-functions/latest/dg/connect-databrew.html) through the service integration pattern.

You can call the [`StartJobRun`](https://docs.aws.amazon.com/databrew/latest/dg/API_StartJobRun.html) API from a `Task` state.

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
tasks.GlueDataBrewStartJobRun(self, "Task",
    name="databrew-job"
)
```

## Lambda

[Invoke](https://docs.aws.amazon.com/lambda/latest/dg/API_Invoke.html) 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.

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
tasks.LambdaInvoke(self, "Invoke with state input",
    lambda_function=fn
)
```

When a function is invoked, the Lambda service sends  [these response
elements](https://docs.aws.amazon.com/lambda/latest/dg/API_Invoke.html#API_Invoke_ResponseElements)
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.

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
tasks.LambdaInvoke(self, "Invoke with empty object as payload",
    lambda_function=fn,
    payload=sfn.TaskInput.from_object()
)

# use the output of fn as input
tasks.LambdaInvoke(self, "Invoke with payload field in the state input",
    lambda_function=fn,
    payload=sfn.TaskInput.from_json_path_at("$.Payload")
)
```

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

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
tasks.LambdaInvoke(self, "Invoke and set function response as task output",
    lambda_function=fn,
    output_path="$.Payload"
)
```

If you want to combine the input and the Lambda function response you can use
the `payloadResponseOnly` property and specify the `resultPath`. This will put the
Lambda function ARN directly in the "Resource" string, but it conflicts with the
integrationPattern, invocationType, clientContext, and qualifier properties.

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
tasks.LambdaInvoke(self, "Invoke and combine function response with task input",
    lambda_function=fn,
    payload_response_only=True,
    result_path="$.fn"
)
```

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](https://docs.aws.amazon.com/step-functions/latest/dg/callback-task-sample-sqs.html#call-back-lambda-example)

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.

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
tasks.LambdaInvoke(self, "Invoke with callback",
    lambda_function=fn,
    integration_pattern=sfn.IntegrationPattern.WAIT_FOR_TASK_TOKEN,
    payload=sfn.TaskInput.from_object(
        token=sfn.JsonPath.task_token,
        input=sfn.JsonPath.string_at("$.someField")
    )
)
```

⚠️ 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](https://docs.aws.amazon.com/step-functions/latest/dg/connect-to-resource.html#connect-wait-token).

AWS Lambda can occasionally experience transient service errors. In this case, invoking Lambda
results in a 500 error, such as `ServiceException`, `AWSLambdaException`, or `SdkClientException`.
As a best practice, the `LambdaInvoke` task will retry on those errors with an interval of 2 seconds,
a back-off rate of 2 and 6 maximum attempts. Set the `retryOnServiceExceptions` prop to `false` to
disable this behavior.

## SageMaker

Step Functions supports [AWS SageMaker](https://docs.aws.amazon.com/step-functions/latest/dg/connect-sagemaker.html) through the service integration pattern.

### Create Training Job

You can call the [`CreateTrainingJob`](https://docs.aws.amazon.com/sagemaker/latest/dg/API_CreateTrainingJob.html) API from a `Task` state.

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
tasks.SageMakerCreateTrainingJob(self, "TrainSagemaker",
    training_job_name=sfn.JsonPath.string_at("$.JobName"),
    algorithm_specification={
        "algorithm_name": "BlazingText",
        "training_input_mode": tasks.InputMode.FILE
    },
    input_data_config=[{
        "channel_name": "train",
        "data_source": {
            "s3_data_source": {
                "s3_data_type": tasks.S3DataType.S3_PREFIX,
                "s3_location": tasks.S3Location.from_json_expression("$.S3Bucket")
            }
        }
    }],
    output_data_config={
        "s3_output_location": tasks.S3Location.from_bucket(s3.Bucket.from_bucket_name(self, "Bucket", "mybucket"), "myoutputpath")
    },
    resource_config={
        "instance_count": 1,
        "instance_type": ec2.InstanceType(JsonPath.string_at("$.InstanceType")),
        "volume_size": cdk.Size.gibibytes(50)
    }, # optional: default is 1 instance of EC2 `M4.XLarge` with `10GB` volume
    stopping_condition={
        "max_runtime": cdk.Duration.hours(2)
    }
)
```

### Create Transform Job

You can call the [`CreateTransformJob`](https://docs.aws.amazon.com/sagemaker/latest/dg/API_CreateTransformJob.html) API from a `Task` state.

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
tasks.SageMakerCreateTransformJob(self, "Batch Inference",
    transform_job_name="MyTransformJob",
    model_name="MyModelName",
    model_client_options={
        "invocations_max_retries": 3, # default is 0
        "invocations_timeout": cdk.Duration.minutes(5)
    },
    transform_input={
        "transform_data_source": {
            "s3_data_source": {
                "s3_uri": "s3://inputbucket/train",
                "s3_data_type": tasks.S3DataType.S3_PREFIX
            }
        }
    },
    transform_output={
        "s3_output_path": "s3://outputbucket/TransformJobOutputPath"
    },
    transform_resources={
        "instance_count": 1,
        "instance_type": ec2.InstanceType.of(ec2.InstanceClass.M4, ec2.InstanceSize.XLARGE)
    }
)
```

### Create Endpoint

You can call the [`CreateEndpoint`](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateEndpoint.html) API from a `Task` state.

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
tasks.SageMakerCreateEndpoint(self, "SagemakerEndpoint",
    endpoint_name=sfn.JsonPath.string_at("$.EndpointName"),
    endpoint_config_name=sfn.JsonPath.string_at("$.EndpointConfigName")
)
```

### Create Endpoint Config

You can call the [`CreateEndpointConfig`](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateEndpointConfig.html) API from a `Task` state.

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
tasks.SageMakerCreateEndpointConfig(self, "SagemakerEndpointConfig",
    endpoint_config_name="MyEndpointConfig",
    production_variants=[{
        "initial_instance_count": 2,
        "instance_type": ec2.InstanceType.of(ec2.InstanceClass.M5, ec2.InstanceSize.XLARGE),
        "model_name": "MyModel",
        "variant_name": "awesome-variant"
    }]
)
```

### Create Model

You can call the [`CreateModel`](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModel.html) API from a `Task` state.

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
tasks.SageMakerCreateModel(self, "Sagemaker",
    model_name="MyModel",
    primary_container=tasks.ContainerDefinition(
        image=tasks.DockerImage.from_json_expression(sfn.JsonPath.string_at("$.Model.imageName")),
        mode=tasks.Mode.SINGLE_MODEL,
        model_s3_location=tasks.S3Location.from_json_expression("$.TrainingJob.ModelArtifacts.S3ModelArtifacts")
    )
)
```

### Update Endpoint

You can call the [`UpdateEndpoint`](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_UpdateEndpoint.html) API from a `Task` state.

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
tasks.SageMakerUpdateEndpoint(self, "SagemakerEndpoint",
    endpoint_name=sfn.JsonPath.string_at("$.Endpoint.Name"),
    endpoint_config_name=sfn.JsonPath.string_at("$.Endpoint.EndpointConfig")
)
```

## SNS

Step Functions supports [Amazon SNS](https://docs.aws.amazon.com/step-functions/latest/dg/connect-sns.html) through the service integration pattern.

You can call the [`Publish`](https://docs.aws.amazon.com/sns/latest/api/API_Publish.html) API from a `Task` state to publish to an SNS topic.

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
topic = sns.Topic(self, "Topic")

# Use a field from the execution data as message.
task1 = tasks.SnsPublish(self, "Publish1",
    topic=topic,
    integration_pattern=sfn.IntegrationPattern.REQUEST_RESPONSE,
    message=sfn.TaskInput.from_data_at("$.state.message"),
    message_attributes={
        "place": {
            "value": sfn.JsonPath.string_at("$.place")
        },
        "pic": {
            # BINARY must be explicitly set
            "type": MessageAttributeDataType.BINARY,
            "value": sfn.JsonPath.string_at("$.pic")
        },
        "people": {
            "value": 4
        },
        "handles": {
            "value": ["@kslater", "@jjf", null, "@mfanning"]
        }
    }
)

# Combine a field from the execution data with
# a literal object.
task2 = tasks.SnsPublish(self, "Publish2",
    topic=topic,
    message=sfn.TaskInput.from_object(
        field1="somedata",
        field2=sfn.JsonPath.string_at("$.field2")
    )
)
```

## Step Functions

### Start Execution

You can manage [AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/connect-stepfunctions.html) executions.

AWS Step Functions supports it's own [`StartExecution`](https://docs.aws.amazon.com/step-functions/latest/apireference/API_StartExecution.html) API as a service integration.

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
# Define a state machine with one Pass state
child = sfn.StateMachine(self, "ChildStateMachine",
    definition=sfn.Chain.start(sfn.Pass(self, "PassState"))
)

# Include the state machine in a Task state with callback pattern
task = tasks.StepFunctionsStartExecution(self, "ChildTask",
    state_machine=child,
    integration_pattern=sfn.IntegrationPattern.WAIT_FOR_TASK_TOKEN,
    input=sfn.TaskInput.from_object(
        token=sfn.JsonPath.task_token,
        foo="bar"
    ),
    name="MyExecutionName"
)

# Define a second state machine with the Task state above
sfn.StateMachine(self, "ParentStateMachine",
    definition=task
)
```

### Invoke Activity

You can invoke a [Step Functions Activity](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-activities.html) which enables you to have
a task in your state machine where the work is performed by a *worker* that can
be hosted on Amazon EC2, Amazon ECS, AWS Lambda, basically anywhere. Activities
are a way to associate code running somewhere (known as an activity worker) with
a specific task in a state machine.

When Step Functions reaches an activity task state, the workflow waits for an
activity worker to poll for a task. An activity worker polls Step Functions by
using GetActivityTask, and sending the ARN for the related activity.

After the activity worker completes its work, it can provide a report of its
success or failure by using `SendTaskSuccess` or `SendTaskFailure`. These two
calls use the taskToken provided by GetActivityTask to associate the result
with that task.

The following example creates an activity and creates a task that invokes the activity.

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
submit_job_activity = sfn.Activity(self, "SubmitJob")

tasks.StepFunctionsInvokeActivity(self, "Submit Job",
    activity=submit_job_activity
)
```

## SQS

Step Functions supports [Amazon SQS](https://docs.aws.amazon.com/step-functions/latest/dg/connect-sqs.html)

You can call the [`SendMessage`](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SendMessage.html) API from a `Task` state
to send a message to an SQS queue.

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
queue = sqs.Queue(self, "Queue")

# Use a field from the execution data as message.
task1 = tasks.SqsSendMessage(self, "Send1",
    queue=queue,
    message_body=sfn.TaskInput.from_json_path_at("$.message")
)

# Combine a field from the execution data with
# a literal object.
task2 = tasks.SqsSendMessage(self, "Send2",
    queue=queue,
    message_body=sfn.TaskInput.from_object(
        field1="somedata",
        field2=sfn.JsonPath.string_at("$.field2")
    )
)
```


