使用 SDK for Kotlin 的 Step Functions 範例 - AWS SDK 程式碼範例

文件範例儲存庫中有更多 AWS SDK可用的範例。 AWS SDK GitHub

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

使用 SDK for Kotlin 的 Step Functions 範例

下列程式碼範例示範如何使用 for Kotlin 搭配 Step Functions AWS SDK來執行動作和實作常見案例。

基本知識是程式碼範例,示範如何在 服務內執行基本操作。

Actions 是大型程式的程式碼摘錄,必須在內容中執行。雖然動作會示範如何呼叫個別服務函數,但您可以在其相關案例中查看內容中的動作。

每個範例都包含完整原始程式碼的連結,您可以在其中找到如何在內容中設定和執行程式碼的指示。

開始使用

下列程式碼範例示範如何使用 Step Functions。

SDK 適用於 Kotlin
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

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}") } } }
  • 如需API詳細資訊,請參閱ListStateMachines中的 AWS SDK for Kotlin API參考

基本概念

以下程式碼範例顯示做法:

  • 建立活動。

  • 從 Amazon States 語言定義建立狀態機器,其中包含先前建立的活動作為步驟。

  • 執行 狀態機器,並使用使用者輸入回應活動。

  • 在執行完成後取得最終狀態和輸出,然後清除資源。

SDK 適用於 Kotlin
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

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 } }

動作

下列程式碼範例示範如何使用 CreateActivity

SDK 適用於 Kotlin
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

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 } }
  • 如需API詳細資訊,請參閱CreateActivity中的 AWS SDK for Kotlin API參考

下列程式碼範例示範如何使用 CreateStateMachine

SDK 適用於 Kotlin
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

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 } }
  • 如需API詳細資訊,請參閱CreateStateMachine中的 AWS SDK for Kotlin API參考

下列程式碼範例示範如何使用 DeleteActivity

SDK 適用於 Kotlin
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

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") } }
  • 如需API詳細資訊,請參閱DeleteActivity中的 AWS SDK for Kotlin API參考

下列程式碼範例示範如何使用 DeleteStateMachine

SDK 適用於 Kotlin
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

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.") } }
  • 如需API詳細資訊,請參閱DeleteStateMachine中的 AWS SDK for Kotlin API參考

下列程式碼範例示範如何使用 DescribeExecution

SDK 適用於 Kotlin
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

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") }
  • 如需API詳細資訊,請參閱DescribeExecution中的 AWS SDK for Kotlin API參考

下列程式碼範例示範如何使用 DescribeStateMachine

SDK 適用於 Kotlin
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

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}") } }

下列程式碼範例示範如何使用 GetActivityTask

SDK 適用於 Kotlin
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

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 } }
  • 如需API詳細資訊,請參閱GetActivityTask中的 AWS SDK for Kotlin API參考

下列程式碼範例示範如何使用 ListActivities

SDK 適用於 Kotlin
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

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}") } } }
  • 如需API詳細資訊,請參閱ListActivities中的 AWS SDK for Kotlin API參考

下列程式碼範例示範如何使用 ListExecutions

SDK 適用於 Kotlin
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

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}") } } }
  • 如需API詳細資訊,請參閱ListExecutions中的 AWS SDK for Kotlin API參考

下列程式碼範例示範如何使用 ListStateMachines

SDK 適用於 Kotlin
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

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}") } } }
  • 如需API詳細資訊,請參閱ListStateMachines中的 AWS SDK for Kotlin API參考

下列程式碼範例示範如何使用 SendTaskSuccess

SDK 適用於 Kotlin
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

suspend fun sendTaskSuccess( token: String?, json: String?, ) { val successRequest = SendTaskSuccessRequest { taskToken = token output = json } SfnClient { region = "us-east-1" }.use { sfnClient -> sfnClient.sendTaskSuccess(successRequest) } }
  • 如需API詳細資訊,請參閱SendTaskSuccess中的 AWS SDK for Kotlin API參考

下列程式碼範例示範如何使用 StartExecution

SDK 適用於 Kotlin
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

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 } }
  • 如需API詳細資訊,請參閱StartExecution中的 AWS SDK for Kotlin API參考