Step Functions examples using SDK for Kotlin - AWS SDK Code Examples

There are more AWS SDK examples available in the AWS Doc SDK Examples GitHub repo.

Step Functions examples using SDK for Kotlin

The following code examples show you how to perform actions and implement common scenarios by using the AWS SDK for Kotlin with Step Functions.

Basics are code examples that show you how to perform the essential operations within a service.

Actions are code excerpts from larger programs and must be run in context. While actions show you how to call individual service functions, you can see actions in context in their related scenarios.

Each example includes a link to the complete source code, where you can find instructions on how to set up and run the code in context.

Get started

The following code examples show how to get started using Step Functions.

SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

import aws.sdk.kotlin.services.sfn.SfnClient import aws.sdk.kotlin.services.sfn.model.ListStateMachinesRequest /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main() { println(DASHES) println("Welcome to the AWS Step Functions Hello example.") println("Lets list up to ten of your state machines:") println(DASHES) listMachines() } suspend fun listMachines() { SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.listStateMachines(ListStateMachinesRequest {}) response.stateMachines?.forEach { machine -> println("The name of the state machine is ${machine.name}") println("The ARN value is ${machine.stateMachineArn}") } } }

Basics

The following code example shows how to:

  • Create an activity.

  • Create a state machine from an Amazon States Language definition that contains the previously created activity as a step.

  • Run the state machine and respond to the activity with user input.

  • Get the final status and output after the run completes, then clean up resources.

SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

import aws.sdk.kotlin.services.iam.IamClient import aws.sdk.kotlin.services.iam.model.CreateRoleRequest import aws.sdk.kotlin.services.sfn.SfnClient import aws.sdk.kotlin.services.sfn.model.CreateActivityRequest import aws.sdk.kotlin.services.sfn.model.CreateStateMachineRequest import aws.sdk.kotlin.services.sfn.model.DeleteActivityRequest import aws.sdk.kotlin.services.sfn.model.DeleteStateMachineRequest import aws.sdk.kotlin.services.sfn.model.DescribeExecutionRequest import aws.sdk.kotlin.services.sfn.model.DescribeStateMachineRequest import aws.sdk.kotlin.services.sfn.model.GetActivityTaskRequest import aws.sdk.kotlin.services.sfn.model.ListActivitiesRequest import aws.sdk.kotlin.services.sfn.model.ListStateMachinesRequest import aws.sdk.kotlin.services.sfn.model.SendTaskSuccessRequest import aws.sdk.kotlin.services.sfn.model.StartExecutionRequest import aws.sdk.kotlin.services.sfn.model.StateMachineType import aws.sdk.kotlin.services.sfn.paginators.listActivitiesPaginated import aws.sdk.kotlin.services.sfn.paginators.listStateMachinesPaginated import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.node.ObjectNode import kotlinx.coroutines.flow.transform import java.util.Scanner import java.util.UUID import kotlin.collections.ArrayList import kotlin.system.exitProcess /** To run this code example, place the chat_sfn_state_machine.json file into your project's resources folder. You can obtain the JSON file to create a state machine in the following GitHub location: https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/resources/sample_files Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html This Kotlin code example performs the following tasks: 1. List activities using a paginator. 2. List state machines using a paginator. 3. Creates an activity. 4. Creates a state machine. 5. Describes the state machine. 6. Starts execution of the state machine and interacts with it. 7. Describes the execution. 8. Deletes the activity. 9. Deletes the state machine. */ val DASHES: String = String(CharArray(80)).replace("\u0000", "-") suspend fun main(args: Array<String>) { val usage = """ Usage: <roleARN> <activityName> <stateMachineName> Where: roleName - The name of the IAM role to create for this state machine. activityName - The name of an activity to create. stateMachineName - The name of the state machine to create. """ if (args.size != 3) { println(usage) exitProcess(0) } val roleName = args[0] val activityName = args[1] val stateMachineName = args[2] val sc = Scanner(System.`in`) var action = false val polJSON = """{ "Version": "2012-10-17", "Statement": [ { "Sid": "", "Effect": "Allow", "Principal": { "Service": "states.amazonaws.com" }, "Action": "sts:AssumeRole" } ] }""" println(DASHES) println("Welcome to the AWS Step Functions example scenario.") println(DASHES) println(DASHES) println("1. List activities using a Paginator.") listActivitesPagnator() println(DASHES) println(DASHES) println("2. List state machines using a paginator.") listStatemachinesPagnator() println(DASHES) println(DASHES) println("3. Create a new activity.") val activityArn = createActivity(activityName) println("The ARN of the Activity is $activityArn") println(DASHES) // Get JSON to use for the state machine and place the activityArn value into it. val stream = GetStream() val jsonString = stream.getStream() // Modify the Resource node. val objectMapper = ObjectMapper() val root: JsonNode = objectMapper.readTree(jsonString) (root.path("States").path("GetInput") as ObjectNode).put("Resource", activityArn) // Convert the modified Java object back to a JSON string. val stateDefinition = objectMapper.writeValueAsString(root) println(stateDefinition) println(DASHES) println("4. Create a state machine.") val roleARN = createIAMRole(roleName, polJSON) val stateMachineArn = createMachine(roleARN, stateMachineName, stateDefinition) println("The ARN of the state machine is $stateMachineArn") println(DASHES) println(DASHES) println("5. Describe the state machine.") describeStateMachine(stateMachineArn) println("What should ChatSFN call you?") val userName = sc.nextLine() println("Hello $userName") println(DASHES) println(DASHES) // The JSON to pass to the StartExecution call. val executionJson = "{ \"name\" : \"$userName\" }" println(executionJson) println("6. Start execution of the state machine and interact with it.") val runArn = startWorkflow(stateMachineArn, executionJson) println("The ARN of the state machine execution is $runArn") var myList: List<String> while (!action) { myList = getActivityTask(activityArn) println("ChatSFN: " + myList[1]) println("$userName please specify a value.") val myAction = sc.nextLine() if (myAction.compareTo("done") == 0) { action = true } println("You have selected $myAction") val taskJson = "{ \"action\" : \"$myAction\" }" println(taskJson) sendTaskSuccess(myList[0], taskJson) } println(DASHES) println(DASHES) println("7. Describe the execution.") describeExe(runArn) println(DASHES) println(DASHES) println("8. Delete the activity.") deleteActivity(activityArn) println(DASHES) println(DASHES) println("9. Delete the state machines.") deleteMachine(stateMachineArn) println(DASHES) println(DASHES) println("The AWS Step Functions example scenario is complete.") println(DASHES) } suspend fun listStatemachinesPagnator() { val machineRequest = ListStateMachinesRequest { maxResults = 10 } SfnClient { region = "us-east-1" }.use { sfnClient -> sfnClient .listStateMachinesPaginated(machineRequest) .transform { it.stateMachines?.forEach { obj -> emit(obj) } } .collect { obj -> println(" The state machine ARN is ${obj.stateMachineArn}") } } } suspend fun listActivitesPagnator() { val activitiesRequest = ListActivitiesRequest { maxResults = 10 } SfnClient { region = "us-east-1" }.use { sfnClient -> sfnClient .listActivitiesPaginated(activitiesRequest) .transform { it.activities?.forEach { obj -> emit(obj) } } .collect { obj -> println(" The activity ARN is ${obj.activityArn}") } } } suspend fun deleteMachine(stateMachineArnVal: String?) { val deleteStateMachineRequest = DeleteStateMachineRequest { stateMachineArn = stateMachineArnVal } SfnClient { region = "us-east-1" }.use { sfnClient -> sfnClient.deleteStateMachine(deleteStateMachineRequest) println("$stateMachineArnVal was successfully deleted.") } } suspend fun deleteActivity(actArn: String?) { val activityRequest = DeleteActivityRequest { activityArn = actArn } SfnClient { region = "us-east-1" }.use { sfnClient -> sfnClient.deleteActivity(activityRequest) println("You have deleted $actArn") } } suspend fun describeExe(executionArnVal: String?) { val executionRequest = DescribeExecutionRequest { executionArn = executionArnVal } var status = "" var hasSucceeded = false while (!hasSucceeded) { SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.describeExecution(executionRequest) status = response.status.toString() if (status.compareTo("RUNNING") == 0) { println("The state machine is still running, let's wait for it to finish.") Thread.sleep(2000) } else if (status.compareTo("SUCCEEDED") == 0) { println("The Step Function workflow has succeeded") hasSucceeded = true } else { println("The Status is neither running or succeeded") } } } println("The Status is $status") } suspend fun sendTaskSuccess( token: String?, json: String?, ) { val successRequest = SendTaskSuccessRequest { taskToken = token output = json } SfnClient { region = "us-east-1" }.use { sfnClient -> sfnClient.sendTaskSuccess(successRequest) } } suspend fun getActivityTask(actArn: String?): List<String> { val myList: MutableList<String> = ArrayList() val getActivityTaskRequest = GetActivityTaskRequest { activityArn = actArn } SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.getActivityTask(getActivityTaskRequest) myList.add(response.taskToken.toString()) myList.add(response.input.toString()) return myList } } suspend fun startWorkflow( stateMachineArnVal: String?, jsonEx: String?, ): String? { val uuid = UUID.randomUUID() val uuidValue = uuid.toString() val executionRequest = StartExecutionRequest { input = jsonEx stateMachineArn = stateMachineArnVal name = uuidValue } SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.startExecution(executionRequest) return response.executionArn } } suspend fun describeStateMachine(stateMachineArnVal: String?) { val stateMachineRequest = DescribeStateMachineRequest { stateMachineArn = stateMachineArnVal } SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.describeStateMachine(stateMachineRequest) println("The name of the State machine is ${response.name}") println("The status of the State machine is ${response.status}") println("The ARN value of the State machine is ${response.stateMachineArn}") println("The role ARN value is ${response.roleArn}") } } suspend fun createMachine( roleARNVal: String?, stateMachineName: String?, jsonVal: String?, ): String? { val machineRequest = CreateStateMachineRequest { definition = jsonVal name = stateMachineName roleArn = roleARNVal type = StateMachineType.Standard } SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.createStateMachine(machineRequest) return response.stateMachineArn } } suspend fun createIAMRole( roleNameVal: String?, polJSON: String?, ): String? { val request = CreateRoleRequest { roleName = roleNameVal assumeRolePolicyDocument = polJSON description = "Created using the AWS SDK for Kotlin" } IamClient { region = "AWS_GLOBAL" }.use { iamClient -> val response = iamClient.createRole(request) return response.role?.arn } } suspend fun createActivity(activityName: String): String? { val activityRequest = CreateActivityRequest { name = activityName } SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.createActivity(activityRequest) return response.activityArn } }

Actions

The following code example shows how to use CreateActivity.

SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

suspend fun createActivity(activityName: String): String? { val activityRequest = CreateActivityRequest { name = activityName } SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.createActivity(activityRequest) return response.activityArn } }
  • For API details, see CreateActivity in AWS SDK for Kotlin API reference.

The following code example shows how to use CreateStateMachine.

SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

suspend fun createMachine( roleARNVal: String?, stateMachineName: String?, jsonVal: String?, ): String? { val machineRequest = CreateStateMachineRequest { definition = jsonVal name = stateMachineName roleArn = roleARNVal type = StateMachineType.Standard } SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.createStateMachine(machineRequest) return response.stateMachineArn } }

The following code example shows how to use DeleteActivity.

SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

suspend fun deleteActivity(actArn: String?) { val activityRequest = DeleteActivityRequest { activityArn = actArn } SfnClient { region = "us-east-1" }.use { sfnClient -> sfnClient.deleteActivity(activityRequest) println("You have deleted $actArn") } }
  • For API details, see DeleteActivity in AWS SDK for Kotlin API reference.

The following code example shows how to use DeleteStateMachine.

SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

suspend fun deleteMachine(stateMachineArnVal: String?) { val deleteStateMachineRequest = DeleteStateMachineRequest { stateMachineArn = stateMachineArnVal } SfnClient { region = "us-east-1" }.use { sfnClient -> sfnClient.deleteStateMachine(deleteStateMachineRequest) println("$stateMachineArnVal was successfully deleted.") } }

The following code example shows how to use DescribeExecution.

SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

suspend fun describeExe(executionArnVal: String?) { val executionRequest = DescribeExecutionRequest { executionArn = executionArnVal } var status = "" var hasSucceeded = false while (!hasSucceeded) { SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.describeExecution(executionRequest) status = response.status.toString() if (status.compareTo("RUNNING") == 0) { println("The state machine is still running, let's wait for it to finish.") Thread.sleep(2000) } else if (status.compareTo("SUCCEEDED") == 0) { println("The Step Function workflow has succeeded") hasSucceeded = true } else { println("The Status is neither running or succeeded") } } } println("The Status is $status") }

The following code example shows how to use DescribeStateMachine.

SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

suspend fun describeStateMachine(stateMachineArnVal: String?) { val stateMachineRequest = DescribeStateMachineRequest { stateMachineArn = stateMachineArnVal } SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.describeStateMachine(stateMachineRequest) println("The name of the State machine is ${response.name}") println("The status of the State machine is ${response.status}") println("The ARN value of the State machine is ${response.stateMachineArn}") println("The role ARN value is ${response.roleArn}") } }

The following code example shows how to use GetActivityTask.

SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

suspend fun getActivityTask(actArn: String?): List<String> { val myList: MutableList<String> = ArrayList() val getActivityTaskRequest = GetActivityTaskRequest { activityArn = actArn } SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.getActivityTask(getActivityTaskRequest) myList.add(response.taskToken.toString()) myList.add(response.input.toString()) return myList } }
  • For API details, see GetActivityTask in AWS SDK for Kotlin API reference.

The following code example shows how to use ListActivities.

SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

suspend fun listAllActivites() { val activitiesRequest = ListActivitiesRequest { maxResults = 10 } SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.listActivities(activitiesRequest) response.activities?.forEach { item -> println("The activity ARN is ${item.activityArn}") println("The activity name is ${item.name}") } } }
  • For API details, see ListActivities in AWS SDK for Kotlin API reference.

The following code example shows how to use ListExecutions.

SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

suspend fun getExeHistory(exeARN: String?) { val historyRequest = GetExecutionHistoryRequest { executionArn = exeARN maxResults = 10 } SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.getExecutionHistory(historyRequest) response.events?.forEach { event -> println("The event type is ${event.type}") } } }
  • For API details, see ListExecutions in AWS SDK for Kotlin API reference.

The following code example shows how to use ListStateMachines.

SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

import aws.sdk.kotlin.services.sfn.SfnClient import aws.sdk.kotlin.services.sfn.model.ListStateMachinesRequest /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main() { println(DASHES) println("Welcome to the AWS Step Functions Hello example.") println("Lets list up to ten of your state machines:") println(DASHES) listMachines() } suspend fun listMachines() { SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.listStateMachines(ListStateMachinesRequest {}) response.stateMachines?.forEach { machine -> println("The name of the state machine is ${machine.name}") println("The ARN value is ${machine.stateMachineArn}") } } }

The following code example shows how to use SendTaskSuccess.

SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

suspend fun sendTaskSuccess( token: String?, json: String?, ) { val successRequest = SendTaskSuccessRequest { taskToken = token output = json } SfnClient { region = "us-east-1" }.use { sfnClient -> sfnClient.sendTaskSuccess(successRequest) } }
  • For API details, see SendTaskSuccess in AWS SDK for Kotlin API reference.

The following code example shows how to use StartExecution.

SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

suspend fun startWorkflow( stateMachineArnVal: String?, jsonEx: String?, ): String? { val uuid = UUID.randomUUID() val uuidValue = uuid.toString() val executionRequest = StartExecutionRequest { input = jsonEx stateMachineArn = stateMachineArnVal name = uuidValue } SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.startExecution(executionRequest) return response.executionArn } }
  • For API details, see StartExecution in AWS SDK for Kotlin API reference.