id
stringlengths
8
78
source
stringclasses
743 values
chunk_id
int64
1
5.05k
text
stringlengths
593
49.7k
step-functions-api-019
step-functions-api.pdf
19
is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. Response Elements API Version 2016-11-23 80 AWS Step Functions events The list of events that occurred in the execution. Type: Array of HistoryEvent objects nextToken API Reference If nextToken is returned, there are more results available. The value of nextToken is a unique pagination token for each page. Make the call again using the returned token to retrieve the next page. Keep all other arguments unchanged. Each pagination token expires after 24 hours. Using an expired pagination token will return an HTTP 400 InvalidToken error. Type: String Length Constraints: Minimum length of 1. Maximum length of 1024. Errors For information about the errors that are common to all actions, see Common Errors. ExecutionDoesNotExist The specified execution does not exist. HTTP Status Code: 400 InvalidArn The provided Amazon Resource Name (ARN) is not valid. HTTP Status Code: 400 InvalidToken The provided token is not valid. HTTP Status Code: 400 KmsAccessDeniedException Either your AWS KMS key policy or API caller does not have the required permissions. HTTP Status Code: 400 Errors API Version 2016-11-23 81 AWS Step Functions KmsInvalidStateException API Reference The AWS KMS key is not in valid state, for example: Disabled or Deleted. HTTP Status Code: 400 KmsThrottlingException Received when AWS KMS returns ThrottlingException for a AWS KMS call that Step Functions makes on behalf of the caller. HTTP Status Code: 400 Examples HelloWorld Execution History The following shows example output from GetExecutionHistory for a simple HelloWorld state machine, comprised of a single Pass state. Sample Response { "events": [ { "timestamp": 1525283875.58, "executionStartedEventDetails": { "input": "{}", "inputDetails": { "truncated": false }, "roleArn": "arn:aws:iam::123456789123:role/service-role/ StatesExecutionRole-us-east-1" }, "type": "ExecutionStarted", "id": 1, "previousEventId": 0 }, { "timestamp": 1525283875.612, "type": "PassStateEntered", "id": 2, Examples API Version 2016-11-23 82 AWS Step Functions API Reference "stateEnteredEventDetails": { "input": "{}", "inputDetails": { "truncated": false }, "name": "HelloWorld" }, "previousEventId": 0 }, { "timestamp": 1525283875.612, "stateExitedEventDetails": { "output": "\"Hello World!\"", "outputDetails": { "truncated": false }, "name": "HelloWorld" }, "type": "PassStateExited", "id": 3, "previousEventId": 2 }, { "executionSucceededEventDetails": { "output": "\"Hello World!\"", "outputDetails": { "truncated": false } }, "timestamp": 1525283875.612, "type": "ExecutionSucceeded", "id": 4, "previousEventId": 3 } ] } See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface See Also API Version 2016-11-23 83 API Reference AWS Step Functions • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2016-11-23 84 AWS Step Functions ListActivities Lists the existing activities. API Reference If nextToken is returned, there are more results available. The value of nextToken is a unique pagination token for each page. Make the call again using the returned token to retrieve the next page. Keep all other arguments unchanged. Each pagination token expires after 24 hours. Using an expired pagination token will return an HTTP 400 InvalidToken error. Note This operation is eventually consistent. The results are best effort and may not reflect very recent updates and changes. Request Syntax { "maxResults": number, "nextToken": "string" } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. maxResults The maximum number of results that are returned per call. You can use nextToken to obtain further pages of results. The default is 100 and the maximum allowed page size is 1000. A value of 0 uses the default. This is only an upper limit. The actual number of results returned per call might be fewer than the specified maximum. Type: Integer ListActivities API Version 2016-11-23 85 AWS Step Functions API Reference Valid Range: Minimum value of 0. Maximum value of 1000. Required: No nextToken If nextToken is returned, there are more results available. The value of nextToken is a unique pagination token for each page. Make the call again using the returned token to retrieve the next page. Keep all other arguments unchanged. Each pagination token expires after 24 hours. Using an expired pagination token will return an HTTP 400 InvalidToken error. Type: String Length Constraints: Minimum length of 1. Maximum length of 1024. Required: No Response Syntax { "activities": [ { "activityArn": "string", "creationDate": number, "name": "string" } ], "nextToken": "string" } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. activities The list of activities. Type: Array of ActivityListItem objects Response Syntax API Version 2016-11-23
step-functions-api-020
step-functions-api.pdf
20
retrieve the next page. Keep all other arguments unchanged. Each pagination token expires after 24 hours. Using an expired pagination token will return an HTTP 400 InvalidToken error. Type: String Length Constraints: Minimum length of 1. Maximum length of 1024. Required: No Response Syntax { "activities": [ { "activityArn": "string", "creationDate": number, "name": "string" } ], "nextToken": "string" } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. activities The list of activities. Type: Array of ActivityListItem objects Response Syntax API Version 2016-11-23 86 AWS Step Functions nextToken API Reference If nextToken is returned, there are more results available. The value of nextToken is a unique pagination token for each page. Make the call again using the returned token to retrieve the next page. Keep all other arguments unchanged. Each pagination token expires after 24 hours. Using an expired pagination token will return an HTTP 400 InvalidToken error. Type: String Length Constraints: Minimum length of 1. Maximum length of 1024. Errors For information about the errors that are common to all actions, see Common Errors. InvalidToken The provided token is not valid. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 Errors API Version 2016-11-23 87 AWS Step Functions API Reference See Also API Version 2016-11-23 88 AWS Step Functions ListExecutions API Reference Lists all executions of a state machine or a Map Run. You can list all executions related to a state machine by specifying a state machine Amazon Resource Name (ARN), or those related to a Map Run by specifying a Map Run ARN. Using this API action, you can also list all redriven executions. You can also provide a state machine alias ARN or version ARN to list the executions associated with a specific alias or version. Results are sorted by time, with the most recent execution first. If nextToken is returned, there are more results available. The value of nextToken is a unique pagination token for each page. Make the call again using the returned token to retrieve the next page. Keep all other arguments unchanged. Each pagination token expires after 24 hours. Using an expired pagination token will return an HTTP 400 InvalidToken error. Note This operation is eventually consistent. The results are best effort and may not reflect very recent updates and changes. This API action is not supported by EXPRESS state machines. Request Syntax { "mapRunArn": "string", "maxResults": number, "nextToken": "string", "redriveFilter": "string", "stateMachineArn": "string", "statusFilter": "string" } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. ListExecutions API Version 2016-11-23 89 AWS Step Functions mapRunArn API Reference The Amazon Resource Name (ARN) of the Map Run that started the child workflow executions. If the mapRunArn field is specified, a list of all of the child workflow executions started by a Map Run is returned. For more information, see Examining Map Run in the AWS Step Functions Developer Guide. You can specify either a mapRunArn or a stateMachineArn, but not both. Type: String Length Constraints: Minimum length of 1. Maximum length of 2000. Required: No maxResults The maximum number of results that are returned per call. You can use nextToken to obtain further pages of results. The default is 100 and the maximum allowed page size is 1000. A value of 0 uses the default. This is only an upper limit. The actual number of results returned per call might be fewer than the specified maximum. Type: Integer Valid Range: Minimum value of 0. Maximum value of 1000. Required: No nextToken If nextToken is returned, there are more results available. The value of nextToken is a unique pagination token for each page. Make the call again using the returned token to retrieve the next page. Keep all other arguments unchanged. Each pagination token expires after 24 hours. Using an expired pagination token will return an HTTP 400 InvalidToken error. Type: String Length Constraints: Minimum length of 1. Maximum length of 3096. Required: No Request Parameters API Version 2016-11-23 90 AWS Step Functions redriveFilter API Reference Sets a filter to list executions based on whether or not they have been redriven. For a Distributed Map, redriveFilter sets a filter to list child workflow executions based on whether or not they have been
step-functions-api-021
step-functions-api.pdf
21
page. Make the call again using the returned token to retrieve the next page. Keep all other arguments unchanged. Each pagination token expires after 24 hours. Using an expired pagination token will return an HTTP 400 InvalidToken error. Type: String Length Constraints: Minimum length of 1. Maximum length of 3096. Required: No Request Parameters API Version 2016-11-23 90 AWS Step Functions redriveFilter API Reference Sets a filter to list executions based on whether or not they have been redriven. For a Distributed Map, redriveFilter sets a filter to list child workflow executions based on whether or not they have been redriven. If you do not provide a redriveFilter, Step Functions returns a list of both redriven and non- redriven executions. If you provide a state machine ARN in redriveFilter, the API returns a validation exception. Type: String Valid Values: REDRIVEN | NOT_REDRIVEN Required: No stateMachineArn The Amazon Resource Name (ARN) of the state machine whose executions is listed. You can specify either a mapRunArn or a stateMachineArn, but not both. You can also return a list of executions associated with a specific alias or version, by specifying an alias ARN or a version ARN in the stateMachineArn parameter. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Required: No statusFilter If specified, only list the executions whose current execution status matches the given filter. Type: String Valid Values: RUNNING | SUCCEEDED | FAILED | TIMED_OUT | ABORTED | PENDING_REDRIVE Required: No Request Parameters API Version 2016-11-23 91 API Reference AWS Step Functions Response Syntax { "executions": [ { "executionArn": "string", "itemCount": number, "mapRunArn": "string", "name": "string", "redriveCount": number, "redriveDate": number, "startDate": number, "stateMachineAliasArn": "string", "stateMachineArn": "string", "stateMachineVersionArn": "string", "status": "string", "stopDate": number } ], "nextToken": "string" } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. executions The list of matching executions. Type: Array of ExecutionListItem objects nextToken If nextToken is returned, there are more results available. The value of nextToken is a unique pagination token for each page. Make the call again using the returned token to retrieve the next page. Keep all other arguments unchanged. Each pagination token expires after 24 hours. Using an expired pagination token will return an HTTP 400 InvalidToken error. Type: String Response Syntax API Version 2016-11-23 92 AWS Step Functions API Reference Length Constraints: Minimum length of 1. Maximum length of 3096. Errors For information about the errors that are common to all actions, see Common Errors. InvalidArn The provided Amazon Resource Name (ARN) is not valid. HTTP Status Code: 400 InvalidToken The provided token is not valid. HTTP Status Code: 400 ResourceNotFound Could not find the referenced resource. HTTP Status Code: 400 StateMachineDoesNotExist The specified state machine does not exist. HTTP Status Code: 400 StateMachineTypeNotSupported State machine type is not supported. HTTP Status Code: 400 ValidationException The input does not satisfy the constraints specified by an AWS service. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: Errors API Version 2016-11-23 93 API Reference AWS Step Functions • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2016-11-23 94 AWS Step Functions ListMapRuns API Reference Lists all Map Runs that were started by a given state machine execution. Use this API action to obtain Map Run ARNs, and then call DescribeMapRun to obtain more information, if needed. Request Syntax { "executionArn": "string", "maxResults": number, "nextToken": "string" } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. executionArn The Amazon Resource Name (ARN) of the execution for which the Map Runs must be listed. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Required: Yes maxResults The maximum number of results that are returned per call. You can use nextToken to obtain further pages of results. The default is 100 and the maximum allowed page size is 1000. A value of 0 uses the default. This is only an upper limit. The actual number of results returned per call might be fewer than the specified maximum. Type: Integer Valid Range: Minimum value of 0. Maximum value of 1000. ListMapRuns API Version 2016-11-23 95 AWS Step Functions Required: No nextToken API Reference If nextToken is returned, there are more results available. The value of nextToken is a unique pagination token for each
step-functions-api-022
step-functions-api.pdf
22
that are returned per call. You can use nextToken to obtain further pages of results. The default is 100 and the maximum allowed page size is 1000. A value of 0 uses the default. This is only an upper limit. The actual number of results returned per call might be fewer than the specified maximum. Type: Integer Valid Range: Minimum value of 0. Maximum value of 1000. ListMapRuns API Version 2016-11-23 95 AWS Step Functions Required: No nextToken API Reference If nextToken is returned, there are more results available. The value of nextToken is a unique pagination token for each page. Make the call again using the returned token to retrieve the next page. Keep all other arguments unchanged. Each pagination token expires after 24 hours. Using an expired pagination token will return an HTTP 400 InvalidToken error. Type: String Length Constraints: Minimum length of 1. Maximum length of 1024. Required: No Response Syntax { "mapRuns": [ { "executionArn": "string", "mapRunArn": "string", "startDate": number, "stateMachineArn": "string", "stopDate": number } ], "nextToken": "string" } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. mapRuns An array that lists information related to a Map Run, such as the Amazon Resource Name (ARN) of the Map Run and the ARN of the state machine that started the Map Run. Type: Array of MapRunListItem objects Response Syntax API Version 2016-11-23 96 AWS Step Functions nextToken API Reference If nextToken is returned, there are more results available. The value of nextToken is a unique pagination token for each page. Make the call again using the returned token to retrieve the next page. Keep all other arguments unchanged. Each pagination token expires after 24 hours. Using an expired pagination token will return an HTTP 400 InvalidToken error. Type: String Length Constraints: Minimum length of 1. Maximum length of 1024. Errors For information about the errors that are common to all actions, see Common Errors. ExecutionDoesNotExist The specified execution does not exist. HTTP Status Code: 400 InvalidArn The provided Amazon Resource Name (ARN) is not valid. HTTP Status Code: 400 InvalidToken The provided token is not valid. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ Errors API Version 2016-11-23 97 AWS Step Functions • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 API Reference See Also API Version 2016-11-23 98 AWS Step Functions API Reference ListStateMachineAliases Lists aliases for a specified state machine ARN. Results are sorted by time, with the most recently created aliases listed first. To list aliases that reference a state machine version, you can specify the version ARN in the stateMachineArn parameter. If nextToken is returned, there are more results available. The value of nextToken is a unique pagination token for each page. Make the call again using the returned token to retrieve the next page. Keep all other arguments unchanged. Each pagination token expires after 24 hours. Using an expired pagination token will return an HTTP 400 InvalidToken error. Related operations: • CreateStateMachineAlias • DescribeStateMachineAlias • UpdateStateMachineAlias • DeleteStateMachineAlias Request Syntax { "maxResults": number, "nextToken": "string", "stateMachineArn": "string" } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. maxResults The maximum number of results that are returned per call. You can use nextToken to obtain further pages of results. The default is 100 and the maximum allowed page size is 1000. A value of 0 uses the default. ListStateMachineAliases API Version 2016-11-23 99 AWS Step Functions API Reference This is only an upper limit. The actual number of results returned per call might be fewer than the specified maximum. Type: Integer Valid Range: Minimum value of 0. Maximum value of 1000. Required: No nextToken If nextToken is returned, there are more results available. The value of nextToken is a unique pagination token for each page. Make the call again using the returned token to retrieve the next page. Keep all other arguments unchanged. Each pagination token expires after 24 hours. Using an expired pagination token will return an HTTP 400 InvalidToken error. Type: String Length Constraints: Minimum length of 1. Maximum length of 1024. Required: No stateMachineArn The Amazon Resource Name (ARN) of the state machine for which you want to list aliases. If you specify a state machine version ARN, this API returns a list of aliases
step-functions-api-023
step-functions-api.pdf
23
there are more results available. The value of nextToken is a unique pagination token for each page. Make the call again using the returned token to retrieve the next page. Keep all other arguments unchanged. Each pagination token expires after 24 hours. Using an expired pagination token will return an HTTP 400 InvalidToken error. Type: String Length Constraints: Minimum length of 1. Maximum length of 1024. Required: No stateMachineArn The Amazon Resource Name (ARN) of the state machine for which you want to list aliases. If you specify a state machine version ARN, this API returns a list of aliases for that version. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Required: Yes Response Syntax { "nextToken": "string", "stateMachineAliases": [ { "creationDate": number, "stateMachineAliasArn": "string" Response Syntax API Version 2016-11-23 100 AWS Step Functions } ] } Response Elements API Reference If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. nextToken If nextToken is returned, there are more results available. The value of nextToken is a unique pagination token for each page. Make the call again using the returned token to retrieve the next page. Keep all other arguments unchanged. Each pagination token expires after 24 hours. Using an expired pagination token will return an HTTP 400 InvalidToken error. Type: String Length Constraints: Minimum length of 1. Maximum length of 1024. stateMachineAliases Aliases for the state machine. Type: Array of StateMachineAliasListItem objects Errors For information about the errors that are common to all actions, see Common Errors. InvalidArn The provided Amazon Resource Name (ARN) is not valid. HTTP Status Code: 400 InvalidToken The provided token is not valid. HTTP Status Code: 400 Response Elements API Version 2016-11-23 101 API Reference AWS Step Functions ResourceNotFound Could not find the referenced resource. HTTP Status Code: 400 StateMachineDeleting The specified state machine is being deleted. HTTP Status Code: 400 StateMachineDoesNotExist The specified state machine does not exist. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2016-11-23 102 AWS Step Functions ListStateMachines Lists the existing state machines. API Reference If nextToken is returned, there are more results available. The value of nextToken is a unique pagination token for each page. Make the call again using the returned token to retrieve the next page. Keep all other arguments unchanged. Each pagination token expires after 24 hours. Using an expired pagination token will return an HTTP 400 InvalidToken error. Note This operation is eventually consistent. The results are best effort and may not reflect very recent updates and changes. Request Syntax { "maxResults": number, "nextToken": "string" } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. maxResults The maximum number of results that are returned per call. You can use nextToken to obtain further pages of results. The default is 100 and the maximum allowed page size is 1000. A value of 0 uses the default. This is only an upper limit. The actual number of results returned per call might be fewer than the specified maximum. Type: Integer Valid Range: Minimum value of 0. Maximum value of 1000. ListStateMachines API Version 2016-11-23 103 AWS Step Functions Required: No nextToken API Reference If nextToken is returned, there are more results available. The value of nextToken is a unique pagination token for each page. Make the call again using the returned token to retrieve the next page. Keep all other arguments unchanged. Each pagination token expires after 24 hours. Using an expired pagination token will return an HTTP 400 InvalidToken error. Type: String Length Constraints: Minimum length of 1. Maximum length of 1024. Required: No Response Syntax { "nextToken": "string", "stateMachines": [ { "creationDate": number, "name": "string", "stateMachineArn": "string", "type": "string" } ] } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. nextToken If nextToken is returned, there are more results available. The value of nextToken is a unique pagination token for each page. Make the call again using the returned token to retrieve the next page. Keep all other arguments unchanged. Each pagination token expires after 24 hours. Using an expired pagination token will return an HTTP 400 InvalidToken
step-functions-api-024
step-functions-api.pdf
24
"nextToken": "string", "stateMachines": [ { "creationDate": number, "name": "string", "stateMachineArn": "string", "type": "string" } ] } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. nextToken If nextToken is returned, there are more results available. The value of nextToken is a unique pagination token for each page. Make the call again using the returned token to retrieve the next page. Keep all other arguments unchanged. Each pagination token expires after 24 hours. Using an expired pagination token will return an HTTP 400 InvalidToken error. Response Syntax API Version 2016-11-23 104 AWS Step Functions Type: String API Reference Length Constraints: Minimum length of 1. Maximum length of 1024. stateMachines Type: Array of StateMachineListItem objects Errors For information about the errors that are common to all actions, see Common Errors. InvalidToken The provided token is not valid. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 Errors API Version 2016-11-23 105 AWS Step Functions API Reference ListStateMachineVersions Lists versions for the specified state machine Amazon Resource Name (ARN). The results are sorted in descending order of the version creation time. If nextToken is returned, there are more results available. The value of nextToken is a unique pagination token for each page. Make the call again using the returned token to retrieve the next page. Keep all other arguments unchanged. Each pagination token expires after 24 hours. Using an expired pagination token will return an HTTP 400 InvalidToken error. Related operations: • PublishStateMachineVersion • DeleteStateMachineVersion Request Syntax { "maxResults": number, "nextToken": "string", "stateMachineArn": "string" } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. maxResults The maximum number of results that are returned per call. You can use nextToken to obtain further pages of results. The default is 100 and the maximum allowed page size is 1000. A value of 0 uses the default. This is only an upper limit. The actual number of results returned per call might be fewer than the specified maximum. Type: Integer ListStateMachineVersions API Version 2016-11-23 106 AWS Step Functions API Reference Valid Range: Minimum value of 0. Maximum value of 1000. Required: No nextToken If nextToken is returned, there are more results available. The value of nextToken is a unique pagination token for each page. Make the call again using the returned token to retrieve the next page. Keep all other arguments unchanged. Each pagination token expires after 24 hours. Using an expired pagination token will return an HTTP 400 InvalidToken error. Type: String Length Constraints: Minimum length of 1. Maximum length of 1024. Required: No stateMachineArn The Amazon Resource Name (ARN) of the state machine. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Required: Yes Response Syntax { "nextToken": "string", "stateMachineVersions": [ { "creationDate": number, "stateMachineVersionArn": "string" } ] } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. Response Syntax API Version 2016-11-23 107 AWS Step Functions nextToken API Reference If nextToken is returned, there are more results available. The value of nextToken is a unique pagination token for each page. Make the call again using the returned token to retrieve the next page. Keep all other arguments unchanged. Each pagination token expires after 24 hours. Using an expired pagination token will return an HTTP 400 InvalidToken error. Type: String Length Constraints: Minimum length of 1. Maximum length of 1024. stateMachineVersions Versions for the state machine. Type: Array of StateMachineVersionListItem objects Errors For information about the errors that are common to all actions, see Common Errors. InvalidArn The provided Amazon Resource Name (ARN) is not valid. HTTP Status Code: 400 InvalidToken The provided token is not valid. HTTP Status Code: 400 ValidationException The input does not satisfy the constraints specified by an AWS service. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: Errors API Version 2016-11-23 108 API Reference AWS Step Functions • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS
step-functions-api-025
step-functions-api.pdf
25
(ARN) is not valid. HTTP Status Code: 400 InvalidToken The provided token is not valid. HTTP Status Code: 400 ValidationException The input does not satisfy the constraints specified by an AWS service. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: Errors API Version 2016-11-23 108 API Reference AWS Step Functions • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2016-11-23 109 AWS Step Functions API Reference ListTagsForResource List tags for a given resource. Tags may only contain Unicode letters, digits, white space, or these symbols: _ . : / = + - @. Request Syntax { "resourceArn": "string" } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. resourceArn The Amazon Resource Name (ARN) for the Step Functions state machine or activity. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Required: Yes Response Syntax { "tags": [ { "key": "string", "value": "string" } ] } ListTagsForResource API Version 2016-11-23 110 AWS Step Functions Response Elements API Reference If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. tags An array of tags associated with the resource. Type: Array of Tag objects Errors For information about the errors that are common to all actions, see Common Errors. InvalidArn The provided Amazon Resource Name (ARN) is not valid. HTTP Status Code: 400 ResourceNotFound Could not find the referenced resource. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 Response Elements API Version 2016-11-23 111 AWS Step Functions • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 API Reference See Also API Version 2016-11-23 112 AWS Step Functions API Reference PublishStateMachineVersion Creates a version from the current revision of a state machine. Use versions to create immutable snapshots of your state machine. You can start executions from versions either directly or with an alias. To create an alias, use CreateStateMachineAlias. You can publish up to 1000 versions for each state machine. You must manually delete unused versions using the DeleteStateMachineVersion API action. PublishStateMachineVersion is an idempotent API. It doesn't create a duplicate state machine version if it already exists for the current revision. Step Functions bases PublishStateMachineVersion's idempotency check on the stateMachineArn, name, and revisionId parameters. Requests with the same parameters return a successful idempotent response. If you don't specify a revisionId, Step Functions checks for a previously published version of the state machine's current revision. Related operations: • DeleteStateMachineVersion • ListStateMachineVersions Request Syntax { "description": "string", "revisionId": "string", "stateMachineArn": "string" } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. description An optional description of the state machine version. Type: String PublishStateMachineVersion API Version 2016-11-23 113 AWS Step Functions API Reference Length Constraints: Maximum length of 256. Required: No revisionId Only publish the state machine version if the current state machine's revision ID matches the specified ID. Use this option to avoid publishing a version if the state machine changed since you last updated it. If the specified revision ID doesn't match the state machine's current revision ID, the API returns ConflictException. Note To specify an initial revision ID for a state machine with no revision ID assigned, specify the string INITIAL for the revisionId parameter. For example, you can specify a revisionID of INITIAL when you create a state machine using the CreateStateMachine API action. Type: String Required: No stateMachineArn The Amazon Resource Name (ARN) of the state machine. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Required: Yes Response Syntax { "creationDate": number, "stateMachineVersionArn": "string" } Response Syntax API Version 2016-11-23 114 AWS Step Functions Response Elements API Reference If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. creationDate The date the version was created. Type: Timestamp stateMachineVersionArn The Amazon Resource Name (ARN) (ARN) that identifies
step-functions-api-026
step-functions-api.pdf
26
create a state machine using the CreateStateMachine API action. Type: String Required: No stateMachineArn The Amazon Resource Name (ARN) of the state machine. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Required: Yes Response Syntax { "creationDate": number, "stateMachineVersionArn": "string" } Response Syntax API Version 2016-11-23 114 AWS Step Functions Response Elements API Reference If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. creationDate The date the version was created. Type: Timestamp stateMachineVersionArn The Amazon Resource Name (ARN) (ARN) that identifies the state machine version. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Errors For information about the errors that are common to all actions, see Common Errors. ConflictException Updating or deleting a resource can cause an inconsistent state. This error occurs when there're concurrent requests for DeleteStateMachineVersion, PublishStateMachineVersion, or UpdateStateMachine with the publish parameter set to true. HTTP Status Code: 409 HTTP Status Code: 400 InvalidArn The provided Amazon Resource Name (ARN) is not valid. HTTP Status Code: 400 ServiceQuotaExceededException The request would cause a service quota to be exceeded. Response Elements API Version 2016-11-23 115 API Reference AWS Step Functions HTTP Status Code: 402 HTTP Status Code: 400 StateMachineDeleting The specified state machine is being deleted. HTTP Status Code: 400 StateMachineDoesNotExist The specified state machine does not exist. HTTP Status Code: 400 ValidationException The input does not satisfy the constraints specified by an AWS service. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2016-11-23 116 AWS Step Functions RedriveExecution API Reference Restarts unsuccessful executions of Standard workflows that didn't complete successfully in the last 14 days. These include failed, aborted, or timed out executions. When you redrive an execution, it continues the failed execution from the unsuccessful step and uses the same input. Step Functions preserves the results and execution history of the successful steps, and doesn't rerun these steps when you redrive an execution. Redriven executions use the same state machine definition and execution ARN as the original execution attempt. For workflows that include an Inline Map or Parallel state, RedriveExecution API action reschedules and redrives only the iterations and branches that failed or aborted. To redrive a workflow that includes a Distributed Map state whose Map Run failed, you must redrive the parent workflow. The parent workflow redrives all the unsuccessful states, including a failed Map Run. If a Map Run was not started in the original execution attempt, the redriven parent workflow starts the Map Run. Note This API action is not supported by EXPRESS state machines. However, you can restart the unsuccessful executions of Express child workflows in a Distributed Map by redriving its Map Run. When you redrive a Map Run, the Express child workflows are rerun using the StartExecution API action. For more information, see Redriving Map Runs. You can redrive executions if your original execution meets the following conditions: • The execution status isn't SUCCEEDED. • Your workflow execution has not exceeded the redrivable period of 14 days. Redrivable period refers to the time during which you can redrive a given execution. This period starts from the day a state machine completes its execution. • The workflow execution has not exceeded the maximum open time of one year. For more information about state machine quotas, see Quotas related to state machine executions. • The execution event history count is less than 24,999. Redriven executions append their event history to the existing event history. Make sure your workflow execution contains less than 24,999 events to accommodate the ExecutionRedriven history event and at least one other history event. RedriveExecution API Version 2016-11-23 117 AWS Step Functions Request Syntax { "clientToken": "string", "executionArn": "string" } Request Parameters API Reference For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. clientToken A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. If you don’t specify a client token, the AWS SDK automatically generates a client token and uses it for the request to ensure idempotency. The API will return idempotent responses for the last 10 client tokens used to successfully redrive the execution. These client tokens are valid for up to 15 minutes after they are first used. Type: String Length
step-functions-api-027
step-functions-api.pdf
27
API Reference For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. clientToken A unique, case-sensitive identifier that you provide to ensure the idempotency of the request. If you don’t specify a client token, the AWS SDK automatically generates a client token and uses it for the request to ensure idempotency. The API will return idempotent responses for the last 10 client tokens used to successfully redrive the execution. These client tokens are valid for up to 15 minutes after they are first used. Type: String Length Constraints: Minimum length of 1. Maximum length of 64. Pattern: [!-~]+ Required: No executionArn The Amazon Resource Name (ARN) of the execution to be redriven. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Required: Yes Response Syntax { Request Syntax API Version 2016-11-23 118 AWS Step Functions "redriveDate": number } Response Elements API Reference If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. redriveDate The date the execution was last redriven. Type: Timestamp Errors For information about the errors that are common to all actions, see Common Errors. ExecutionDoesNotExist The specified execution does not exist. HTTP Status Code: 400 ExecutionLimitExceeded The maximum number of running executions has been reached. Running executions must end or be stopped before a new execution can be started. HTTP Status Code: 400 ExecutionNotRedrivable The execution Amazon Resource Name (ARN) that you specified for executionArn cannot be redriven. HTTP Status Code: 400 InvalidArn The provided Amazon Resource Name (ARN) is not valid. HTTP Status Code: 400 Response Elements API Version 2016-11-23 119 AWS Step Functions ValidationException API Reference The input does not satisfy the constraints specified by an AWS service. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2016-11-23 120 AWS Step Functions SendTaskFailure API Reference Used by activity workers, Task states using the callback pattern, and optionally Task states using the job run pattern to report that the task identified by the taskToken failed. For an execution with encryption enabled, Step Functions will encrypt the error and cause fields using the AWS KMS key for the execution role. A caller can mark a task as fail without using any AWS KMS permissions in the execution role if the caller provides a null value for both error and cause fields because no data needs to be encrypted. Request Syntax { "cause": "string", "error": "string", "taskToken": "string" } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. cause A more detailed explanation of the cause of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 32768. Required: No error The error code of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 256. SendTaskFailure API Version 2016-11-23 121 AWS Step Functions Required: No taskToken API Reference The token that represents this task. Task tokens are generated by Step Functions when tasks are assigned to a worker, or in the context object when a workflow enters a task state. See GetActivityTask:taskToken. Type: String Length Constraints: Minimum length of 1. Maximum length of 2048. Required: Yes Response Elements If the action is successful, the service sends back an HTTP 200 response with an empty HTTP body. Errors For information about the errors that are common to all actions, see Common Errors. InvalidToken The provided token is not valid. HTTP Status Code: 400 KmsAccessDeniedException Either your AWS KMS key policy or API caller does not have the required permissions. HTTP Status Code: 400 KmsInvalidStateException The AWS KMS key is not in valid state, for example: Disabled or Deleted. HTTP Status Code: 400 KmsThrottlingException Received when AWS KMS returns ThrottlingException for a AWS KMS call that Step Functions makes on behalf of the caller. Response Elements API Version 2016-11-23 122 AWS Step Functions HTTP Status Code: 400 TaskDoesNotExist The activity does not exist. HTTP Status Code: 400 TaskTimedOut API Reference The task token has either expired or the task associated with the token has already been closed. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line
step-functions-api-028
step-functions-api.pdf
28
for example: Disabled or Deleted. HTTP Status Code: 400 KmsThrottlingException Received when AWS KMS returns ThrottlingException for a AWS KMS call that Step Functions makes on behalf of the caller. Response Elements API Version 2016-11-23 122 AWS Step Functions HTTP Status Code: 400 TaskDoesNotExist The activity does not exist. HTTP Status Code: 400 TaskTimedOut API Reference The task token has either expired or the task associated with the token has already been closed. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2016-11-23 123 AWS Step Functions SendTaskHeartbeat API Reference Used by activity workers and Task states using the callback pattern, and optionally Task states using the job run pattern to report to Step Functions that the task represented by the specified taskToken is still making progress. This action resets the Heartbeat clock. The Heartbeat threshold is specified in the state machine's Amazon States Language definition (HeartbeatSeconds). This action does not in itself create an event in the execution history. However, if the task times out, the execution history contains an ActivityTimedOut entry for activities, or a TaskTimedOut entry for tasks using the job run or callback pattern. Note The Timeout of a task, defined in the state machine's Amazon States Language definition, is its maximum allowed duration, regardless of the number of SendTaskHeartbeat requests received. Use HeartbeatSeconds to configure the timeout interval for heartbeats. Request Syntax { "taskToken": "string" } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. taskToken The token that represents this task. Task tokens are generated by Step Functions when tasks are assigned to a worker, or in the context object when a workflow enters a task state. See GetActivityTask:taskToken. Type: String Length Constraints: Minimum length of 1. Maximum length of 2048. SendTaskHeartbeat API Version 2016-11-23 124 AWS Step Functions Required: Yes Response Elements API Reference If the action is successful, the service sends back an HTTP 200 response with an empty HTTP body. Errors For information about the errors that are common to all actions, see Common Errors. InvalidToken The provided token is not valid. HTTP Status Code: 400 TaskDoesNotExist The activity does not exist. HTTP Status Code: 400 TaskTimedOut The task token has either expired or the task associated with the token has already been closed. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin Response Elements API Version 2016-11-23 125 AWS Step Functions • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 API Reference See Also API Version 2016-11-23 126 AWS Step Functions SendTaskSuccess API Reference Used by activity workers, Task states using the callback pattern, and optionally Task states using the job run pattern to report that the task identified by the taskToken completed successfully. Request Syntax { "output": "string", "taskToken": "string" } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. output The JSON output of the task. Length constraints apply to the payload size, and are expressed as bytes in UTF-8 encoding. Type: String Length Constraints: Maximum length of 262144. Required: Yes taskToken The token that represents this task. Task tokens are generated by Step Functions when tasks are assigned to a worker, or in the context object when a workflow enters a task state. See GetActivityTask:taskToken. Type: String Length Constraints: Minimum length of 1. Maximum length of 2048. Required: Yes SendTaskSuccess API Version 2016-11-23 127 AWS Step Functions Response Elements API Reference If the action is successful, the service sends back an HTTP 200 response with an empty HTTP body. Errors For information about the errors that are common to all actions, see Common Errors. InvalidOutput The provided JSON output data is not valid. HTTP Status Code: 400 InvalidToken The provided token is not valid. HTTP Status Code: 400 KmsAccessDeniedException Either your AWS KMS key policy or API caller does not have the required permissions. HTTP Status Code: 400 KmsInvalidStateException The AWS KMS
step-functions-api-029
step-functions-api.pdf
29
1. Maximum length of 2048. Required: Yes SendTaskSuccess API Version 2016-11-23 127 AWS Step Functions Response Elements API Reference If the action is successful, the service sends back an HTTP 200 response with an empty HTTP body. Errors For information about the errors that are common to all actions, see Common Errors. InvalidOutput The provided JSON output data is not valid. HTTP Status Code: 400 InvalidToken The provided token is not valid. HTTP Status Code: 400 KmsAccessDeniedException Either your AWS KMS key policy or API caller does not have the required permissions. HTTP Status Code: 400 KmsInvalidStateException The AWS KMS key is not in valid state, for example: Disabled or Deleted. HTTP Status Code: 400 KmsThrottlingException Received when AWS KMS returns ThrottlingException for a AWS KMS call that Step Functions makes on behalf of the caller. HTTP Status Code: 400 TaskDoesNotExist The activity does not exist. HTTP Status Code: 400 TaskTimedOut The task token has either expired or the task associated with the token has already been closed. Response Elements API Version 2016-11-23 128 AWS Step Functions HTTP Status Code: 400 See Also API Reference For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2016-11-23 129 AWS Step Functions StartExecution Starts a state machine execution. API Reference A qualified state machine ARN can either refer to a Distributed Map state defined within a state machine, a version ARN, or an alias ARN. The following are some examples of qualified and unqualified state machine ARNs: • The following qualified state machine ARN refers to a Distributed Map state with a label mapStateLabel in a state machine named myStateMachine. arn:partition:states:region:account-id:stateMachine:myStateMachine/ mapStateLabel Note If you provide a qualified state machine ARN that refers to a Distributed Map state, the request fails with ValidationException. • The following qualified state machine ARN refers to an alias named PROD. arn:<partition>:states:<region>:<account- id>:stateMachine:<myStateMachine:PROD> Note If you provide a qualified state machine ARN that refers to a version ARN or an alias ARN, the request starts execution for that version or alias. • The following unqualified state machine ARN refers to a state machine named myStateMachine. arn:<partition>:states:<region>:<account- id>:stateMachine:<myStateMachine> If you start an execution with an unqualified state machine ARN, Step Functions uses the latest revision of the state machine for the execution. StartExecution API Version 2016-11-23 130 AWS Step Functions API Reference To start executions of a state machine version, call StartExecution and provide the version ARN or the ARN of an alias that points to the version. Note StartExecution is idempotent for STANDARD workflows. For a STANDARD workflow, if you call StartExecution with the same name and input as a running execution, the call succeeds and return the same response as the original request. If the execution is closed or if the input is different, it returns a 400 ExecutionAlreadyExists error. You can reuse names after 90 days. StartExecution isn't idempotent for EXPRESS workflows. Request Syntax { "input": "string", "name": "string", "stateMachineArn": "string", "traceHeader": "string" } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. input The string that contains the JSON input data for the execution, for example: "input": "{\"first_name\" : \"test\"}" Note If you don't include any JSON input data, you still must include the two braces, for example: "input": "{}" Request Syntax API Version 2016-11-23 131 AWS Step Functions API Reference Length constraints apply to the payload size, and are expressed as bytes in UTF-8 encoding. Type: String Length Constraints: Maximum length of 262144. Required: No name Optional name of the execution. This name must be unique for your AWS account, Region, and state machine for 90 days. For more information, see Limits Related to State Machine Executions in the AWS Step Functions Developer Guide. If you don't provide a name for the execution, Step Functions automatically generates a universally unique identifier (UUID) as the execution name. A name must not contain: • white space • brackets < > { } [ ] • wildcard characters ? * • special characters " # % \ ^ | ~ ` $ & , ; : / • control characters (U+0000-001F, U+007F-009F, U+FFFE-FFFF) • surrogates (U+D800-DFFF) • invalid characters ( U+10FFFF) To enable logging with CloudWatch Logs, the name should only contain 0-9, A-Z, a-z, - and _. Type: String Length Constraints: Minimum length of 1. Maximum length of 80. Required: No stateMachineArn The
step-functions-api-030
step-functions-api.pdf
30
the execution, Step Functions automatically generates a universally unique identifier (UUID) as the execution name. A name must not contain: • white space • brackets < > { } [ ] • wildcard characters ? * • special characters " # % \ ^ | ~ ` $ & , ; : / • control characters (U+0000-001F, U+007F-009F, U+FFFE-FFFF) • surrogates (U+D800-DFFF) • invalid characters ( U+10FFFF) To enable logging with CloudWatch Logs, the name should only contain 0-9, A-Z, a-z, - and _. Type: String Length Constraints: Minimum length of 1. Maximum length of 80. Required: No stateMachineArn The Amazon Resource Name (ARN) of the state machine to execute. The stateMachineArn parameter accepts one of the following inputs: • An unqualified state machine ARN – Refers to a state machine ARN that isn't qualified with a version or alias ARN. The following is an example of an unqualified state machine ARN. Request Parameters API Version 2016-11-23 132 AWS Step Functions API Reference arn:<partition>:states:<region>:<account- id>:stateMachine:<myStateMachine> Step Functions doesn't associate state machine executions that you start with an unqualified ARN with a version. This is true even if that version uses the same revision that the execution used. • A state machine version ARN – Refers to a version ARN, which is a combination of state machine ARN and the version number separated by a colon (:). The following is an example of the ARN for version 10. arn:<partition>:states:<region>:<account- id>:stateMachine:<myStateMachine>:10 Step Functions doesn't associate executions that you start with a version ARN with any aliases that point to that version. • A state machine alias ARN – Refers to an alias ARN, which is a combination of state machine ARN and the alias name separated by a colon (:). The following is an example of the ARN for an alias named PROD. arn:<partition>:states:<region>:<account- id>:stateMachine:<myStateMachine:PROD> Step Functions associates executions that you start with an alias ARN with that alias and the state machine version used for that execution. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Required: Yes traceHeader Passes the AWS X-Ray trace header. The trace header can also be passed in the request payload. Note For X-Ray traces, all AWS services use the X-Amzn-Trace-Id header from the HTTP request. Using the header is the preferred mechanism to identify a trace. StartExecution and StartSyncExecution API operations can also use Request Parameters API Version 2016-11-23 133 AWS Step Functions API Reference traceHeader from the body of the request payload. If both sources are provided, Step Functions will use the header value (preferred) over the value in the request body. Type: String Length Constraints: Minimum length of 0. Maximum length of 256. Pattern: \p{ASCII}* Required: No Response Syntax { "executionArn": "string", "startDate": number } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. executionArn The Amazon Resource Name (ARN) that identifies the execution. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. startDate The date the execution is started. Type: Timestamp Errors For information about the errors that are common to all actions, see Common Errors. Response Syntax API Version 2016-11-23 134 AWS Step Functions ExecutionAlreadyExists API Reference The execution has the same name as another execution (but a different input). Note Executions with the same name and input are considered idempotent. HTTP Status Code: 400 ExecutionLimitExceeded The maximum number of running executions has been reached. Running executions must end or be stopped before a new execution can be started. HTTP Status Code: 400 InvalidArn The provided Amazon Resource Name (ARN) is not valid. HTTP Status Code: 400 InvalidExecutionInput The provided JSON input data is not valid. HTTP Status Code: 400 InvalidName The provided name is not valid. HTTP Status Code: 400 KmsAccessDeniedException Either your AWS KMS key policy or API caller does not have the required permissions. HTTP Status Code: 400 KmsInvalidStateException The AWS KMS key is not in valid state, for example: Disabled or Deleted. HTTP Status Code: 400 Errors API Version 2016-11-23 135 AWS Step Functions KmsThrottlingException API Reference Received when AWS KMS returns ThrottlingException for a AWS KMS call that Step Functions makes on behalf of the caller. HTTP Status Code: 400 StateMachineDeleting The specified state machine is being deleted. HTTP Status Code: 400 StateMachineDoesNotExist The specified state machine does not exist. HTTP Status Code: 400 ValidationException The input does not satisfy the constraints specified by an AWS service. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3
step-functions-api-031
step-functions-api.pdf
31
of the caller. HTTP Status Code: 400 StateMachineDeleting The specified state machine is being deleted. HTTP Status Code: 400 StateMachineDoesNotExist The specified state machine does not exist. HTTP Status Code: 400 ValidationException The input does not satisfy the constraints specified by an AWS service. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2016-11-23 136 AWS Step Functions API Reference See Also API Version 2016-11-23 137 AWS Step Functions StartSyncExecution API Reference Starts a Synchronous Express state machine execution. StartSyncExecution is not available for STANDARD workflows. Note StartSyncExecution will return a 200 OK response, even if your execution fails, because the status code in the API response doesn't reflect function errors. Error codes are reserved for errors that prevent your execution from running, such as permissions errors, limit errors, or issues with your state machine code and configuration. Note This API action isn't logged in CloudTrail. Request Syntax { "includedData": "string", "input": "string", "name": "string", "stateMachineArn": "string", "traceHeader": "string" } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. includedData If your state machine definition is encrypted with a AWS KMS key, callers must have kms:Decrypt permission to decrypt the definition. Alternatively, you can call the API with StartSyncExecution API Version 2016-11-23 138 AWS Step Functions API Reference includedData = METADATA_ONLY to get a successful response without the encrypted definition. Type: String Valid Values: ALL_DATA | METADATA_ONLY Required: No input The string that contains the JSON input data for the execution, for example: "input": "{\"first_name\" : \"test\"}" Note If you don't include any JSON input data, you still must include the two braces, for example: "input": "{}" Length constraints apply to the payload size, and are expressed as bytes in UTF-8 encoding. Type: String Length Constraints: Maximum length of 262144. Required: No name The name of the execution. Type: String Length Constraints: Minimum length of 1. Maximum length of 80. Required: No stateMachineArn The Amazon Resource Name (ARN) of the state machine to execute. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Request Parameters API Version 2016-11-23 139 AWS Step Functions Required: Yes traceHeader API Reference Passes the AWS X-Ray trace header. The trace header can also be passed in the request payload. Note For X-Ray traces, all AWS services use the X-Amzn-Trace-Id header from the HTTP request. Using the header is the preferred mechanism to identify a trace. StartExecution and StartSyncExecution API operations can also use traceHeader from the body of the request payload. If both sources are provided, Step Functions will use the header value (preferred) over the value in the request body. Type: String Length Constraints: Minimum length of 0. Maximum length of 256. Pattern: \p{ASCII}* Required: No Response Syntax { "billingDetails": { "billedDurationInMilliseconds": number, "billedMemoryUsedInMB": number }, "cause": "string", "error": "string", "executionArn": "string", "input": "string", "inputDetails": { "included": boolean }, "name": "string", "output": "string", "outputDetails": { "included": boolean }, Response Syntax API Version 2016-11-23 140 AWS Step Functions API Reference "startDate": number, "stateMachineArn": "string", "status": "string", "stopDate": number, "traceHeader": "string" } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. billingDetails An object that describes workflow billing details, including billed duration and memory use. Type: BillingDetails object cause A more detailed explanation of the cause of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 32768. error The error code of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 256. executionArn The Amazon Resource Name (ARN) that identifies the execution. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. input The string that contains the JSON input data of the execution. Length constraints apply to the payload size, and are expressed as bytes in UTF-8 encoding. Response Elements API Version 2016-11-23 141 API Reference AWS Step Functions Type: String Length Constraints: Maximum length of 262144. inputDetails Provides details about execution input or output. Type: CloudWatchEventsExecutionDataDetails object name The name of the execution. Type: String Length Constraints: Minimum length of 1. Maximum length of 80. output The JSON output data of the execution. Length constraints apply to the payload size, and are expressed as bytes in UTF-8 encoding. Note This field is set only if
step-functions-api-032
step-functions-api.pdf
32
the JSON input data of the execution. Length constraints apply to the payload size, and are expressed as bytes in UTF-8 encoding. Response Elements API Version 2016-11-23 141 API Reference AWS Step Functions Type: String Length Constraints: Maximum length of 262144. inputDetails Provides details about execution input or output. Type: CloudWatchEventsExecutionDataDetails object name The name of the execution. Type: String Length Constraints: Minimum length of 1. Maximum length of 80. output The JSON output data of the execution. Length constraints apply to the payload size, and are expressed as bytes in UTF-8 encoding. Note This field is set only if the execution succeeds. If the execution fails, this field is null. Type: String Length Constraints: Maximum length of 262144. outputDetails Provides details about execution input or output. Type: CloudWatchEventsExecutionDataDetails object startDate The date the execution is started. Type: Timestamp stateMachineArn The Amazon Resource Name (ARN) that identifies the state machine. Response Elements API Version 2016-11-23 142 AWS Step Functions Type: String API Reference Length Constraints: Minimum length of 1. Maximum length of 256. status The current status of the execution. Type: String Valid Values: SUCCEEDED | FAILED | TIMED_OUT stopDate If the execution has already ended, the date the execution stopped. Type: Timestamp traceHeader The AWS X-Ray trace header that was passed to the execution. Note For X-Ray traces, all AWS services use the X-Amzn-Trace-Id header from the HTTP request. Using the header is the preferred mechanism to identify a trace. StartExecution and StartSyncExecution API operations can also use traceHeader from the body of the request payload. If both sources are provided, Step Functions will use the header value (preferred) over the value in the request body. Type: String Length Constraints: Minimum length of 0. Maximum length of 256. Pattern: \p{ASCII}* Errors For information about the errors that are common to all actions, see Common Errors. InvalidArn The provided Amazon Resource Name (ARN) is not valid. Errors API Version 2016-11-23 143 API Reference AWS Step Functions HTTP Status Code: 400 InvalidExecutionInput The provided JSON input data is not valid. HTTP Status Code: 400 InvalidName The provided name is not valid. HTTP Status Code: 400 KmsAccessDeniedException Either your AWS KMS key policy or API caller does not have the required permissions. HTTP Status Code: 400 KmsInvalidStateException The AWS KMS key is not in valid state, for example: Disabled or Deleted. HTTP Status Code: 400 KmsThrottlingException Received when AWS KMS returns ThrottlingException for a AWS KMS call that Step Functions makes on behalf of the caller. HTTP Status Code: 400 StateMachineDeleting The specified state machine is being deleted. HTTP Status Code: 400 StateMachineDoesNotExist The specified state machine does not exist. HTTP Status Code: 400 StateMachineTypeNotSupported State machine type is not supported. Errors API Version 2016-11-23 144 AWS Step Functions HTTP Status Code: 400 See Also API Reference For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2016-11-23 145 AWS Step Functions StopExecution Stops an execution. API Reference This API action is not supported by EXPRESS state machines. For an execution with encryption enabled, Step Functions will encrypt the error and cause fields using the AWS KMS key for the execution role. A caller can stop an execution without using any AWS KMS permissions in the execution role if the caller provides a null value for both error and cause fields because no data needs to be encrypted. Request Syntax { "cause": "string", "error": "string", "executionArn": "string" } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. cause A more detailed explanation of the cause of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 32768. Required: No error The error code of the failure. Type: String StopExecution API Version 2016-11-23 146 AWS Step Functions API Reference Length Constraints: Minimum length of 0. Maximum length of 256. Required: No executionArn The Amazon Resource Name (ARN) of the execution to stop. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Required: Yes Response Syntax { "stopDate": number } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. stopDate The date the execution is stopped. Type: Timestamp Errors For information about the errors that are common to all actions, see Common Errors. ExecutionDoesNotExist The specified execution does not
step-functions-api-033
step-functions-api.pdf
33
Reference Length Constraints: Minimum length of 0. Maximum length of 256. Required: No executionArn The Amazon Resource Name (ARN) of the execution to stop. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Required: Yes Response Syntax { "stopDate": number } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. stopDate The date the execution is stopped. Type: Timestamp Errors For information about the errors that are common to all actions, see Common Errors. ExecutionDoesNotExist The specified execution does not exist. HTTP Status Code: 400 Response Syntax API Version 2016-11-23 147 AWS Step Functions InvalidArn The provided Amazon Resource Name (ARN) is not valid. HTTP Status Code: 400 KmsAccessDeniedException API Reference Either your AWS KMS key policy or API caller does not have the required permissions. HTTP Status Code: 400 KmsInvalidStateException The AWS KMS key is not in valid state, for example: Disabled or Deleted. HTTP Status Code: 400 KmsThrottlingException Received when AWS KMS returns ThrottlingException for a AWS KMS call that Step Functions makes on behalf of the caller. HTTP Status Code: 400 ValidationException The input does not satisfy the constraints specified by an AWS service. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 See Also API Version 2016-11-23 148 AWS Step Functions • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 API Reference See Also API Version 2016-11-23 149 AWS Step Functions TagResource Add a tag to a Step Functions resource. API Reference An array of key-value pairs. For more information, see Using Cost Allocation Tags in the AWS Billing and Cost Management User Guide, and Controlling Access Using IAM Tags. Tags may only contain Unicode letters, digits, white space, or these symbols: _ . : / = + - @. Request Syntax { "resourceArn": "string", "tags": [ { "key": "string", "value": "string" } ] } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. resourceArn The Amazon Resource Name (ARN) for the Step Functions state machine or activity. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Required: Yes tags The list of tags to add to a resource. Tags may only contain Unicode letters, digits, white space, or these symbols: _ . : / = + - @. TagResource API Version 2016-11-23 150 AWS Step Functions Type: Array of Tag objects Required: Yes Response Elements API Reference If the action is successful, the service sends back an HTTP 200 response with an empty HTTP body. Errors For information about the errors that are common to all actions, see Common Errors. InvalidArn The provided Amazon Resource Name (ARN) is not valid. HTTP Status Code: 400 ResourceNotFound Could not find the referenced resource. HTTP Status Code: 400 TooManyTags You've exceeded the number of tags allowed for a resource. See the Limits Topic in the AWS Step Functions Developer Guide. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 Response Elements API Version 2016-11-23 151 AWS Step Functions • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 API Reference See Also API Version 2016-11-23 152 AWS Step Functions TestState API Reference Accepts the definition of a single state and executes it. You can test a state without creating a state machine or updating an existing state machine. Using this API, you can test the following: • A state's input and output processing data flow • An AWS service integration request and response • An HTTP Task request and response You can call this API on only one state at a time. The states that you can test include the following: • All Task types except Activity • Pass • Wait • Choice • Succeed • Fail The TestState API assumes an IAM role which must contain the required IAM permissions for the resources your state is accessing. For information about the permissions a state might need, see IAM permissions to test a state. The TestState API can run for
step-functions-api-034
step-functions-api.pdf
34
and output processing data flow • An AWS service integration request and response • An HTTP Task request and response You can call this API on only one state at a time. The states that you can test include the following: • All Task types except Activity • Pass • Wait • Choice • Succeed • Fail The TestState API assumes an IAM role which must contain the required IAM permissions for the resources your state is accessing. For information about the permissions a state might need, see IAM permissions to test a state. The TestState API can run for up to five minutes. If the execution of a state exceeds this duration, it fails with the States.Timeout error. TestState doesn't support Activity tasks, .sync or .waitForTaskToken service integration patterns, Parallel, or Map states. Request Syntax { "definition": "string", "input": "string", "inspectionLevel": "string", "revealSecrets": boolean, "roleArn": "string", "variables": "string" TestState API Version 2016-11-23 153 AWS Step Functions } Request Parameters API Reference For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. definition The Amazon States Language (ASL) definition of the state. Type: String Length Constraints: Minimum length of 1. Maximum length of 1048576. Required: Yes input A string that contains the JSON input data for the state. Type: String Length Constraints: Maximum length of 262144. Required: No inspectionLevel Determines the values to return when a state is tested. You can specify one of the following types: • INFO: Shows the final state output. By default, Step Functions sets inspectionLevel to INFO if you don't specify a level. • DEBUG: Shows the final state output along with the input and output data processing result. • TRACE: Shows the HTTP request and response for an HTTP Task. This level also shows the final state output along with the input and output data processing result. Each of these levels also provide information about the status of the state execution and the next state to transition to. Type: String Request Parameters API Version 2016-11-23 154 AWS Step Functions API Reference Valid Values: INFO | DEBUG | TRACE Required: No revealSecrets Specifies whether or not to include secret information in the test result. For HTTP Tasks, a secret includes the data that an EventBridge connection adds to modify the HTTP request headers, query parameters, and body. Step Functions doesn't omit any information included in the state definition or the HTTP response. If you set revealSecrets to true, you must make sure that the IAM user that calls the TestState API has permission for the states:RevealSecrets action. For an example of IAM policy that sets the states:RevealSecrets permission, see IAM permissions to test a state. Without this permission, Step Functions throws an access denied error. By default, revealSecrets is set to false. Type: Boolean Required: No roleArn The Amazon Resource Name (ARN) of the execution role with the required IAM permissions for the state. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Required: No variables JSON object literal that sets variables used in the state under test. Object keys are the variable names and values are the variable values. Type: String Length Constraints: Maximum length of 262144. Required: No Request Parameters API Version 2016-11-23 155 API Reference AWS Step Functions Response Syntax { "cause": "string", "error": "string", "inspectionData": { "afterArguments": "string", "afterInputPath": "string", "afterParameters": "string", "afterResultPath": "string", "afterResultSelector": "string", "input": "string", "request": { "body": "string", "headers": "string", "method": "string", "protocol": "string", "url": "string" }, "response": { "body": "string", "headers": "string", "protocol": "string", "statusCode": "string", "statusMessage": "string" }, "result": "string", "variables": "string" }, "nextState": "string", "output": "string", "status": "string" } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. cause A detailed explanation of the cause for the error when the execution of a state fails. Response Syntax API Version 2016-11-23 156 AWS Step Functions Type: String API Reference Length Constraints: Minimum length of 0. Maximum length of 32768. error The error returned when the execution of a state fails. Type: String Length Constraints: Minimum length of 0. Maximum length of 256. inspectionData Returns additional details about the state's execution, including its input and output data processing flow, and HTTP request and response information. The inspectionLevel request parameter specifies which details are returned. Type: InspectionData object nextState The name of the next state to transition to. If you haven't defined a next state in your definition or if the execution of the state fails, this field doesn't contain a value. Type: String Length Constraints: Minimum length of 1. Maximum length of 80. output The JSON output data of the state. Length constraints apply to the payload size, and are expressed as bytes
step-functions-api-035
step-functions-api.pdf
35
inspectionData Returns additional details about the state's execution, including its input and output data processing flow, and HTTP request and response information. The inspectionLevel request parameter specifies which details are returned. Type: InspectionData object nextState The name of the next state to transition to. If you haven't defined a next state in your definition or if the execution of the state fails, this field doesn't contain a value. Type: String Length Constraints: Minimum length of 1. Maximum length of 80. output The JSON output data of the state. Length constraints apply to the payload size, and are expressed as bytes in UTF-8 encoding. Type: String Length Constraints: Maximum length of 262144. status The execution status of the state. Type: String Valid Values: SUCCEEDED | FAILED | RETRIABLE | CAUGHT_ERROR Response Elements API Version 2016-11-23 157 AWS Step Functions Errors API Reference For information about the errors that are common to all actions, see Common Errors. InvalidArn The provided Amazon Resource Name (ARN) is not valid. HTTP Status Code: 400 InvalidDefinition The provided Amazon States Language definition is not valid. HTTP Status Code: 400 InvalidExecutionInput The provided JSON input data is not valid. HTTP Status Code: 400 ValidationException The input does not satisfy the constraints specified by an AWS service. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 Errors API Version 2016-11-23 158 AWS Step Functions • AWS SDK for Python • AWS SDK for Ruby V3 API Reference See Also API Version 2016-11-23 159 API Reference AWS Step Functions UntagResource Remove a tag from a Step Functions resource Request Syntax { "resourceArn": "string", "tagKeys": [ "string" ] } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. resourceArn The Amazon Resource Name (ARN) for the Step Functions state machine or activity. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Required: Yes tagKeys The list of tags to remove from the resource. Type: Array of strings Length Constraints: Minimum length of 1. Maximum length of 128. Required: Yes Response Elements If the action is successful, the service sends back an HTTP 200 response with an empty HTTP body. UntagResource API Version 2016-11-23 160 AWS Step Functions Errors API Reference For information about the errors that are common to all actions, see Common Errors. InvalidArn The provided Amazon Resource Name (ARN) is not valid. HTTP Status Code: 400 ResourceNotFound Could not find the referenced resource. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 Errors API Version 2016-11-23 161 AWS Step Functions UpdateMapRun API Reference Updates an in-progress Map Run's configuration to include changes to the settings that control maximum concurrency and Map Run failure. Request Syntax { "mapRunArn": "string", "maxConcurrency": number, "toleratedFailureCount": number, "toleratedFailurePercentage": number } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. mapRunArn The Amazon Resource Name (ARN) of a Map Run. Type: String Length Constraints: Minimum length of 1. Maximum length of 2000. Required: Yes maxConcurrency The maximum number of child workflow executions that can be specified to run in parallel for the Map Run at the same time. Type: Integer Valid Range: Minimum value of 0. Required: No UpdateMapRun API Version 2016-11-23 162 AWS Step Functions toleratedFailureCount API Reference The maximum number of failed items before the Map Run fails. Type: Long Valid Range: Minimum value of 0. Required: No toleratedFailurePercentage The maximum percentage of failed items before the Map Run fails. Type: Float Valid Range: Minimum value of 0. Maximum value of 100. Required: No Response Elements If the action is successful, the service sends back an HTTP 200 response with an empty HTTP body. Errors For information about the errors that are common to all actions, see Common Errors. InvalidArn The provided Amazon Resource Name (ARN) is not valid. HTTP Status Code: 400 ResourceNotFound Could not find the referenced resource. HTTP Status Code: 400 ValidationException The input does not satisfy
step-functions-api-036
step-functions-api.pdf
36
Valid Range: Minimum value of 0. Required: No toleratedFailurePercentage The maximum percentage of failed items before the Map Run fails. Type: Float Valid Range: Minimum value of 0. Maximum value of 100. Required: No Response Elements If the action is successful, the service sends back an HTTP 200 response with an empty HTTP body. Errors For information about the errors that are common to all actions, see Common Errors. InvalidArn The provided Amazon Resource Name (ARN) is not valid. HTTP Status Code: 400 ResourceNotFound Could not find the referenced resource. HTTP Status Code: 400 ValidationException The input does not satisfy the constraints specified by an AWS service. HTTP Status Code: 400 Response Elements API Version 2016-11-23 163 AWS Step Functions See Also API Reference For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2016-11-23 164 AWS Step Functions API Reference UpdateStateMachine Updates an existing state machine by modifying its definition, roleArn, loggingConfiguration, or EncryptionConfiguration. Running executions will continue to use the previous definition and roleArn. You must include at least one of definition or roleArn or you will receive a MissingRequiredParameter error. A qualified state machine ARN refers to a Distributed Map state defined within a state machine. For example, the qualified state machine ARN arn:partition:states:region:account- id:stateMachine:stateMachineName/mapStateLabel refers to a Distributed Map state with a label mapStateLabel in the state machine named stateMachineName. A qualified state machine ARN can either refer to a Distributed Map state defined within a state machine, a version ARN, or an alias ARN. The following are some examples of qualified and unqualified state machine ARNs: • The following qualified state machine ARN refers to a Distributed Map state with a label mapStateLabel in a state machine named myStateMachine. arn:partition:states:region:account-id:stateMachine:myStateMachine/ mapStateLabel Note If you provide a qualified state machine ARN that refers to a Distributed Map state, the request fails with ValidationException. • The following qualified state machine ARN refers to an alias named PROD. arn:<partition>:states:<region>:<account- id>:stateMachine:<myStateMachine:PROD> Note If you provide a qualified state machine ARN that refers to a version ARN or an alias ARN, the request starts execution for that version or alias. • The following unqualified state machine ARN refers to a state machine named myStateMachine. UpdateStateMachine API Version 2016-11-23 165 AWS Step Functions API Reference arn:<partition>:states:<region>:<account- id>:stateMachine:<myStateMachine> After you update your state machine, you can set the publish parameter to true in the same action to publish a new version. This way, you can opt-in to strict versioning of your state machine. Note Step Functions assigns monotonically increasing integers for state machine versions, starting at version number 1. Note All StartExecution calls within a few seconds use the updated definition and roleArn. Executions started immediately after you call UpdateStateMachine may use the previous state machine definition and roleArn. Request Syntax { "definition": "string", "encryptionConfiguration": { "kmsDataKeyReusePeriodSeconds": number, "kmsKeyId": "string", "type": "string" }, "loggingConfiguration": { "destinations": [ { "cloudWatchLogsLogGroup": { "logGroupArn": "string" } } ], "includeExecutionData": boolean, "level": "string" }, Request Syntax API Version 2016-11-23 166 AWS Step Functions API Reference "publish": boolean, "roleArn": "string", "stateMachineArn": "string", "tracingConfiguration": { "enabled": boolean }, "versionDescription": "string" } Request Parameters For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. definition The Amazon States Language definition of the state machine. See Amazon States Language. Type: String Length Constraints: Minimum length of 1. Maximum length of 1048576. Required: No encryptionConfiguration Settings to configure server-side encryption. Type: EncryptionConfiguration object Required: No loggingConfiguration Use the LoggingConfiguration data type to set CloudWatch Logs options. Type: LoggingConfiguration object Required: No publish Specifies whether the state machine version is published. The default is false. To publish a version after updating the state machine, set publish to true. Request Parameters API Version 2016-11-23 167 API Reference AWS Step Functions Type: Boolean Required: No roleArn The Amazon Resource Name (ARN) of the IAM role of the state machine. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Required: No stateMachineArn The Amazon Resource Name (ARN) of the state machine. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Required: Yes tracingConfiguration Selects whether AWS X-Ray tracing is enabled. Type: TracingConfiguration object Required: No versionDescription An optional description of the state machine version to publish. You can only specify the versionDescription parameter if you've set publish to true. Type: String Length Constraints: Maximum length of 256. Required: No Response
step-functions-api-037
step-functions-api.pdf
37
roleArn The Amazon Resource Name (ARN) of the IAM role of the state machine. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Required: No stateMachineArn The Amazon Resource Name (ARN) of the state machine. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Required: Yes tracingConfiguration Selects whether AWS X-Ray tracing is enabled. Type: TracingConfiguration object Required: No versionDescription An optional description of the state machine version to publish. You can only specify the versionDescription parameter if you've set publish to true. Type: String Length Constraints: Maximum length of 256. Required: No Response Syntax { Response Syntax API Version 2016-11-23 168 AWS Step Functions API Reference "revisionId": "string", "stateMachineVersionArn": "string", "updateDate": number } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. revisionId The revision identifier for the updated state machine. Type: String stateMachineVersionArn The Amazon Resource Name (ARN) of the published state machine version. If the publish parameter isn't set to true, this field returns null. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. updateDate The date and time the state machine was updated. Type: Timestamp Errors For information about the errors that are common to all actions, see Common Errors. ConflictException Updating or deleting a resource can cause an inconsistent state. This error occurs when there're concurrent requests for DeleteStateMachineVersion, PublishStateMachineVersion, or UpdateStateMachine with the publish parameter set to true. Response Elements API Version 2016-11-23 169 API Reference AWS Step Functions HTTP Status Code: 409 HTTP Status Code: 400 InvalidArn The provided Amazon Resource Name (ARN) is not valid. HTTP Status Code: 400 InvalidDefinition The provided Amazon States Language definition is not valid. HTTP Status Code: 400 InvalidEncryptionConfiguration Received when encryptionConfiguration is specified but various conditions exist which make the configuration invalid. For example, if type is set to CUSTOMER_MANAGED_KMS_KEY, but kmsKeyId is null, or kmsDataKeyReusePeriodSeconds is not between 60 and 900, or the AWS KMS key is not symmetric or inactive. HTTP Status Code: 400 InvalidLoggingConfiguration Configuration is not valid. HTTP Status Code: 400 InvalidTracingConfiguration Your tracingConfiguration key does not match, or enabled has not been set to true or false. HTTP Status Code: 400 KmsAccessDeniedException Either your AWS KMS key policy or API caller does not have the required permissions. HTTP Status Code: 400 KmsThrottlingException Received when AWS KMS returns ThrottlingException for a AWS KMS call that Step Functions makes on behalf of the caller. Errors API Version 2016-11-23 170 AWS Step Functions HTTP Status Code: 400 MissingRequiredParameter API Reference Request is missing a required parameter. This error occurs if both definition and roleArn are not specified. HTTP Status Code: 400 ServiceQuotaExceededException The request would cause a service quota to be exceeded. HTTP Status Code: 402 HTTP Status Code: 400 StateMachineDeleting The specified state machine is being deleted. HTTP Status Code: 400 StateMachineDoesNotExist The specified state machine does not exist. HTTP Status Code: 400 ValidationException The input does not satisfy the constraints specified by an AWS service. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 See Also API Version 2016-11-23 171 AWS Step Functions • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 API Reference See Also API Version 2016-11-23 172 AWS Step Functions API Reference UpdateStateMachineAlias Updates the configuration of an existing state machine alias by modifying its description or routingConfiguration. You must specify at least one of the description or routingConfiguration parameters to update a state machine alias. Note UpdateStateMachineAlias is an idempotent API. Step Functions bases the idempotency check on the stateMachineAliasArn, description, and routingConfiguration parameters. Requests with the same parameters return an idempotent response. Note This operation is eventually consistent. All StartExecution requests made within a few seconds use the latest alias configuration. Executions started immediately after calling UpdateStateMachineAlias may use the previous routing configuration. Related operations: • CreateStateMachineAlias • DescribeStateMachineAlias • ListStateMachineAliases • DeleteStateMachineAlias Request Syntax { "description": "string", "routingConfiguration": [ { "stateMachineVersionArn": "string", "weight": number UpdateStateMachineAlias API Version 2016-11-23 173 AWS Step Functions } ], "stateMachineAliasArn": "string" } Request Parameters API Reference For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. description A description of the state machine alias. Type: String Length Constraints: Maximum length of 256. Required: No routingConfiguration The routing configuration of the state machine alias. An array of RoutingConfig objects that specifies up to
step-functions-api-038
step-functions-api.pdf
38
routing configuration. Related operations: • CreateStateMachineAlias • DescribeStateMachineAlias • ListStateMachineAliases • DeleteStateMachineAlias Request Syntax { "description": "string", "routingConfiguration": [ { "stateMachineVersionArn": "string", "weight": number UpdateStateMachineAlias API Version 2016-11-23 173 AWS Step Functions } ], "stateMachineAliasArn": "string" } Request Parameters API Reference For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. description A description of the state machine alias. Type: String Length Constraints: Maximum length of 256. Required: No routingConfiguration The routing configuration of the state machine alias. An array of RoutingConfig objects that specifies up to two state machine versions that the alias starts executions for. Type: Array of RoutingConfigurationListItem objects Array Members: Minimum number of 1 item. Maximum number of 2 items. Required: No stateMachineAliasArn The Amazon Resource Name (ARN) of the state machine alias. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Required: Yes Request Parameters API Version 2016-11-23 174 AWS Step Functions Response Syntax { "updateDate": number } Response Elements API Reference If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. updateDate The date and time the state machine alias was updated. Type: Timestamp Errors For information about the errors that are common to all actions, see Common Errors. ConflictException Updating or deleting a resource can cause an inconsistent state. This error occurs when there're concurrent requests for DeleteStateMachineVersion, PublishStateMachineVersion, or UpdateStateMachine with the publish parameter set to true. HTTP Status Code: 409 HTTP Status Code: 400 InvalidArn The provided Amazon Resource Name (ARN) is not valid. HTTP Status Code: 400 ResourceNotFound Could not find the referenced resource. HTTP Status Code: 400 Response Syntax API Version 2016-11-23 175 AWS Step Functions StateMachineDeleting The specified state machine is being deleted. HTTP Status Code: 400 ValidationException API Reference The input does not satisfy the constraints specified by an AWS service. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2016-11-23 176 AWS Step Functions API Reference ValidateStateMachineDefinition Validates the syntax of a state machine definition specified in Amazon States Language (ASL), a JSON-based, structured language. You can validate that a state machine definition is correct without creating a state machine resource. Suggested uses for ValidateStateMachineDefinition: • Integrate automated checks into your code review or Continuous Integration (CI) process to check state machine definitions before starting deployments. • Run validation from a Git pre-commit hook to verify the definition before committing to your source repository. Validation will look for problems in your state machine definition and return a result and a list of diagnostic elements. The result value will be OK when your workflow definition can be successfully created or updated. Note the result can be OK even when diagnostic warnings are present in the response. The result value will be FAIL when the workflow definition contains errors that would prevent you from creating or updating your state machine. The list of ValidateStateMachineDefinitionDiagnostic data elements can contain zero or more WARNING and/or ERROR elements. Note The ValidateStateMachineDefinition API might add new diagnostics in the future, adjust diagnostic codes, or change the message wording. Your automated processes should only rely on the value of the result field value (OK, FAIL). Do not rely on the exact order, count, or wording of diagnostic messages. Request Syntax { "definition": "string", ValidateStateMachineDefinition API Version 2016-11-23 177 AWS Step Functions "maxResults": number, "severity": "string", "type": "string" } Request Parameters API Reference For information about the parameters that are common to all actions, see Common Parameters. The request accepts the following data in JSON format. definition The Amazon States Language definition of the state machine. For more information, see Amazon States Language (ASL). Type: String Length Constraints: Minimum length of 1. Maximum length of 1048576. Required: Yes maxResults The maximum number of diagnostics that are returned per call. The default and maximum value is 100. Setting the value to 0 will also use the default of 100. If the number of diagnostics returned in the response exceeds maxResults, the value of the truncated field in the response will be set to true. Type: Integer Valid Range: Minimum value of 0. Maximum value of 100. Required: No severity Minimum level of diagnostics to return. ERROR returns only ERROR diagnostics, whereas WARNING returns both WARNING and ERROR diagnostics. The default is ERROR.
step-functions-api-039
step-functions-api.pdf
39
1. Maximum length of 1048576. Required: Yes maxResults The maximum number of diagnostics that are returned per call. The default and maximum value is 100. Setting the value to 0 will also use the default of 100. If the number of diagnostics returned in the response exceeds maxResults, the value of the truncated field in the response will be set to true. Type: Integer Valid Range: Minimum value of 0. Maximum value of 100. Required: No severity Minimum level of diagnostics to return. ERROR returns only ERROR diagnostics, whereas WARNING returns both WARNING and ERROR diagnostics. The default is ERROR. Type: String Request Parameters API Version 2016-11-23 178 AWS Step Functions API Reference Valid Values: ERROR | WARNING Required: No type The target type of state machine for this definition. The default is STANDARD. Type: String Valid Values: STANDARD | EXPRESS Required: No Response Syntax { "diagnostics": [ { "code": "string", "location": "string", "message": "string", "severity": "string" } ], "result": "string", "truncated": boolean } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. diagnostics An array of diagnostic errors and warnings found during validation of the state machine definition. Since warnings do not prevent deploying your workflow definition, the result value could be OK even when warning diagnostics are present in the response. Type: Array of ValidateStateMachineDefinitionDiagnostic objects Response Syntax API Version 2016-11-23 179 AWS Step Functions result API Reference The result value will be OK when no syntax errors are found, or FAIL if the workflow definition does not pass verification. Type: String Valid Values: OK | FAIL truncated The result value will be true if the number of diagnostics found in the workflow definition exceeds maxResults. When all diagnostics results are returned, the value will be false. Type: Boolean Errors For information about the errors that are common to all actions, see Common Errors. ValidationException The input does not satisfy the constraints specified by an AWS service. HTTP Status Code: 400 Examples Validate an inline state machine definition The following example shows how to invoke the API from the CLI: aws stepfunctions validate-state-machine-definition \ --definition '{"StartAt":"WaitState","States":{"WaitState": {"Type":"Wait","Seconds":5,"End":true}}}' \ --type 'STANDARD' Validate a state machine definition from a file If your state machine definition is saved in a JSON file, you can use the file:// notation to pass the file contents to the API. Errors API Version 2016-11-23 180 AWS Step Functions API Reference aws stepfunctions validate-state-machine-definition \ --definition file://my-state-machine-definition.asl.json Parse the validation result On POSIX compliant systems, you can use a command-line utility like grep to parse the output and generate a non-zero return code if the definition did not successfully pass the syntax check: aws stepfunctions validate-state-machine-definition \ --definition file://my-state-machine-definition.asl.json | grep '"result": "OK"' Validate a state machine definition with static analysis By setting the severity level to WARNING, you can gain visibility into potential issues with your definition before deploying your state machine. In the following example, the four WARNING level diagnostics alert you to potential issues, but they will not prevent you from creating or updating your state machine. Any diagnostic results with ERROR level severity will prevent you from deploying the state machine. Example results with static analysis warnings: $ aws stepfunctions validate-state-machine-definition \ --definition file://my-workflow-definition.asl.json \ --severity WARNING { "result": "OK", "diagnostics": [ { "severity": "WARNING", "code": "NO_DOLLAR", "message": "The value of 'a' looks like a JSONPath. Instead of 'a', use 'a. $' to evaluate it as a JSONPath at runtime.", "location": "/States/HelloWorld/Parameters" }, { "severity": "WARNING", "code": "PASS_RESULT_IS_STATIC", Examples API Version 2016-11-23 181 AWS Step Functions API Reference "message": "The value of 'c.$' will not evaluate as a JSONPath or Intrinsic Function at runtime. Instead of 'Result', use 'Parameters' to evaluate it as a JSONPath or Intrinsic Function at runtime.", "location": "/States/HelloWorld/Result" }, { "severity": "WARNING", "code": "NO_PATH", "message": "The value of 'Error' looks like a JSONPath. Instead of 'Error', use 'ErrorPath' to evaluate it as a JSONPath at runtime.", "location": "/States/FailState/Error" }, { "severity": "WARNING", "code": "NO_PATH", "message": "The value of 'Cause' looks like a JSONPath. Instead of 'Cause', use 'CausePath' to evaluate it as a JSONPath at runtime.", "location": "/States/FailState/Cause" } ], "truncated": false } See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2016-11-23 182 AWS Step Functions Data Types API Reference The AWS Step Functions API contains several data types that various
step-functions-api-040
step-functions-api.pdf
40
false } See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2016-11-23 182 AWS Step Functions Data Types API Reference The AWS Step Functions API contains several data types that various actions use. This section describes each data type in detail. Note The order of each element in a data type structure is not guaranteed. Applications should not assume a particular order. The following data types are supported: • ActivityFailedEventDetails • ActivityListItem • ActivityScheduledEventDetails • ActivityScheduleFailedEventDetails • ActivityStartedEventDetails • ActivitySucceededEventDetails • ActivityTimedOutEventDetails • AssignedVariablesDetails • BillingDetails • CloudWatchEventsExecutionDataDetails • CloudWatchLogsLogGroup • EncryptionConfiguration • EvaluationFailedEventDetails • ExecutionAbortedEventDetails • ExecutionFailedEventDetails • ExecutionListItem • ExecutionRedrivenEventDetails • ExecutionStartedEventDetails • ExecutionSucceededEventDetails • ExecutionTimedOutEventDetails API Version 2016-11-23 183 AWS Step Functions • HistoryEvent • HistoryEventExecutionDataDetails • InspectionData • InspectionDataRequest • InspectionDataResponse • LambdaFunctionFailedEventDetails • LambdaFunctionScheduledEventDetails • LambdaFunctionScheduleFailedEventDetails • LambdaFunctionStartFailedEventDetails • LambdaFunctionSucceededEventDetails • LambdaFunctionTimedOutEventDetails • LogDestination • LoggingConfiguration • MapIterationEventDetails • MapRunExecutionCounts • MapRunFailedEventDetails • MapRunItemCounts • MapRunListItem • MapRunRedrivenEventDetails • MapRunStartedEventDetails • MapStateStartedEventDetails • RoutingConfigurationListItem • StateEnteredEventDetails • StateExitedEventDetails • StateMachineAliasListItem • StateMachineListItem • StateMachineVersionListItem • Tag • TaskCredentials • TaskFailedEventDetails API Reference API Version 2016-11-23 184 API Reference AWS Step Functions • TaskScheduledEventDetails • TaskStartedEventDetails • TaskStartFailedEventDetails • TaskSubmitFailedEventDetails • TaskSubmittedEventDetails • TaskSucceededEventDetails • TaskTimedOutEventDetails • TracingConfiguration • ValidateStateMachineDefinitionDiagnostic API Version 2016-11-23 185 AWS Step Functions API Reference ActivityFailedEventDetails Contains details about an activity that failed during an execution. Contents cause A more detailed explanation of the cause of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 32768. Required: No error The error code of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 256. Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 ActivityFailedEventDetails API Version 2016-11-23 186 API Reference AWS Step Functions ActivityListItem Contains details about an activity. Contents activityArn The Amazon Resource Name (ARN) that identifies the activity. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Required: Yes creationDate The date the activity is created. Type: Timestamp Required: Yes name The name of the activity. A name must not contain: • white space • brackets < > { } [ ] • wildcard characters ? * • special characters " # % \ ^ | ~ ` $ & , ; : / • control characters (U+0000-001F, U+007F-009F, U+FFFE-FFFF) • surrogates (U+D800-DFFF) • invalid characters ( U+10FFFF) To enable logging with CloudWatch Logs, the name should only contain 0-9, A-Z, a-z, - and _. Type: String ActivityListItem API Version 2016-11-23 187 AWS Step Functions API Reference Length Constraints: Minimum length of 1. Maximum length of 80. Required: Yes See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API Version 2016-11-23 188 AWS Step Functions API Reference ActivityScheduledEventDetails Contains details about an activity scheduled during an execution. Contents resource The Amazon Resource Name (ARN) of the scheduled activity. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Required: Yes heartbeatInSeconds The maximum allowed duration between two heartbeats for the activity task. Type: Long Required: No input The JSON data input to the activity task. Length constraints apply to the payload size, and are expressed as bytes in UTF-8 encoding. Type: String Length Constraints: Maximum length of 262144. Required: No inputDetails Contains details about the input for an execution history event. Type: HistoryEventExecutionDataDetails object Required: No timeoutInSeconds The maximum allowed duration of the activity task. ActivityScheduledEventDetails API Version 2016-11-23 189 AWS Step Functions Type: Long Required: No See Also API Reference For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API Version 2016-11-23 190 AWS Step Functions API Reference ActivityScheduleFailedEventDetails Contains details about an activity schedule failure that occurred during an execution. Contents cause A more detailed explanation of the cause of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 32768. Required: No error The error code of the failure. Type: String Length Constraints: Minimum length of 0. Maximum
step-functions-api-041
step-functions-api.pdf
41
For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API Version 2016-11-23 190 AWS Step Functions API Reference ActivityScheduleFailedEventDetails Contains details about an activity schedule failure that occurred during an execution. Contents cause A more detailed explanation of the cause of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 32768. Required: No error The error code of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 256. Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 ActivityScheduleFailedEventDetails API Version 2016-11-23 191 AWS Step Functions API Reference ActivityStartedEventDetails Contains details about the start of an activity during an execution. Contents workerName The name of the worker that the task is assigned to. These names are provided by the workers when calling GetActivityTask. Type: String Length Constraints: Maximum length of 256. Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 ActivityStartedEventDetails API Version 2016-11-23 192 AWS Step Functions API Reference ActivitySucceededEventDetails Contains details about an activity that successfully terminated during an execution. Contents output The JSON data output by the activity task. Length constraints apply to the payload size, and are expressed as bytes in UTF-8 encoding. Type: String Length Constraints: Maximum length of 262144. Required: No outputDetails Contains details about the output of an execution history event. Type: HistoryEventExecutionDataDetails object Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 ActivitySucceededEventDetails API Version 2016-11-23 193 AWS Step Functions API Reference ActivityTimedOutEventDetails Contains details about an activity timeout that occurred during an execution. Contents cause A more detailed explanation of the cause of the timeout. Type: String Length Constraints: Minimum length of 0. Maximum length of 32768. Required: No error The error code of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 256. Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 ActivityTimedOutEventDetails API Version 2016-11-23 194 AWS Step Functions API Reference AssignedVariablesDetails Provides details about assigned variables in an execution history event. Contents truncated Indicates whether assigned variables were truncated in the response. Always false for API calls. In CloudWatch logs, the value will be true if the data is truncated due to size limits. Type: Boolean Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 AssignedVariablesDetails API Version 2016-11-23 195 API Reference AWS Step Functions BillingDetails An object that describes workflow billing details. Contents billedDurationInMilliseconds Billed duration of your workflow, in milliseconds. Type: Long Valid Range: Minimum value of 0. Required: No billedMemoryUsedInMB Billed memory consumption of your workflow, in MB. Type: Long Valid Range: Minimum value of 0. Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 BillingDetails API Version 2016-11-23 196 AWS Step Functions API Reference CloudWatchEventsExecutionDataDetails Provides details about execution input or output. Contents included Indicates whether input or output was included in the response. Always true for API calls. Type: Boolean Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 CloudWatchEventsExecutionDataDetails API Version 2016-11-23 197 AWS Step Functions API Reference CloudWatchLogsLogGroup Contents logGroupArn The ARN of the the CloudWatch log group to which you want your logs emitted to. The ARN must end with :* Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 CloudWatchLogsLogGroup API Version 2016-11-23 198 AWS Step Functions
step-functions-api-042
step-functions-api.pdf
42
V2 • AWS SDK for Ruby V3 CloudWatchEventsExecutionDataDetails API Version 2016-11-23 197 AWS Step Functions API Reference CloudWatchLogsLogGroup Contents logGroupArn The ARN of the the CloudWatch log group to which you want your logs emitted to. The ARN must end with :* Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 CloudWatchLogsLogGroup API Version 2016-11-23 198 AWS Step Functions API Reference EncryptionConfiguration Settings to configure server-side encryption. For additional control over security, you can encrypt your data using a customer-managed key for Step Functions state machines and activities. You can configure a symmetric AWS KMS key and data key reuse period when creating or updating a State Machine, and when creating an Activity. The execution history and state machine definition will be encrypted with the key applied to the State Machine. Activity inputs will be encrypted with the key applied to the Activity. Note Step Functions automatically enables encryption at rest using AWS owned keys at no charge. However, AWS KMS charges apply when using a customer managed key. For more information about pricing, see AWS Key Management Service pricing. For more information on AWS KMS, see What is AWS Key Management Service? Contents type Encryption type Type: String Valid Values: AWS_OWNED_KEY | CUSTOMER_MANAGED_KMS_KEY Required: Yes kmsDataKeyReusePeriodSeconds Maximum duration that Step Functions will reuse data keys. When the period expires, Step Functions will call GenerateDataKey. Only applies to customer managed keys. Type: Integer Valid Range: Minimum value of 60. Maximum value of 900. Required: No EncryptionConfiguration API Version 2016-11-23 199 AWS Step Functions kmsKeyId API Reference An alias, alias ARN, key ID, or key ARN of a symmetric encryption AWS KMS key to encrypt data. To specify a AWS KMS key in a different AWS account, you must use the key ARN or alias ARN. Type: String Length Constraints: Minimum length of 1. Maximum length of 2048. Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API Version 2016-11-23 200 AWS Step Functions API Reference EvaluationFailedEventDetails Contains details about an evaluation failure that occurred while processing a state, for example, when a JSONata expression throws an error. This event will only be present in state machines that have QueryLanguage set to JSONata, or individual states set to JSONata. Contents state The name of the state in which the evaluation error occurred. Type: String Length Constraints: Minimum length of 1. Maximum length of 80. Required: Yes cause A more detailed explanation of the cause of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 32768. Required: No error The error code of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 256. Required: No location The location of the field in the state in which the evaluation error occurred. Type: String Length Constraints: Minimum length of 0. Maximum length of 256. EvaluationFailedEventDetails API Version 2016-11-23 201 AWS Step Functions Required: No See Also API Reference For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API Version 2016-11-23 202 AWS Step Functions API Reference ExecutionAbortedEventDetails Contains details about an abort of an execution. Contents cause A more detailed explanation of the cause of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 32768. Required: No error The error code of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 256. Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 ExecutionAbortedEventDetails API Version 2016-11-23 203 AWS Step Functions API Reference ExecutionFailedEventDetails Contains details about an execution failure event. Contents cause A more detailed explanation of the cause of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 32768. Required: No error The error code of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 256. Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 ExecutionFailedEventDetails API Version 2016-11-23 204 API Reference AWS
step-functions-api-043
step-functions-api.pdf
43
Reference ExecutionFailedEventDetails Contains details about an execution failure event. Contents cause A more detailed explanation of the cause of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 32768. Required: No error The error code of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 256. Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 ExecutionFailedEventDetails API Version 2016-11-23 204 API Reference AWS Step Functions ExecutionListItem Contains details about an execution. Contents executionArn The Amazon Resource Name (ARN) that identifies the execution. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Required: Yes name The name of the execution. A name must not contain: • white space • brackets < > { } [ ] • wildcard characters ? * • special characters " # % \ ^ | ~ ` $ & , ; : / • control characters (U+0000-001F, U+007F-009F, U+FFFE-FFFF) • surrogates (U+D800-DFFF) • invalid characters ( U+10FFFF) To enable logging with CloudWatch Logs, the name should only contain 0-9, A-Z, a-z, - and _. Type: String Length Constraints: Minimum length of 1. Maximum length of 80. Required: Yes startDate The date the execution started. ExecutionListItem API Version 2016-11-23 205 AWS Step Functions Type: Timestamp Required: Yes stateMachineArn API Reference The Amazon Resource Name (ARN) of the state machine that ran the execution. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Required: Yes status The current status of the execution. Type: String Valid Values: RUNNING | SUCCEEDED | FAILED | TIMED_OUT | ABORTED | PENDING_REDRIVE Required: Yes itemCount The total number of items processed in a child workflow execution. This field is returned only if mapRunArn was specified in the ListExecutions API action. If stateMachineArn was specified in ListExecutions, the itemCount field isn't returned. Type: Integer Valid Range: Minimum value of 0. Required: No mapRunArn The Amazon Resource Name (ARN) of a Map Run. This field is returned only if mapRunArn was specified in the ListExecutions API action. If stateMachineArn was specified in ListExecutions, the mapRunArn isn't returned. Type: String Length Constraints: Minimum length of 1. Maximum length of 2000. Contents API Version 2016-11-23 206 AWS Step Functions Required: No redriveCount API Reference The number of times you've redriven an execution. If you have not yet redriven an execution, the redriveCount is 0. This count is only updated when you successfully redrive an execution. Type: Integer Required: No redriveDate The date the execution was last redriven. Type: Timestamp Required: No stateMachineAliasArn The Amazon Resource Name (ARN) of the state machine alias used to start an execution. If the state machine execution was started with an unqualified ARN or a version ARN, it returns null. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Required: No stateMachineVersionArn The Amazon Resource Name (ARN) of the state machine version associated with the execution. If the state machine execution was started with an unqualified ARN, it returns null. If the execution was started using a stateMachineAliasArn, both the stateMachineAliasArn and stateMachineVersionArn parameters contain the respective values. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Contents API Version 2016-11-23 207 AWS Step Functions Required: No stopDate If the execution already ended, the date the execution stopped. API Reference Type: Timestamp Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API Version 2016-11-23 208 AWS Step Functions API Reference ExecutionRedrivenEventDetails Contains details about a redriven execution. Contents redriveCount The number of times you've redriven an execution. If you have not yet redriven an execution, the redriveCount is 0. This count is not updated for redrives that failed to start or are pending to be redriven. Type: Integer Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 ExecutionRedrivenEventDetails API Version 2016-11-23 209 AWS Step Functions API Reference ExecutionStartedEventDetails Contains details about the start of the execution. Contents input The JSON data input to the execution. Length constraints apply to the payload size, and are expressed as bytes in UTF-8 encoding. Type: String Length Constraints: Maximum length of 262144. Required: No inputDetails Contains details about the input for an execution history event. Type: HistoryEventExecutionDataDetails object Required: No roleArn The Amazon Resource Name (ARN) of the IAM role used for executing AWS Lambda tasks. Type:
step-functions-api-044
step-functions-api.pdf
44
for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 ExecutionRedrivenEventDetails API Version 2016-11-23 209 AWS Step Functions API Reference ExecutionStartedEventDetails Contains details about the start of the execution. Contents input The JSON data input to the execution. Length constraints apply to the payload size, and are expressed as bytes in UTF-8 encoding. Type: String Length Constraints: Maximum length of 262144. Required: No inputDetails Contains details about the input for an execution history event. Type: HistoryEventExecutionDataDetails object Required: No roleArn The Amazon Resource Name (ARN) of the IAM role used for executing AWS Lambda tasks. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Required: No stateMachineAliasArn The Amazon Resource Name (ARN) that identifies a state machine alias used for starting the state machine execution. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Required: No ExecutionStartedEventDetails API Version 2016-11-23 210 AWS Step Functions stateMachineVersionArn API Reference The Amazon Resource Name (ARN) that identifies a state machine version used for starting the state machine execution. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API Version 2016-11-23 211 AWS Step Functions API Reference ExecutionSucceededEventDetails Contains details about the successful termination of the execution. Contents output The JSON data output by the execution. Length constraints apply to the payload size, and are expressed as bytes in UTF-8 encoding. Type: String Length Constraints: Maximum length of 262144. Required: No outputDetails Contains details about the output of an execution history event. Type: HistoryEventExecutionDataDetails object Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 ExecutionSucceededEventDetails API Version 2016-11-23 212 AWS Step Functions API Reference ExecutionTimedOutEventDetails Contains details about the execution timeout that occurred during the execution. Contents cause A more detailed explanation of the cause of the timeout. Type: String Length Constraints: Minimum length of 0. Maximum length of 32768. Required: No error The error code of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 256. Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 ExecutionTimedOutEventDetails API Version 2016-11-23 213 AWS Step Functions HistoryEvent Contains details about the events of an execution. Contents id The id of the event. Events are numbered sequentially, starting at one. API Reference Type: Long Required: Yes timestamp The date and time the event occurred. Type: Timestamp Required: Yes type The type of the event. Type: String Valid Values: ActivityFailed | ActivityScheduled | ActivityScheduleFailed | ActivityStarted | ActivitySucceeded | ActivityTimedOut | ChoiceStateEntered | ChoiceStateExited | ExecutionAborted | ExecutionFailed | ExecutionStarted | ExecutionSucceeded | ExecutionTimedOut | FailStateEntered | LambdaFunctionFailed | LambdaFunctionScheduled | LambdaFunctionScheduleFailed | LambdaFunctionStarted | LambdaFunctionStartFailed | LambdaFunctionSucceeded | LambdaFunctionTimedOut | MapIterationAborted | MapIterationFailed | MapIterationStarted | MapIterationSucceeded | MapStateAborted | MapStateEntered | MapStateExited | MapStateFailed | MapStateStarted | MapStateSucceeded | ParallelStateAborted | ParallelStateEntered | ParallelStateExited | ParallelStateFailed | ParallelStateStarted | ParallelStateSucceeded | PassStateEntered | HistoryEvent API Version 2016-11-23 214 AWS Step Functions API Reference PassStateExited | SucceedStateEntered | SucceedStateExited | TaskFailed | TaskScheduled | TaskStarted | TaskStartFailed | TaskStateAborted | TaskStateEntered | TaskStateExited | TaskSubmitFailed | TaskSubmitted | TaskSucceeded | TaskTimedOut | WaitStateAborted | WaitStateEntered | WaitStateExited | MapRunAborted | MapRunFailed | MapRunStarted | MapRunSucceeded | ExecutionRedriven | MapRunRedriven | EvaluationFailed Required: Yes activityFailedEventDetails Type: ActivityFailedEventDetails object Required: No activityScheduledEventDetails Type: ActivityScheduledEventDetails object Required: No activityScheduleFailedEventDetails Contains details about an activity schedule event that failed during an execution. Type: ActivityScheduleFailedEventDetails object Required: No activityStartedEventDetails Type: ActivityStartedEventDetails object Required: No activitySucceededEventDetails Type: ActivitySucceededEventDetails object Required: No activityTimedOutEventDetails Type: ActivityTimedOutEventDetails object Required: No Contents API Version 2016-11-23 215 AWS Step Functions evaluationFailedEventDetails API Reference Contains details about an evaluation failure that occurred while processing a state. Type: EvaluationFailedEventDetails object Required: No executionAbortedEventDetails Type: ExecutionAbortedEventDetails object Required: No executionFailedEventDetails Type: ExecutionFailedEventDetails object Required: No executionRedrivenEventDetails Contains details about the redrive attempt of an execution. Type: ExecutionRedrivenEventDetails object Required: No executionStartedEventDetails Type: ExecutionStartedEventDetails object Required: No executionSucceededEventDetails Type: ExecutionSucceededEventDetails object Required: No executionTimedOutEventDetails Type: ExecutionTimedOutEventDetails object Required: No lambdaFunctionFailedEventDetails Type: LambdaFunctionFailedEventDetails object Contents API Version 2016-11-23 216 API Reference AWS Step Functions Required: No lambdaFunctionScheduledEventDetails Type: LambdaFunctionScheduledEventDetails object Required: No lambdaFunctionScheduleFailedEventDetails Type: LambdaFunctionScheduleFailedEventDetails object Required: No lambdaFunctionStartFailedEventDetails Contains details about a lambda function that failed to start during an execution. Type: LambdaFunctionStartFailedEventDetails object Required: No lambdaFunctionSucceededEventDetails
step-functions-api-045
step-functions-api.pdf
45
a state. Type: EvaluationFailedEventDetails object Required: No executionAbortedEventDetails Type: ExecutionAbortedEventDetails object Required: No executionFailedEventDetails Type: ExecutionFailedEventDetails object Required: No executionRedrivenEventDetails Contains details about the redrive attempt of an execution. Type: ExecutionRedrivenEventDetails object Required: No executionStartedEventDetails Type: ExecutionStartedEventDetails object Required: No executionSucceededEventDetails Type: ExecutionSucceededEventDetails object Required: No executionTimedOutEventDetails Type: ExecutionTimedOutEventDetails object Required: No lambdaFunctionFailedEventDetails Type: LambdaFunctionFailedEventDetails object Contents API Version 2016-11-23 216 API Reference AWS Step Functions Required: No lambdaFunctionScheduledEventDetails Type: LambdaFunctionScheduledEventDetails object Required: No lambdaFunctionScheduleFailedEventDetails Type: LambdaFunctionScheduleFailedEventDetails object Required: No lambdaFunctionStartFailedEventDetails Contains details about a lambda function that failed to start during an execution. Type: LambdaFunctionStartFailedEventDetails object Required: No lambdaFunctionSucceededEventDetails Contains details about a Lambda function that terminated successfully during an execution. Type: LambdaFunctionSucceededEventDetails object Required: No lambdaFunctionTimedOutEventDetails Type: LambdaFunctionTimedOutEventDetails object Required: No mapIterationAbortedEventDetails Contains details about an iteration of a Map state that was aborted. Type: MapIterationEventDetails object Required: No mapIterationFailedEventDetails Contains details about an iteration of a Map state that failed. Contents API Version 2016-11-23 217 AWS Step Functions API Reference Type: MapIterationEventDetails object Required: No mapIterationStartedEventDetails Contains details about an iteration of a Map state that was started. Type: MapIterationEventDetails object Required: No mapIterationSucceededEventDetails Contains details about an iteration of a Map state that succeeded. Type: MapIterationEventDetails object Required: No mapRunFailedEventDetails Contains error and cause details about a Map Run that failed. Type: MapRunFailedEventDetails object Required: No mapRunRedrivenEventDetails Contains details about the redrive attempt of a Map Run. Type: MapRunRedrivenEventDetails object Required: No mapRunStartedEventDetails Contains details, such as mapRunArn, and the start date and time of a Map Run. mapRunArn is the Amazon Resource Name (ARN) of the Map Run that was started. Type: MapRunStartedEventDetails object Required: No mapStateStartedEventDetails Contains details about Map state that was started. Contents API Version 2016-11-23 218 AWS Step Functions API Reference Type: MapStateStartedEventDetails object Required: No previousEventId The id of the previous event. Type: Long Required: No stateEnteredEventDetails Type: StateEnteredEventDetails object Required: No stateExitedEventDetails Type: StateExitedEventDetails object Required: No taskFailedEventDetails Contains details about the failure of a task. Type: TaskFailedEventDetails object Required: No taskScheduledEventDetails Contains details about a task that was scheduled. Type: TaskScheduledEventDetails object Required: No taskStartedEventDetails Contains details about a task that was started. Type: TaskStartedEventDetails object Required: No Contents API Version 2016-11-23 219 API Reference AWS Step Functions taskStartFailedEventDetails Contains details about a task that failed to start. Type: TaskStartFailedEventDetails object Required: No taskSubmitFailedEventDetails Contains details about a task that where the submit failed. Type: TaskSubmitFailedEventDetails object Required: No taskSubmittedEventDetails Contains details about a submitted task. Type: TaskSubmittedEventDetails object Required: No taskSucceededEventDetails Contains details about a task that succeeded. Type: TaskSucceededEventDetails object Required: No taskTimedOutEventDetails Contains details about a task that timed out. Type: TaskTimedOutEventDetails object Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: See Also API Version 2016-11-23 220 AWS Step Functions • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 API Reference See Also API Version 2016-11-23 221 AWS Step Functions API Reference HistoryEventExecutionDataDetails Provides details about input or output in an execution history event. Contents truncated Indicates whether input or output was truncated in the response. Always false for API calls. In CloudWatch logs, the value will be true if the data is truncated due to size limits. Type: Boolean Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 HistoryEventExecutionDataDetails API Version 2016-11-23 222 AWS Step Functions InspectionData API Reference Contains additional details about the state's execution, including its input and output data processing flow, and HTTP request and response information. Contents afterArguments The input after Step Functions applies an Arguments filter. This event will only be present when QueryLanguage for the state machine or individual states is set to JSONata. For more info, see Transforming data with Step Functions. Type: String Length Constraints: Maximum length of 262144. Required: No afterInputPath The input after Step Functions applies the InputPath filter. Not populated when QueryLanguage is JSONata. Type: String Length Constraints: Maximum length of 262144. Required: No afterParameters The effective input after Step Functions applies the Parameters filter. Not populated when QueryLanguage is JSONata. Type: String Length Constraints: Maximum length of 262144. Required: No afterResultPath The effective result combined with the raw state input after Step Functions applies the ResultPath filter. Not populated when QueryLanguage is JSONata. InspectionData API Version 2016-11-23 223 AWS Step Functions Type: String Length Constraints: Maximum length of 262144. Required: No afterResultSelector API Reference The effective result after Step Functions applies the ResultSelector filter. Not populated when QueryLanguage is JSONata. Type: String Length Constraints: Maximum length of 262144. Required: No input The raw state input. Type: String Length Constraints: Maximum length of
step-functions-api-046
step-functions-api.pdf
46
Parameters filter. Not populated when QueryLanguage is JSONata. Type: String Length Constraints: Maximum length of 262144. Required: No afterResultPath The effective result combined with the raw state input after Step Functions applies the ResultPath filter. Not populated when QueryLanguage is JSONata. InspectionData API Version 2016-11-23 223 AWS Step Functions Type: String Length Constraints: Maximum length of 262144. Required: No afterResultSelector API Reference The effective result after Step Functions applies the ResultSelector filter. Not populated when QueryLanguage is JSONata. Type: String Length Constraints: Maximum length of 262144. Required: No input The raw state input. Type: String Length Constraints: Maximum length of 262144. Required: No request The raw HTTP request that is sent when you test an HTTP Task. Type: InspectionDataRequest object Required: No response The raw HTTP response that is returned when you test an HTTP Task. Type: InspectionDataResponse object Required: No result The state's raw result. Contents API Version 2016-11-23 224 AWS Step Functions Type: String Length Constraints: Maximum length of 262144. Required: No variables API Reference JSON string that contains the set of workflow variables after execution of the state. The set will include variables assigned in the state and variables set up as test state input. Type: String Length Constraints: Maximum length of 262144. Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API Version 2016-11-23 225 AWS Step Functions API Reference InspectionDataRequest Contains additional details about the state's execution, including its input and output data processing flow, and HTTP request information. Contents body The request body for the HTTP request. Type: String Required: No headers The request headers associated with the HTTP request. Type: String Required: No method The HTTP method used for the HTTP request. Type: String Required: No protocol The protocol used to make the HTTP request. Type: String Required: No url The API endpoint used for the HTTP request. Type: String Required: No InspectionDataRequest API Version 2016-11-23 226 AWS Step Functions See Also API Reference For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API Version 2016-11-23 227 AWS Step Functions API Reference InspectionDataResponse Contains additional details about the state's execution, including its input and output data processing flow, and HTTP response information. The inspectionLevel request parameter specifies which details are returned. Contents body The HTTP response returned. Type: String Required: No headers The response headers associated with the HTTP response. Type: String Required: No protocol The protocol used to return the HTTP response. Type: String Required: No statusCode The HTTP response status code for the HTTP response. Type: String Required: No statusMessage The message associated with the HTTP status code. Type: String InspectionDataResponse API Version 2016-11-23 228 AWS Step Functions Required: No See Also API Reference For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API Version 2016-11-23 229 AWS Step Functions API Reference LambdaFunctionFailedEventDetails Contains details about a Lambda function that failed during an execution. Contents cause A more detailed explanation of the cause of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 32768. Required: No error The error code of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 256. Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 LambdaFunctionFailedEventDetails API Version 2016-11-23 230 AWS Step Functions API Reference LambdaFunctionScheduledEventDetails Contains details about a Lambda function scheduled during an execution. Contents resource The Amazon Resource Name (ARN) of the scheduled Lambda function. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Required: Yes input The JSON data input to the Lambda function. Length constraints apply to the payload size, and are expressed as bytes in UTF-8 encoding. Type: String Length Constraints: Maximum length of 262144. Required: No inputDetails Contains details about input for an execution history event. Type: HistoryEventExecutionDataDetails object Required: No taskCredentials The credentials that Step Functions uses for the task. Type: TaskCredentials object Required: No timeoutInSeconds The maximum allowed duration of the Lambda function. LambdaFunctionScheduledEventDetails API Version 2016-11-23 231 AWS Step Functions Type: Long Required: No See Also API Reference For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ •
step-functions-api-047
step-functions-api.pdf
47
to the payload size, and are expressed as bytes in UTF-8 encoding. Type: String Length Constraints: Maximum length of 262144. Required: No inputDetails Contains details about input for an execution history event. Type: HistoryEventExecutionDataDetails object Required: No taskCredentials The credentials that Step Functions uses for the task. Type: TaskCredentials object Required: No timeoutInSeconds The maximum allowed duration of the Lambda function. LambdaFunctionScheduledEventDetails API Version 2016-11-23 231 AWS Step Functions Type: Long Required: No See Also API Reference For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API Version 2016-11-23 232 AWS Step Functions API Reference LambdaFunctionScheduleFailedEventDetails Contains details about a failed Lambda function schedule event that occurred during an execution. Contents cause A more detailed explanation of the cause of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 32768. Required: No error The error code of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 256. Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 LambdaFunctionScheduleFailedEventDetails API Version 2016-11-23 233 AWS Step Functions API Reference LambdaFunctionStartFailedEventDetails Contains details about a lambda function that failed to start during an execution. Contents cause A more detailed explanation of the cause of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 32768. Required: No error The error code of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 256. Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 LambdaFunctionStartFailedEventDetails API Version 2016-11-23 234 AWS Step Functions API Reference LambdaFunctionSucceededEventDetails Contains details about a Lambda function that successfully terminated during an execution. Contents output The JSON data output by the Lambda function. Length constraints apply to the payload size, and are expressed as bytes in UTF-8 encoding. Type: String Length Constraints: Maximum length of 262144. Required: No outputDetails Contains details about the output of an execution history event. Type: HistoryEventExecutionDataDetails object Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 LambdaFunctionSucceededEventDetails API Version 2016-11-23 235 AWS Step Functions API Reference LambdaFunctionTimedOutEventDetails Contains details about a Lambda function timeout that occurred during an execution. Contents cause A more detailed explanation of the cause of the timeout. Type: String Length Constraints: Minimum length of 0. Maximum length of 32768. Required: No error The error code of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 256. Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 LambdaFunctionTimedOutEventDetails API Version 2016-11-23 236 AWS Step Functions LogDestination Contents cloudWatchLogsLogGroup API Reference An object describing a CloudWatch log group. For more information, see AWS::Logs::LogGroup in the AWS CloudFormation User Guide. Type: CloudWatchLogsLogGroup object Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 LogDestination API Version 2016-11-23 237 AWS Step Functions API Reference LoggingConfiguration The LoggingConfiguration data type is used to set CloudWatch Logs options. Contents destinations An array of objects that describes where your execution history events will be logged. Limited to size 1. Required, if your log level is not set to OFF. Type: Array of LogDestination objects Required: No includeExecutionData Determines whether execution data is included in your log. When set to false, data is excluded. Type: Boolean Required: No level Defines which category of execution history events are logged. Type: String Valid Values: ALL | ERROR | FATAL | OFF Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 LoggingConfiguration API Version 2016-11-23 238 AWS Step Functions API Reference See Also API Version 2016-11-23 239 AWS Step Functions API Reference MapIterationEventDetails Contains details about an iteration of a Map state. Contents index The index of the array belonging to the Map state iteration. Type: Integer
step-functions-api-048
step-functions-api.pdf
48
execution history events are logged. Type: String Valid Values: ALL | ERROR | FATAL | OFF Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 LoggingConfiguration API Version 2016-11-23 238 AWS Step Functions API Reference See Also API Version 2016-11-23 239 AWS Step Functions API Reference MapIterationEventDetails Contains details about an iteration of a Map state. Contents index The index of the array belonging to the Map state iteration. Type: Integer Valid Range: Minimum value of 0. Required: No name The name of the iteration’s parent Map state. Type: String Length Constraints: Minimum length of 1. Maximum length of 80. Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 MapIterationEventDetails API Version 2016-11-23 240 AWS Step Functions API Reference MapRunExecutionCounts Contains details about all of the child workflow executions started by a Map Run. Contents aborted The total number of child workflow executions that were started by a Map Run and were running, but were either stopped by the user or by Step Functions because the Map Run failed. Type: Long Valid Range: Minimum value of 0. Required: Yes failed The total number of child workflow executions that were started by a Map Run, but have failed. Type: Long Valid Range: Minimum value of 0. Required: Yes pending The total number of child workflow executions that were started by a Map Run, but haven't started executing yet. Type: Long Valid Range: Minimum value of 0. Required: Yes resultsWritten Returns the count of child workflow executions whose results were written by ResultWriter. For more information, see ResultWriter in the AWS Step Functions Developer Guide. Type: Long MapRunExecutionCounts API Version 2016-11-23 241 AWS Step Functions API Reference Valid Range: Minimum value of 0. Required: Yes running The total number of child workflow executions that were started by a Map Run and are currently in-progress. Type: Long Valid Range: Minimum value of 0. Required: Yes succeeded The total number of child workflow executions that were started by a Map Run and have completed successfully. Type: Long Valid Range: Minimum value of 0. Required: Yes timedOut The total number of child workflow executions that were started by a Map Run and have timed out. Type: Long Valid Range: Minimum value of 0. Required: Yes total The total number of child workflow executions that were started by a Map Run. Type: Long Valid Range: Minimum value of 0. Required: Yes Contents API Version 2016-11-23 242 AWS Step Functions failuresNotRedrivable API Reference The number of FAILED, ABORTED, or TIMED_OUT child workflow executions that cannot be redriven because their execution status is terminal. For example, child workflows with an execution status of FAILED, ABORTED, or TIMED_OUT and a redriveStatus of NOT_REDRIVABLE. Type: Long Required: No pendingRedrive The number of unsuccessful child workflow executions currently waiting to be redriven. The status of these child workflow executions could be FAILED, ABORTED, or TIMED_OUT in the original execution attempt or a previous redrive attempt. Type: Long Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API Version 2016-11-23 243 AWS Step Functions API Reference MapRunFailedEventDetails Contains details about a Map Run failure event that occurred during a state machine execution. Contents cause A more detailed explanation of the cause of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 32768. Required: No error The error code of the Map Run failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 256. Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 MapRunFailedEventDetails API Version 2016-11-23 244 AWS Step Functions MapRunItemCounts API Reference Contains details about items that were processed in all of the child workflow executions that were started by a Map Run. Contents aborted The total number of items processed in child workflow executions that were either stopped by the user or by Step Functions, because the Map Run failed. Type: Long Valid Range: Minimum value of 0. Required: Yes failed The total number of items processed in child workflow executions that have failed. Type: Long Valid Range: Minimum value of 0. Required: Yes pending The total number of items to process in child workflow executions
step-functions-api-049
step-functions-api.pdf
49
Step Functions MapRunItemCounts API Reference Contains details about items that were processed in all of the child workflow executions that were started by a Map Run. Contents aborted The total number of items processed in child workflow executions that were either stopped by the user or by Step Functions, because the Map Run failed. Type: Long Valid Range: Minimum value of 0. Required: Yes failed The total number of items processed in child workflow executions that have failed. Type: Long Valid Range: Minimum value of 0. Required: Yes pending The total number of items to process in child workflow executions that haven't started running yet. Type: Long Valid Range: Minimum value of 0. Required: Yes resultsWritten Returns the count of items whose results were written by ResultWriter. For more information, see ResultWriter in the AWS Step Functions Developer Guide. MapRunItemCounts API Version 2016-11-23 245 AWS Step Functions Type: Long Valid Range: Minimum value of 0. Required: Yes running API Reference The total number of items being processed in child workflow executions that are currently in- progress. Type: Long Valid Range: Minimum value of 0. Required: Yes succeeded The total number of items processed in child workflow executions that have completed successfully. Type: Long Valid Range: Minimum value of 0. Required: Yes timedOut The total number of items processed in child workflow executions that have timed out. Type: Long Valid Range: Minimum value of 0. Required: Yes total The total number of items processed in all the child workflow executions started by a Map Run. Type: Long Valid Range: Minimum value of 0. Contents API Version 2016-11-23 246 AWS Step Functions Required: Yes failuresNotRedrivable API Reference The number of FAILED, ABORTED, or TIMED_OUT items in child workflow executions that cannot be redriven because the execution status of those child workflows is terminal. For example, child workflows with an execution status of FAILED, ABORTED, or TIMED_OUT and a redriveStatus of NOT_REDRIVABLE. Type: Long Required: No pendingRedrive The number of unsuccessful items in child workflow executions currently waiting to be redriven. Type: Long Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API Version 2016-11-23 247 API Reference AWS Step Functions MapRunListItem Contains details about a specific Map Run. Contents executionArn The executionArn of the execution from which the Map Run was started. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Required: Yes mapRunArn The Amazon Resource Name (ARN) of the Map Run. Type: String Length Constraints: Minimum length of 1. Maximum length of 2000. Required: Yes startDate The date on which the Map Run started. Type: Timestamp Required: Yes stateMachineArn The Amazon Resource Name (ARN) of the executed state machine. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Required: Yes stopDate The date on which the Map Run stopped. MapRunListItem API Version 2016-11-23 248 AWS Step Functions Type: Timestamp Required: No See Also API Reference For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API Version 2016-11-23 249 AWS Step Functions API Reference MapRunRedrivenEventDetails Contains details about a Map Run that was redriven. Contents mapRunArn The Amazon Resource Name (ARN) of a Map Run that was redriven. Type: String Length Constraints: Minimum length of 1. Maximum length of 2000. Required: No redriveCount The number of times the Map Run has been redriven at this point in the execution's history including this event. The redrive count for a redriven Map Run is always greater than 0. Type: Integer Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 MapRunRedrivenEventDetails API Version 2016-11-23 250 AWS Step Functions API Reference MapRunStartedEventDetails Contains details about a Map Run that was started during a state machine execution. Contents mapRunArn The Amazon Resource Name (ARN) of a Map Run that was started. Type: String Length Constraints: Minimum length of 1. Maximum length of 2000. Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 MapRunStartedEventDetails API Version 2016-11-23 251 AWS Step Functions API Reference MapStateStartedEventDetails Details about a Map state that was started. Contents length The size of the array for Map state iterations. Type: Integer Valid Range: Minimum value of 0. Required: No See Also
step-functions-api-050
step-functions-api.pdf
50
(ARN) of a Map Run that was started. Type: String Length Constraints: Minimum length of 1. Maximum length of 2000. Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 MapRunStartedEventDetails API Version 2016-11-23 251 AWS Step Functions API Reference MapStateStartedEventDetails Details about a Map state that was started. Contents length The size of the array for Map state iterations. Type: Integer Valid Range: Minimum value of 0. Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 MapStateStartedEventDetails API Version 2016-11-23 252 AWS Step Functions API Reference RoutingConfigurationListItem Contains details about the routing configuration of a state machine alias. In a routing configuration, you define an array of objects that specify up to two state machine versions. You also specify the percentage of traffic to be routed to each version. Contents stateMachineVersionArn The Amazon Resource Name (ARN) that identifies one or two state machine versions defined in the routing configuration. If you specify the ARN of a second version, it must belong to the same state machine as the first version. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Required: Yes weight The percentage of traffic you want to route to a state machine version. The sum of the weights in the routing configuration must be equal to 100. Type: Integer Valid Range: Minimum value of 0. Maximum value of 100. Required: Yes See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 RoutingConfigurationListItem API Version 2016-11-23 253 AWS Step Functions API Reference See Also API Version 2016-11-23 254 AWS Step Functions API Reference StateEnteredEventDetails Contains details about a state entered during an execution. Contents name The name of the state. Type: String Length Constraints: Minimum length of 1. Maximum length of 80. Required: Yes input The string that contains the JSON input data for the state. Length constraints apply to the payload size, and are expressed as bytes in UTF-8 encoding. Type: String Length Constraints: Maximum length of 262144. Required: No inputDetails Contains details about the input for an execution history event. Type: HistoryEventExecutionDataDetails object Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 StateEnteredEventDetails API Version 2016-11-23 255 AWS Step Functions • AWS SDK for Ruby V3 API Reference See Also API Version 2016-11-23 256 AWS Step Functions API Reference StateExitedEventDetails Contains details about an exit from a state during an execution. Contents name The name of the state. A name must not contain: • white space • brackets < > { } [ ] • wildcard characters ? * • special characters " # % \ ^ | ~ ` $ & , ; : / • control characters (U+0000-001F, U+007F-009F, U+FFFE-FFFF) • surrogates (U+D800-DFFF) • invalid characters ( U+10FFFF) To enable logging with CloudWatch Logs, the name should only contain 0-9, A-Z, a-z, - and _. Type: String Length Constraints: Minimum length of 1. Maximum length of 80. Required: Yes assignedVariables Map of variable name and value as a serialized JSON representation. Type: String to string map Required: No assignedVariablesDetails Provides details about input or output in an execution history event. Type: AssignedVariablesDetails object StateExitedEventDetails API Version 2016-11-23 257 AWS Step Functions Required: No output API Reference The JSON output data of the state. Length constraints apply to the payload size, and are expressed as bytes in UTF-8 encoding. Type: String Length Constraints: Maximum length of 262144. Required: No outputDetails Contains details about the output of an execution history event. Type: HistoryEventExecutionDataDetails object Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API Version 2016-11-23 258 AWS Step Functions API Reference StateMachineAliasListItem Contains details about a specific state machine alias. Contents creationDate The creation date of a state machine alias. Type: Timestamp Required: Yes stateMachineAliasArn The Amazon Resource Name (ARN) that identifies a state machine alias. The alias ARN is a combination of state machine ARN and the alias name separated by a colon (:). For example, stateMachineARN:PROD. Type: String Length Constraints: Minimum length of 1. Maximum length of 2000. Required: Yes See Also For
step-functions-api-051
step-functions-api.pdf
51
SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API Version 2016-11-23 258 AWS Step Functions API Reference StateMachineAliasListItem Contains details about a specific state machine alias. Contents creationDate The creation date of a state machine alias. Type: Timestamp Required: Yes stateMachineAliasArn The Amazon Resource Name (ARN) that identifies a state machine alias. The alias ARN is a combination of state machine ARN and the alias name separated by a colon (:). For example, stateMachineARN:PROD. Type: String Length Constraints: Minimum length of 1. Maximum length of 2000. Required: Yes See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 StateMachineAliasListItem API Version 2016-11-23 259 AWS Step Functions API Reference StateMachineListItem Contains details about the state machine. Contents creationDate The date the state machine is created. Type: Timestamp Required: Yes name The name of the state machine. A name must not contain: • white space • brackets < > { } [ ] • wildcard characters ? * • special characters " # % \ ^ | ~ ` $ & , ; : / • control characters (U+0000-001F, U+007F-009F, U+FFFE-FFFF) • surrogates (U+D800-DFFF) • invalid characters ( U+10FFFF) To enable logging with CloudWatch Logs, the name should only contain 0-9, A-Z, a-z, - and _. Type: String Length Constraints: Minimum length of 1. Maximum length of 80. Required: Yes stateMachineArn The Amazon Resource Name (ARN) that identifies the state machine. Type: String StateMachineListItem API Version 2016-11-23 260 AWS Step Functions API Reference Length Constraints: Minimum length of 1. Maximum length of 256. Required: Yes type Type: String Valid Values: STANDARD | EXPRESS Required: Yes See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API Version 2016-11-23 261 AWS Step Functions API Reference StateMachineVersionListItem Contains details about a specific state machine version. Contents creationDate The creation date of a state machine version. Type: Timestamp Required: Yes stateMachineVersionArn The Amazon Resource Name (ARN) that identifies a state machine version. The version ARN is a combination of state machine ARN and the version number separated by a colon (:). For example, stateMachineARN:1. Type: String Length Constraints: Minimum length of 1. Maximum length of 2000. Required: Yes See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 StateMachineVersionListItem API Version 2016-11-23 262 AWS Step Functions Tag API Reference Tags are key-value pairs that can be associated with Step Functions state machines and activities. An array of key-value pairs. For more information, see Using Cost Allocation Tags in the AWS Billing and Cost Management User Guide, and Controlling Access Using IAM Tags. Tags may only contain Unicode letters, digits, white space, or these symbols: _ . : / = + - @. Contents key The key of a tag. Type: String Length Constraints: Minimum length of 1. Maximum length of 128. Required: No value The value of a tag. Type: String Length Constraints: Minimum length of 0. Maximum length of 256. Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 Tag API Version 2016-11-23 263 AWS Step Functions TaskCredentials API Reference Contains details about the credentials that Step Functions uses for a task. Contents roleArn The ARN of an IAM role that Step Functions assumes for the task. The role can allow cross- account access to resources. Type: String Length Constraints: Minimum length of 1. Maximum length of 2000. Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 TaskCredentials API Version 2016-11-23 264 AWS Step Functions API Reference TaskFailedEventDetails Contains details about a task failure event. Contents resource The action of the resource called by a task state. Type: String Length Constraints: Minimum length of 1. Maximum length of 80. Required: Yes resourceType The service name of the resource in a task state. Type: String Length Constraints: Minimum length of 1. Maximum length of 80. Required: Yes cause A more detailed explanation of the cause of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 32768. Required: No error The error code of the
step-functions-api-052
step-functions-api.pdf
52
TaskCredentials API Version 2016-11-23 264 AWS Step Functions API Reference TaskFailedEventDetails Contains details about a task failure event. Contents resource The action of the resource called by a task state. Type: String Length Constraints: Minimum length of 1. Maximum length of 80. Required: Yes resourceType The service name of the resource in a task state. Type: String Length Constraints: Minimum length of 1. Maximum length of 80. Required: Yes cause A more detailed explanation of the cause of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 32768. Required: No error The error code of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 256. Required: No TaskFailedEventDetails API Version 2016-11-23 265 AWS Step Functions See Also API Reference For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API Version 2016-11-23 266 AWS Step Functions API Reference TaskScheduledEventDetails Contains details about a task scheduled during an execution. Contents parameters The JSON data passed to the resource referenced in a task state. Length constraints apply to the payload size, and are expressed as bytes in UTF-8 encoding. Type: String Length Constraints: Minimum length of 0. Maximum length of 262144. Required: Yes region The region of the scheduled task Type: String Length Constraints: Minimum length of 1. Maximum length of 80. Required: Yes resource The action of the resource called by a task state. Type: String Length Constraints: Minimum length of 1. Maximum length of 80. Required: Yes resourceType The service name of the resource in a task state. Type: String Length Constraints: Minimum length of 1. Maximum length of 80. TaskScheduledEventDetails API Version 2016-11-23 267 AWS Step Functions Required: Yes heartbeatInSeconds The maximum allowed duration between two heartbeats for the task. API Reference Type: Long Required: No taskCredentials The credentials that Step Functions uses for the task. Type: TaskCredentials object Required: No timeoutInSeconds The maximum allowed duration of the task. Type: Long Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API Version 2016-11-23 268 AWS Step Functions API Reference TaskStartedEventDetails Contains details about the start of a task during an execution. Contents resource The action of the resource called by a task state. Type: String Length Constraints: Minimum length of 1. Maximum length of 80. Required: Yes resourceType The service name of the resource in a task state. Type: String Length Constraints: Minimum length of 1. Maximum length of 80. Required: Yes See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 TaskStartedEventDetails API Version 2016-11-23 269 AWS Step Functions API Reference TaskStartFailedEventDetails Contains details about a task that failed to start during an execution. Contents resource The action of the resource called by a task state. Type: String Length Constraints: Minimum length of 1. Maximum length of 80. Required: Yes resourceType The service name of the resource in a task state. Type: String Length Constraints: Minimum length of 1. Maximum length of 80. Required: Yes cause A more detailed explanation of the cause of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 32768. Required: No error The error code of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 256. Required: No TaskStartFailedEventDetails API Version 2016-11-23 270 AWS Step Functions See Also API Reference For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API Version 2016-11-23 271 AWS Step Functions API Reference TaskSubmitFailedEventDetails Contains details about a task that failed to submit during an execution. Contents resource The action of the resource called by a task state. Type: String Length Constraints: Minimum length of 1. Maximum length of 80. Required: Yes resourceType The service name of the resource in a task state. Type: String Length Constraints: Minimum length of 1. Maximum length of 80. Required: Yes cause A more detailed explanation of the cause of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 32768. Required: No error The error code of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 256. Required: No TaskSubmitFailedEventDetails API Version 2016-11-23 272 AWS Step Functions See Also API Reference For more information about using this API
step-functions-api-053
step-functions-api.pdf
53
Minimum length of 1. Maximum length of 80. Required: Yes resourceType The service name of the resource in a task state. Type: String Length Constraints: Minimum length of 1. Maximum length of 80. Required: Yes cause A more detailed explanation of the cause of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 32768. Required: No error The error code of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 256. Required: No TaskSubmitFailedEventDetails API Version 2016-11-23 272 AWS Step Functions See Also API Reference For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API Version 2016-11-23 273 AWS Step Functions API Reference TaskSubmittedEventDetails Contains details about a task submitted to a resource . Contents resource The action of the resource called by a task state. Type: String Length Constraints: Minimum length of 1. Maximum length of 80. Required: Yes resourceType The service name of the resource in a task state. Type: String Length Constraints: Minimum length of 1. Maximum length of 80. Required: Yes output The response from a resource when a task has started. Length constraints apply to the payload size, and are expressed as bytes in UTF-8 encoding. Type: String Length Constraints: Maximum length of 262144. Required: No outputDetails Contains details about the output of an execution history event. Type: HistoryEventExecutionDataDetails object Required: No TaskSubmittedEventDetails API Version 2016-11-23 274 AWS Step Functions See Also API Reference For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API Version 2016-11-23 275 AWS Step Functions API Reference TaskSucceededEventDetails Contains details about the successful completion of a task state. Contents resource The action of the resource called by a task state. Type: String Length Constraints: Minimum length of 1. Maximum length of 80. Required: Yes resourceType The service name of the resource in a task state. Type: String Length Constraints: Minimum length of 1. Maximum length of 80. Required: Yes output The full JSON response from a resource when a task has succeeded. This response becomes the output of the related task. Length constraints apply to the payload size, and are expressed as bytes in UTF-8 encoding. Type: String Length Constraints: Maximum length of 262144. Required: No outputDetails Contains details about the output of an execution history event. Type: HistoryEventExecutionDataDetails object Required: No TaskSucceededEventDetails API Version 2016-11-23 276 AWS Step Functions See Also API Reference For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API Version 2016-11-23 277 AWS Step Functions API Reference TaskTimedOutEventDetails Contains details about a resource timeout that occurred during an execution. Contents resource The action of the resource called by a task state. Type: String Length Constraints: Minimum length of 1. Maximum length of 80. Required: Yes resourceType The service name of the resource in a task state. Type: String Length Constraints: Minimum length of 1. Maximum length of 80. Required: Yes cause A more detailed explanation of the cause of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 32768. Required: No error The error code of the failure. Type: String Length Constraints: Minimum length of 0. Maximum length of 256. Required: No TaskTimedOutEventDetails API Version 2016-11-23 278 AWS Step Functions See Also API Reference For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API Version 2016-11-23 279 AWS Step Functions API Reference TracingConfiguration Selects whether or not the state machine's AWS X-Ray tracing is enabled. Default is false Contents enabled When set to true, AWS X-Ray tracing is enabled. Type: Boolean Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 TracingConfiguration API Version 2016-11-23 280 AWS Step Functions API Reference ValidateStateMachineDefinitionDiagnostic Describes potential issues found during state machine validation. Rather than raise an exception, validation will return a list of diagnostic elements containing diagnostic information. Note The ValidateStateMachineDefinitionlAPI might add new diagnostics in the future, adjust diagnostic codes, or change the message wording. Your automated processes should only rely on the value of the result field value (OK, FAIL). Do not rely on the exact order,
step-functions-api-054
step-functions-api.pdf
54
the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 TracingConfiguration API Version 2016-11-23 280 AWS Step Functions API Reference ValidateStateMachineDefinitionDiagnostic Describes potential issues found during state machine validation. Rather than raise an exception, validation will return a list of diagnostic elements containing diagnostic information. Note The ValidateStateMachineDefinitionlAPI might add new diagnostics in the future, adjust diagnostic codes, or change the message wording. Your automated processes should only rely on the value of the result field value (OK, FAIL). Do not rely on the exact order, count, or wording of diagnostic messages. List of warning codes NO_DOLLAR No .$ on a field that appears to be a JSONPath or Intrinsic Function. NO_PATH Field value looks like a path, but field name does not end with 'Path'. PASS_RESULT_IS_STATIC Attempt to use a path in the result of a pass state. List of error codes INVALID_JSON_DESCRIPTION JSON syntax problem found. MISSING_DESCRIPTION Received a null or empty workflow input. SCHEMA_VALIDATION_FAILED Schema validation reported errors. INVALID_RESOURCE The value of a Task-state resource field is invalid. ValidateStateMachineDefinitionDiagnostic API Version 2016-11-23 281 API Reference AWS Step Functions MISSING_END_STATE The workflow does not have a terminal state. DUPLICATE_STATE_NAME The same state name appears more than once. INVALID_STATE_NAME The state name does not follow the naming convention. STATE_MACHINE_NAME_EMPTY The state machine name has not been specified. STATE_MACHINE_NAME_INVALID The state machine name does not follow the naming convention. STATE_MACHINE_NAME_TOO_LONG The state name exceeds the allowed length. STATE_MACHINE_NAME_ALREADY_EXISTS The state name already exists. DUPLICATE_LABEL_NAME A label name appears more than once. INVALID_LABEL_NAME You have provided an invalid label name. MISSING_TRANSITION_TARGET The value of "Next" field doesn't match a known state name. TOO_DEEPLY_NESTED The states are too deeply nested. Contents code Identifying code for the diagnostic. Contents API Version 2016-11-23 282 API Reference AWS Step Functions Type: String Required: Yes message Message describing the diagnostic condition. Type: String Required: Yes severity A value of ERROR means that you cannot create or update a state machine with this definition. WARNING level diagnostics alert you to potential issues, but they will not prevent you from creating or updating your state machine. Type: String Valid Values: ERROR | WARNING Required: Yes location Location of the issue in the state machine, if available. For errors specific to a field, the location could be in the format: /States/<StateName>/ <FieldName>, for example: /States/FailState/ErrorPath. Type: String Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 See Also API Version 2016-11-23 283 AWS Step Functions • AWS SDK for Ruby V3 API Reference See Also API Version 2016-11-23 284 AWS Step Functions API Reference Common Parameters The following list contains the parameters that all actions use for signing Signature Version 4 requests with a query string. Any action-specific parameters are listed in the topic for that action. For more information about Signature Version 4, see Signing AWS API requests in the IAM User Guide. Action The action to be performed. Type: string Required: Yes Version The API version that the request is written for, expressed in the format YYYY-MM-DD. Type: string Required: Yes X-Amz-Algorithm The hash algorithm that you used to create the request signature. Condition: Specify this parameter when you include authentication information in a query string instead of in the HTTP authorization header. Type: string Valid Values: AWS4-HMAC-SHA256 Required: Conditional X-Amz-Credential The credential scope value, which is a string that includes your access key, the date, the region you are targeting, the service you are requesting, and a termination string ("aws4_request"). The value is expressed in the following format: access_key/YYYYMMDD/region/service/ aws4_request. API Version 2016-11-23 285 AWS Step Functions API Reference For more information, see Create a signed AWS API request in the IAM User Guide. Condition: Specify this parameter when you include authentication information in a query string instead of in the HTTP authorization header. Type: string Required: Conditional X-Amz-Date The date that is used to create the signature. The format must be ISO 8601 basic format (YYYYMMDD'T'HHMMSS'Z'). For example, the following date time is a valid X-Amz-Date value: 20120325T120000Z. Condition: X-Amz-Date is optional for all requests; it can be used to override the date used for signing requests. If the Date header is specified in the ISO 8601 basic format, X-Amz-Date is not required. When X-Amz-Date is used, it always overrides the value of the Date header. For more information, see Elements of an AWS API request signature in the IAM User Guide. Type: string Required: Conditional X-Amz-Security-Token The temporary security token that was obtained through a call to AWS Security Token Service (AWS STS). For a list of services that support temporary security credentials from AWS STS, see
step-functions-api-055
step-functions-api.pdf
55
Condition: X-Amz-Date is optional for all requests; it can be used to override the date used for signing requests. If the Date header is specified in the ISO 8601 basic format, X-Amz-Date is not required. When X-Amz-Date is used, it always overrides the value of the Date header. For more information, see Elements of an AWS API request signature in the IAM User Guide. Type: string Required: Conditional X-Amz-Security-Token The temporary security token that was obtained through a call to AWS Security Token Service (AWS STS). For a list of services that support temporary security credentials from AWS STS, see AWS services that work with IAM in the IAM User Guide. Condition: If you're using temporary security credentials from AWS STS, you must include the security token. Type: string Required: Conditional X-Amz-Signature Specifies the hex-encoded signature that was calculated from the string to sign and the derived signing key. Condition: Specify this parameter when you include authentication information in a query string instead of in the HTTP authorization header. API Version 2016-11-23 286 AWS Step Functions Type: string Required: Conditional X-Amz-SignedHeaders API Reference Specifies all the HTTP headers that were included as part of the canonical request. For more information about specifying signed headers, see Create a signed AWS API request in the IAM User Guide. Condition: Specify this parameter when you include authentication information in a query string instead of in the HTTP authorization header. Type: string Required: Conditional API Version 2016-11-23 287 AWS Step Functions API Reference Common Errors This section lists the errors common to the API actions of all AWS services. For errors specific to an API action for this service, see the topic for that API action. AccessDeniedException You do not have sufficient access to perform this action. HTTP Status Code: 400 IncompleteSignature The request signature does not conform to AWS standards. HTTP Status Code: 400 InternalFailure The request processing has failed because of an unknown error, exception or failure. HTTP Status Code: 500 InvalidAction The action or operation requested is invalid. Verify that the action is typed correctly. HTTP Status Code: 400 InvalidClientTokenId The X.509 certificate or AWS access key ID provided does not exist in our records. HTTP Status Code: 403 NotAuthorized You do not have permission to perform this action. HTTP Status Code: 400 OptInRequired The AWS access key ID needs a subscription for the service. HTTP Status Code: 403 API Version 2016-11-23 288 AWS Step Functions RequestExpired API Reference The request reached the service more than 15 minutes after the date stamp on the request or more than 15 minutes after the request expiration date (such as for pre-signed URLs), or the date stamp on the request is more than 15 minutes in the future. HTTP Status Code: 400 ServiceUnavailable The request has failed due to a temporary failure of the server. HTTP Status Code: 503 ThrottlingException The request was denied due to request throttling. HTTP Status Code: 400 ValidationError The input fails to satisfy the constraints specified by an AWS service. HTTP Status Code: 400 API Version 2016-11-23 289
step-functions-dg-001
step-functions-dg.pdf
1
Developer Guide AWS Step Functions Copyright © 2025 Amazon Web Services, Inc. and/or its affiliates. All rights reserved. AWS Step Functions Developer Guide AWS Step Functions: Developer Guide Copyright © 2025 Amazon Web Services, Inc. and/or its affiliates. All rights reserved. Amazon's trademarks and trade dress may not be used in connection with any product or service that is not Amazon's, in any manner that is likely to cause confusion among customers, or in any manner that disparages or discredits Amazon. All other trademarks not owned by Amazon are the property of their respective owners, who may or may not be affiliated with, connected to, or sponsored by Amazon. AWS Step Functions Table of Contents Developer Guide What is Step Functions? .................................................................................................................. 1 Standard and Express workflows types ................................................................................................... 3 .................................................................................................................................................................... 4 Integrating with other services ................................................................................................................. 4 Example use cases for workflows ............................................................................................................. 7 .................................................................................................................................................................... 7 Use cases ........................................................................................................................................ 11 Data processing .......................................................................................................................................... 11 Machine learning ........................................................................................................................................ 12 Microservice orchestration ....................................................................................................................... 14 IT and security automation ...................................................................................................................... 15 Getting started tutorial ................................................................................................................. 17 What you will build ................................................................................................................................... 17 Step 1 - Create your state machine ....................................................................................................... 19 Overview of Workflow Studio ............................................................................................................ 20 Overview of the state machine ......................................................................................................... 21 View the workflow code (ASL) ........................................................................................................... 22 (Actually) Create the state machine ................................................................................................. 23 Step 2 - Start your state machine ......................................................................................................... 25 Review the execution details .............................................................................................................. 26 Step 3 - Process external input .............................................................................................................. 29 Remove the hard-coded input ........................................................................................................... 30 Run the updated workflow, with input data ................................................................................... 30 Review workflow executions .............................................................................................................. 31 Step 4 - Integrate a service ..................................................................................................................... 32 How do integrations work? ................................................................................................................ 33 Step 4.1 - Add sentiment analysis state .......................................................................................... 34 Step 4.2 - Configure the sentiment analysis state ........................................................................ 34 Step 4.3 - Configure an identity policy ............................................................................................ 35 Step 4.4 - Run your state machine ................................................................................................... 36 Clean up resources ..................................................................................................................................... 38 State machines .............................................................................................................................. 39 Key concepts ............................................................................................................................................... 41 State Machine Data ................................................................................................................................... 43 iii AWS Step Functions Developer Guide Data Format ........................................................................................................................................... 44 State Machine Input/Output .............................................................................................................. 44 State Input/Output .............................................................................................................................. 45 Invoke Step Functions ............................................................................................................................... 46 Transitions in state machines .................................................................................................................. 47 Transitions in Distributed Map state ................................................................................................. 48 Read Consistency ........................................................................................................................................ 48 Activities ......................................................................................................................................... 49 Overview ...................................................................................................................................................... 49 APIs Related to Activity Tasks ............................................................................................................ 49 Waiting for an Activity Task to Complete ............................................................................................. 50 Example: Activity Worker in Ruby .......................................................................................................... 51 Next Steps ................................................................................................................................................... 52 Choosing workflow type ............................................................................................................... 53 Express Workflow types ............................................................................................................................ 56 Execution guarantees ................................................................................................................................ 57 Amazon States Language .............................................................................................................. 59 Example Amazon States Language Specification (JSONata) ............................................................. 59 State machine structure ........................................................................................................................... 61 Common state fields ............................................................................................................................ 63 Intrinsic functions ....................................................................................................................................... 64 Fields that support intrinsic functions ............................................................................................. 66 Intrinsics for arrays ............................................................................................................................... 66 Intrinsics for data encoding and decoding ...................................................................................... 71 Intrinsic for hash calculation .............................................................................................................. 72 Intrinsics for JSON data manipulation ............................................................................................. 73 Intrinsics for Math operations ............................................................................................................ 75 Intrinsic for String operation .............................................................................................................. 77 Intrinsic for unique identifier generation ........................................................................................ 78 Intrinsic for generic operation ........................................................................................................... 79 Reserved characters in intrinsic functions ....................................................................................... 80 Workflow states ............................................................................................................................. 81 Reference list of workflow states ........................................................................................................... 83 Task ............................................................................................................................................................... 83 Task types ............................................................................................................................................... 85 Task state fields .................................................................................................................................... 88 iv AWS Step Functions Developer Guide Task state definition examples .......................................................................................................... 91 Choice ........................................................................................................................................................... 94 Choice Rules (JSONata) ....................................................................................................................... 95 Choice Rules (JSONPath) ..................................................................................................................... 96 Parallel ........................................................................................................................................................ 100 Parallel State Example ...................................................................................................................... 101 Parallel State Input and Output Processing ................................................................................. 103 Error Handling ..................................................................................................................................... 105 Map ............................................................................................................................................................. 105 Map processing modes ...................................................................................................................... 106 Inline mode .......................................................................................................................................... 108 Distributed mode ................................................................................................................................ 118 Pass ............................................................................................................................................................. 132 Pass State Example (JSONPath) ...................................................................................................... 134 Wait ............................................................................................................................................................. 134 Wait State Examples .......................................................................................................................... 136 Succeed ...................................................................................................................................................... 137 Fail ............................................................................................................................................................... 137 Fail state definition examples .......................................................................................................... 139 Tutorials and Workshops ............................................................................................................ 141 Tutorials ..................................................................................................................................................... 142 Create a state machine using AWS SAM ............................................................................................. 144 Prerequisites ........................................................................................................................................ 144 Step 1: Download a Sample AWS SAM Application .................................................................... 145 Step 2: Build Your Application ........................................................................................................ 146 Step 3: Deploy Your Application to the AWS Cloud .................................................................... 147 Troubleshooting .................................................................................................................................. 148 Clean Up ............................................................................................................................................... 149 Examine executions ................................................................................................................................. 149 Step 1: Create and test the required Lambda functions ............................................................ 150 Step 2: Create and execute the state machine ............................................................................ 153 Step 3: View the state machine execution details ....................................................................... 156 Step 4: Explore the different View modes ..................................................................................... 156 Create a state machine that uses Lambda ......................................................................................... 158 Step 1: Create a Lambda function .................................................................................................. 159 Step 2: Test the Lambda function .................................................................................................. 160 v AWS Step Functions Developer Guide Step 3: Create a state machine ....................................................................................................... 160 Step 4: Run the state machine ........................................................................................................ 162 Wait for human approval ....................................................................................................................... 163 Step 1: Create a Template ................................................................................................................ 164 Step 2: Create a stack ....................................................................................................................... 164 Step 3: Approve the SNS subscription ........................................................................................... 165 Step 4: Run the state
step-functions-dg-002
step-functions-dg.pdf
2
153 Step 3: View the state machine execution details ....................................................................... 156 Step 4: Explore the different View modes ..................................................................................... 156 Create a state machine that uses Lambda ......................................................................................... 158 Step 1: Create a Lambda function .................................................................................................. 159 Step 2: Test the Lambda function .................................................................................................. 160 v AWS Step Functions Developer Guide Step 3: Create a state machine ....................................................................................................... 160 Step 4: Run the state machine ........................................................................................................ 162 Wait for human approval ....................................................................................................................... 163 Step 1: Create a Template ................................................................................................................ 164 Step 2: Create a stack ....................................................................................................................... 164 Step 3: Approve the SNS subscription ........................................................................................... 165 Step 4: Run the state machine ........................................................................................................ 165 Template Source Code ...................................................................................................................... 168 Repeat actions with Inline Map ............................................................................................................ 178 Step 1: Create the workflow prototype ......................................................................................... 178 Step 2: Configure input and output ............................................................................................... 179 Step 3: Review and save auto-generated definition ................................................................... 180 Step 4: Run the state machine ........................................................................................................ 182 Copy large-scale CSV using Distributed Map ..................................................................................... 183 Prerequisites ........................................................................................................................................ 184 Step 1: Create the workflow prototype ......................................................................................... 184 Step 2: Configure the required fields for Map state ................................................................... 185 Step 3: Configure additional options ............................................................................................. 186 Step 4: Configure the Lambda function ........................................................................................ 187 Step 5: Update the workflow prototype ....................................................................................... 188 Step 6: Review the auto-generated Amazon States Language definition and save the workflow ............................................................................................................................................... 188 Step 7: Run the state machine ........................................................................................................ 190 Iterate a loop with Lambda ................................................................................................................... 191 Step 1: Create a Lambda function to iterate a count ................................................................. 192 Step 2: Test the Lambda Function ................................................................................................. 193 Step 3: Create a State Machine ....................................................................................................... 194 Step 4: Start a New Execution ........................................................................................................ 197 Process batch data with Lambda ......................................................................................................... 198 Step 1: Create the state machine ................................................................................................... 198 Step 2: Create the Lambda function .............................................................................................. 200 Step 3: Run the state machine ........................................................................................................ 201 Process individual items with Lambda ................................................................................................ 203 Step 1: Create the state machine ................................................................................................... 203 Step 2: Create the Lambda function .............................................................................................. 206 Step 3: Run the state machine ........................................................................................................ 201 vi AWS Step Functions Developer Guide Start a workflow from EventBridge ..................................................................................................... 210 Prerequisite: Create a State Machine ............................................................................................. 210 Step 1: Create a Bucket in Amazon S3 .......................................................................................... 211 Step 2: Enable Amazon S3 Event Notification with EventBridge ............................................. 211 Step 3: Create an Amazon EventBridge Rule ............................................................................... 212 Step 4: Test the Rule ......................................................................................................................... 213 Example of Execution Input ............................................................................................................. 214 Create an API using API Gateway ........................................................................................................ 214 Step 1: Create an IAM Role for API Gateway ............................................................................... 215 Step 2: Create your API Gateway API ............................................................................................ 216 Step 3: Test and Deploy the API Gateway API ............................................................................. 217 Handle error conditions .......................................................................................................................... 219 Step 1: Create a Lambda function that fails ................................................................................ 220 Step 2: Test the Lambda function .................................................................................................. 221 Step 3: Create a state machine with a Catch field ...................................................................... 221 Step 4: Run the state machine ........................................................................................................ 223 Create an Activity state machine ......................................................................................................... 225 Step 1: Create an Activity ................................................................................................................. 225 Step 2: Create a state machine ....................................................................................................... 226 Step 3: Implement a Worker ............................................................................................................ 228 Step 4: Run the state machine ........................................................................................................ 230 Step 5: Run and Stop the Worker ................................................................................................... 231 View X-Ray traces .................................................................................................................................... 232 Step 1: Create an IAM role for Lambda ......................................................................................... 232 Step 2: Create a Lambda function .................................................................................................. 233 Step 3: Create two more Lambda functions ................................................................................. 234 Step 4: Create a state machine ....................................................................................................... 235 Step 5: Run the state machine ........................................................................................................ 237 Gather Amazon S3 bucket info ............................................................................................................ 240 Step 1: Create the state machine ................................................................................................... 240 Step 2: Add the necessary IAM role permissions ......................................................................... 242 Step 3: Run a Standard state machine execution ........................................................................ 243 Step 4: Run an Express state machine execution ........................................................................ 244 Continue long-running workflows using Step Functions API (recommended) ............................ 245 Step 1: Create a long-running state machine .............................................................................. 245 Step 2: Create a state machine to call the Step Functions API action ..................................... 245 vii AWS Step Functions Developer Guide Step 3: Update the IAM policy ........................................................................................................ 247 Step 4: Run the state machine ........................................................................................................ 248 Using Lambda to continue a workflow ............................................................................................... 249 Prerequisites ........................................................................................................................................ 250 Step 1: Create a Lambda function to iterate a count ................................................................. 250 Step 2: Create a Restart Lambda function to start a new Step Functions execution ............ 253 Step 3: Create a state machine ....................................................................................................... 254 Step 4: Update the IAM Policy ........................................................................................................ 258 Step 5: Run the state machine ........................................................................................................ 258 Access cross-account resources ............................................................................................................. 261 Prerequisites ........................................................................................................................................ 262 Step 1: Update the Task state definition to specify the target role ......................................... 262 Step 2: Update the target role's trust policy ................................................................................ 264 Step 3: Add the required permission in the target role ............................................................. 265 Step 4: Add permission in execution role to assume the target role ....................................... 265 Workshops ................................................................................................................................................. 266 Starter templates ........................................................................................................................ 268 Manage a container
step-functions-dg-003
step-functions-dg.pdf
3
start a new Step Functions execution ............ 253 Step 3: Create a state machine ....................................................................................................... 254 Step 4: Update the IAM Policy ........................................................................................................ 258 Step 5: Run the state machine ........................................................................................................ 258 Access cross-account resources ............................................................................................................. 261 Prerequisites ........................................................................................................................................ 262 Step 1: Update the Task state definition to specify the target role ......................................... 262 Step 2: Update the target role's trust policy ................................................................................ 264 Step 3: Add the required permission in the target role ............................................................. 265 Step 4: Add permission in execution role to assume the target role ....................................... 265 Workshops ................................................................................................................................................. 266 Starter templates ........................................................................................................................ 268 Manage a container task ........................................................................................................................ 269 Step 1: Create the state machine ................................................................................................... 269 Step 2: Run the demo state machine ............................................................................................ 270 Transfer data records .............................................................................................................................. 270 Step 1: Create the state machine ................................................................................................... 271 Step 2: Run the demo state machine ............................................................................................ 271 Job poller ................................................................................................................................................... 272 Step 1: Create the state machine ................................................................................................... 272 Step 2: Run the demo state machine ............................................................................................ 273 Task timer .................................................................................................................................................. 273 Step 1: Create the state machine ................................................................................................... 274 Step 2: Run the demo state machine ............................................................................................ 274 Callback pattern example ...................................................................................................................... 275 Step 1: Create the state machine ................................................................................................... 275 Step 2: Run the demo state machine ............................................................................................ 275 Manage an Amazon EMR job ................................................................................................................ 276 Step 1: Create the state machine ................................................................................................... 276 Step 2: Run the demo state machine ............................................................................................ 270 Run an EMR Serverless job .................................................................................................................... 277 viii AWS Step Functions Developer Guide Step 1: Create the state machine ................................................................................................... 278 Step 2: Run the demo state machine ............................................................................................ 278 Start a workflow within a workflow .................................................................................................... 279 Step 1: Create the state machine ................................................................................................... 279 Step 2: Run the demo state machine ............................................................................................ 279 Process data with a Map ........................................................................................................................ 280 Step 1: Create the state machine ................................................................................................... 280 Step 2: Subscribe to the Amazon SNS topic ................................................................................ 280 Step 3: Add messages to the Amazon SQS queue ...................................................................... 281 Step 4: Run the state machine ........................................................................................................ 281 Distributed Map to process a CSV file in S3 ...................................................................................... 282 Step 1: Create the state machine ................................................................................................... 282 Step 2: Run the demo state machine ............................................................................................ 283 Distributed Map to process files in S3 ................................................................................................ 283 Step 1: Create the state machine ................................................................................................... 284 Step 2: Run the demo state machine ............................................................................................ 285 Train a machine learning model ........................................................................................................... 285 Step 1: Create the state machine ................................................................................................... 286 Step 2: Run the demo state machine ............................................................................................ 286 Tune a machine learning model ........................................................................................................... 287 Step 1: Create the state machine ................................................................................................... 287 Step 2: Run the demo state machine ............................................................................................ 288 Perform AI prompt-chaining with Amazon Bedrock ........................................................................ 288 Prerequisites ........................................................................................................................................ 289 Step 1: Create the state machine ................................................................................................... 289 Step 2: Run the demo state machine ............................................................................................ 290 Process high-volume messages from SQS ......................................................................................... 290 Step 1: Create the state machine ................................................................................................... 291 Step 2: Trigger the state machine execution ................................................................................ 291 Selective checkpointing example ......................................................................................................... 292 Step 1: Create the State Machine ................................................................................................... 293 Step 2: Run the demo state machine ............................................................................................ 293 Start a CodeBuild build .......................................................................................................................... 294 Step 1: Create the state machine ................................................................................................... 294 Step 2: Run the demo state machine ............................................................................................ 294 Preprocess data and train a machine learning model ...................................................................... 295 ix AWS Step Functions Developer Guide Step 1: Create the state machine ................................................................................................... 295 Step 2: Run the demo state machine ............................................................................................ 296 Orchestrate Lambda functions ............................................................................................................. 296 Step 1: Create the state machine ................................................................................................... 298 Step 2: Run the demo state machine ............................................................................................ 298 Start an Athena query ............................................................................................................................ 299 Step 1: Create the state machine ................................................................................................... 299 Step 2: Run the demo state machine ............................................................................................ 299 Execute queries in sequence and parallel using Athena .................................................................. 300 Step 1: Create the state machine ................................................................................................... 300 Step 2: Run the demo state machine ............................................................................................ 301 Query large datasets ............................................................................................................................... 301 Step 1: Create the state machine ................................................................................................... 301 Step 2: Run the demo state machine ............................................................................................ 302 Keep data up to date .............................................................................................................................. 302 Step 1: Create the state machine ................................................................................................... 302 Step 2: Run the demo state machine ............................................................................................ 303 Manage an Amazon EKS cluster ........................................................................................................... 303 Step 1: Create the state machine ................................................................................................... 304 Step 2: Run the demo state machine ............................................................................................ 304 Make a call to API Gateway ................................................................................................................... 305 Step 1: Create the state .................................................................................................................... 305 Step 2: Run the demo state machine ............................................................................................ 306 Call a microservice with API Gateway ................................................................................................. 306 Step 1: Create the state machine ................................................................................................... 306 Step 2: Run the demo state machine ............................................................................................ 307 Send a custom event to EventBridge .................................................................................................. 307 Step 1: Create the state machine ................................................................................................... 308 Step 2: Run the demo state machine ............................................................................................ 308 Invoke Synchronous Express Workflows through API Gateway ...................................................... 309 Step 1: Create the state machine ................................................................................................... 309 Step 2: Run the demo state
step-functions-dg-004
step-functions-dg.pdf
4
machine ............................................................................................ 304 Make a call to API Gateway ................................................................................................................... 305 Step 1: Create the state .................................................................................................................... 305 Step 2: Run the demo state machine ............................................................................................ 306 Call a microservice with API Gateway ................................................................................................. 306 Step 1: Create the state machine ................................................................................................... 306 Step 2: Run the demo state machine ............................................................................................ 307 Send a custom event to EventBridge .................................................................................................. 307 Step 1: Create the state machine ................................................................................................... 308 Step 2: Run the demo state machine ............................................................................................ 308 Invoke Synchronous Express Workflows through API Gateway ...................................................... 309 Step 1: Create the state machine ................................................................................................... 309 Step 2: Run the demo state machine ............................................................................................ 310 ETL job in Amazon Redshift .................................................................................................................. 310 Step 1: Create the state machine ................................................................................................... 311 Step 2: Run the demo state machine ............................................................................................ 312 Manage a batch job ................................................................................................................................ 312 x AWS Step Functions Developer Guide Step 1: Create the state machine ................................................................................................... 312 Step 2: Run the demo state machine ............................................................................................ 270 Fan out a batch job ................................................................................................................................. 313 Step 1: Create the state machine ................................................................................................... 314 Step 2: Run the demo state machine ............................................................................................ 314 Batch job with Lambda .......................................................................................................................... 314 Step 1: Create the state machine ................................................................................................... 315 Step 2: Run the demo state machine ............................................................................................ 315 Developing workflows ................................................................................................................. 316 Defining your workflow .......................................................................................................................... 317 Running and debugging your workflows ............................................................................................ 324 Deploying your workflows ..................................................................................................................... 325 Using Workflow Studio ........................................................................................................................... 326 Design mode ........................................................................................................................................ 327 Code mode ........................................................................................................................................... 330 Config mode ........................................................................................................................................ 332 Create a workflow .............................................................................................................................. 333 Configure input and output ............................................................................................................. 341 Set up execution roles ....................................................................................................................... 348 Configure error handling .................................................................................................................. 354 Using Workflow Studio in Infrastructure Composer ................................................................... 356 Using AWS SAM ....................................................................................................................................... 360 Why use Step Functions with AWS SAM? ...................................................................................... 360 Step Functions integration with the AWS SAM specification .................................................... 361 Step Functions integration with the SAM CLI .............................................................................. 361 DefinitionSubstitutions in AWS SAM templates ........................................................................... 362 Next steps ............................................................................................................................................ 366 Create a state machine with CloudFormation ................................................................................... 367 Step 1: Set up your AWS CloudFormation template .................................................................. 367 Step 2: Use the AWS CloudFormation template to create a Lambda State Machine ............ 372 Step 3: Start a State Machine execution ....................................................................................... 377 Using CDK to create a Standard workflow ......................................................................................... 378 Step 1: Set up your AWS CDK project ........................................................................................... 379 Step 2: Use AWS CDK to create a state machine ........................................................................ 380 Step 3: Start a state machine execution ....................................................................................... 389 Step 4: Clean Up ................................................................................................................................ 390 xi AWS Step Functions Developer Guide Next steps ............................................................................................................................................ 390 Using CDK to create an Express workflow ......................................................................................... 391 Step 1: Set Up Your AWS CDK Project ........................................................................................... 391 Step 2: Use the AWS CDK to create an API Gateway REST API with Synchronous Express State Machine backend integration ................................................................................................ 395 Step 3: Test the API Gateway .......................................................................................................... 404 Step 4: Clean Up ................................................................................................................................ 406 Using Terraform to deploy workflows ................................................................................................. 406 Prerequisites ........................................................................................................................................ 407 Development lifecycle with Terraform ........................................................................................... 407 IAM roles and policies for your state machine ............................................................................. 409 Exporting to IaC templates .................................................................................................................... 410 Template configuration options ...................................................................................................... 411 Export and download IaC template ............................................................................................... 412 Export IaC template to AWS Infrastructure Composer ............................................................... 412 Starting state machines .............................................................................................................. 415 Start from a Task ..................................................................................................................................... 415 Associate Workflow Executions ....................................................................................................... 417 Using EventBridge Scheduler ................................................................................................................ 418 Set up the execution role ................................................................................................................. 418 Create a schedule ............................................................................................................................... 419 Related resources ................................................................................................................................ 423 Viewing workflow runs ........................................................................................................................... 423 Execution details ................................................................................................................................. 424 Standard and Express differences ................................................................................................... 431 Limitations viewing Express workflow executions ....................................................................... 432 Redriving state machines ....................................................................................................................... 433 Redrive eligibility for unsuccessful executions ............................................................................. 434 Redrive behavior of individual states ............................................................................................. 434 IAM permission to redrive an execution ........................................................................................ 436 Redriving executions in console ...................................................................................................... 436 Redriving executions using API ........................................................................................................ 438 Examining redriven executions ........................................................................................................ 438 Retry behavior of redriven executions ........................................................................................... 440 Viewing Map Runs ................................................................................................................................... 442 Map Run execution summary .......................................................................................................... 442 xii AWS Step Functions Developer Guide Error message ...................................................................................................................................... 443 Item processing status ...................................................................................................................... 443 Listing executions ............................................................................................................................... 445 Redriving Map Runs ................................................................................................................................ 446 Redrive eligibility for child workflows in a Map Run .................................................................. 447 Child workflow execution redrive behavior .................................................................................. 448 Scenarios of input used on Map Run redrive ............................................................................... 449 IAM permission to redrive a Map Run ............................................................................................ 450 Redriving Map Run in console ......................................................................................................... 451 Redriving Map Run using API .......................................................................................................... 452 Processing input and output ...................................................................................................... 454 Passing data with variables ................................................................................................................... 457 Conceptual overview of variables ................................................................................................... 457 Reserved variable : $states ............................................................................................................... 459 Variable name syntax ........................................................................................................................ 459 Variable scope ..................................................................................................................................... 460 Assign field in ASL ............................................................................................................................. 460 Evaluation order in an assign field ................................................................................................. 462 Limits ..................................................................................................................................................... 463 Using variables in JSONPath states ................................................................................................ 463 Transforming data ................................................................................................................................... 465 QueryLanguage field ......................................................................................................................... 468 Writing JSONata expressions ........................................................................................................... 468 Reserved variable : $states ............................................................................................................... 469 Handling expression errors ............................................................................................................... 470 Converting to
step-functions-dg-005
step-functions-dg.pdf
5
Run ............................................................................................ 450 Redriving Map Run in console ......................................................................................................... 451 Redriving Map Run using API .......................................................................................................... 452 Processing input and output ...................................................................................................... 454 Passing data with variables ................................................................................................................... 457 Conceptual overview of variables ................................................................................................... 457 Reserved variable : $states ............................................................................................................... 459 Variable name syntax ........................................................................................................................ 459 Variable scope ..................................................................................................................................... 460 Assign field in ASL ............................................................................................................................. 460 Evaluation order in an assign field ................................................................................................. 462 Limits ..................................................................................................................................................... 463 Using variables in JSONPath states ................................................................................................ 463 Transforming data ................................................................................................................................... 465 QueryLanguage field ......................................................................................................................... 468 Writing JSONata expressions ........................................................................................................... 468 Reserved variable : $states ............................................................................................................... 469 Handling expression errors ............................................................................................................... 470 Converting to JSONata ..................................................................................................................... 470 JSONata examples .............................................................................................................................. 473 JSONata functions .............................................................................................................................. 476 Context object .......................................................................................................................................... 479 Accessing the Context object ........................................................................................................... 479 Context object fields .......................................................................................................................... 480 Context object data for Map states ................................................................................................ 481 Using JSONPath paths ............................................................................................................................ 484 Reference Paths .................................................................................................................................. 484 Manipulate parameters with paths ...................................................................................................... 486 InputPath .............................................................................................................................................. 486 xiii AWS Step Functions Developer Guide Parameters ........................................................................................................................................... 487 ResultSelector ...................................................................................................................................... 489 Example: Manipulating state data with paths ................................................................................... 492 Filtering state output ........................................................................................................................ 497 Specify state output with paths ........................................................................................................... 497 Replace input with result .................................................................................................................. 498 Discard Result and Keep Input ........................................................................................................ 499 Include Result with Input ................................................................................................................. 499 Update a Node in Input with Result .............................................................................................. 501 Include Error and Input in a Catch ............................................................................................... 501 Map state input and output fields in Step Functions ...................................................................... 502 ItemReader ........................................................................................................................................... 504 ItemsPath ............................................................................................................................................. 521 ItemSelector ......................................................................................................................................... 523 ItemBatcher .......................................................................................................................................... 525 ResultWriter ......................................................................................................................................... 530 Parsing input CSV files ...................................................................................................................... 541 Integrating services ..................................................................................................................... 544 Call other AWS services .......................................................................................................................... 544 AWS SDK integrations ....................................................................................................................... 544 Optimized integrations ...................................................................................................................... 545 Cross-account access .......................................................................................................................... 545 Integration pattern support .................................................................................................................. 545 Service integration patterns .................................................................................................................. 547 Integration pattern support ............................................................................................................. 545 Request Response ............................................................................................................................... 549 Run a Job (.sync) ................................................................................................................................ 550 Wait for Callback ................................................................................................................................ 552 Call HTTPS APIs ....................................................................................................................................... 558 Connectivity for an HTTP Task ........................................................................................................ 559 HTTP Task definition ......................................................................................................................... 560 HTTP Task fields ................................................................................................................................. 560 Merging EventBridge connection and HTTP Task definition data ............................................ 568 Applying URL-encoding on request body ...................................................................................... 571 IAM permissions to run an HTTP Task ........................................................................................... 573 HTTP Task example ............................................................................................................................ 574 xiv AWS Step Functions Developer Guide Testing an HTTP Task ........................................................................................................................ 576 Unsupported HTTP Task responses ................................................................................................ 578 Connection errors ............................................................................................................................... 579 Pass parameters ....................................................................................................................................... 579 Pass static JSON as parameters ...................................................................................................... 580 Pass state input as parameters using Paths ................................................................................. 580 Pass Context object nodes as parameters .................................................................................... 581 AWS SDK integrations ............................................................................................................................ 582 Using service integrations ................................................................................................................ 582 Supported service integrations ....................................................................................................... 584 Deprecated service integrations ...................................................................................................... 634 Integrating optimized services ................................................................................................... 635 Amazon API Gateway .............................................................................................................................. 637 API Gateway feature support ........................................................................................................... 637 Request format ................................................................................................................................... 638 Authentication and authorization ................................................................................................... 641 Service integration patterns ............................................................................................................. 642 Output format ..................................................................................................................................... 643 Error handling ..................................................................................................................................... 644 IAM policies .......................................................................................................................................... 644 Amazon Athena ........................................................................................................................................ 646 Supported APIs ................................................................................................................................... 647 IAM policies .......................................................................................................................................... 648 AWS Batch ................................................................................................................................................. 657 Supported APIs ................................................................................................................................... 658 IAM policies .......................................................................................................................................... 659 Amazon Bedrock ...................................................................................................................................... 661 Service integration APIs .................................................................................................................... 661 Task state definition .......................................................................................................................... 662 IAM policies .......................................................................................................................................... 663 AWS CodeBuild ......................................................................................................................................... 671 Supported APIs ................................................................................................................................... 672 ................................................................................................................................................................ 676 IAM policies .......................................................................................................................................... 676 Amazon DynamoDB ................................................................................................................................. 688 Supported APIs ................................................................................................................................... 690 xv AWS Step Functions Developer Guide IAM policies .......................................................................................................................................... 692 Amazon ECS/Fargate ............................................................................................................................... 693 Supported APIs ................................................................................................................................... 694 Passing Data to an Amazon ECS Task ............................................................................................ 694 IAM policies .......................................................................................................................................... 696 Amazon EKS .............................................................................................................................................. 699 Kubernetes API integrations ............................................................................................................ 701 Optimized Amazon EKS APIs ........................................................................................................... 707 Permissions .......................................................................................................................................... 711 IAM policies .......................................................................................................................................... 713 Amazon EMR ............................................................................................................................................. 717 Supported APIs ................................................................................................................................... 718 Examples ............................................................................................................................................... 726 IAM policies .......................................................................................................................................... 729 Amazon EMR on EKS .............................................................................................................................. 735 Amazon EMR Serverless ......................................................................................................................... 738 Service integration APIs .................................................................................................................... 739 Integration use cases ......................................................................................................................... 744 IAM policies .......................................................................................................................................... 747 Amazon EventBridge ............................................................................................................................... 764 Supported APIs ................................................................................................................................... 766 Error handling ..................................................................................................................................... 766 IAM policies .......................................................................................................................................... 767 AWS Glue ................................................................................................................................................... 768 Supported APIs ................................................................................................................................... 768 IAM policies .......................................................................................................................................... 769 AWS Glue DataBrew ................................................................................................................................ 770 Supported APIs ................................................................................................................................... 771 IAM policies .......................................................................................................................................... 771 AWS Lambda ............................................................................................................................................. 772 Supported APIs ................................................................................................................................... 772 Examples ............................................................................................................................................... 773 IAM policies .......................................................................................................................................... 775 AWS Elemental MediaConvert .............................................................................................................. 776 Supported APIs ................................................................................................................................... 779 IAM policies .......................................................................................................................................... 779 xvi AWS Step Functions Developer Guide Amazon SageMaker AI ............................................................................................................................ 782 Supported APIs ................................................................................................................................... 782 Transform Job Example .................................................................................................................... 786 Training Job Example ........................................................................................................................ 786 Labeling Job Example ........................................................................................................................ 789 Processing Job Example .................................................................................................................... 790 IAM policies .......................................................................................................................................... 792 Amazon SNS ............................................................................................................................................. 802 Supported APIs ................................................................................................................................... 804 IAM policies .......................................................................................................................................... 804 Amazon SQS ............................................................................................................................................. 805 Supported APIs ................................................................................................................................... 807 IAM policies .......................................................................................................................................... 808 AWS Step Functions ................................................................................................................................ 809 Supported APIs ................................................................................................................................... 809 Examples ............................................................................................................................................... 809 IAM policies .......................................................................................................................................... 812 Securing state machines ............................................................................................................. 815 Data protection ........................................................................................................................................ 815 Data at rest encryption ..................................................................................................................... 817 Data in transit encryption ................................................................................................................ 837 Identity and Access
step-functions-dg-006
step-functions-dg.pdf
6
Functions Developer Guide Amazon SageMaker AI ............................................................................................................................ 782 Supported APIs ................................................................................................................................... 782 Transform Job Example .................................................................................................................... 786 Training Job Example ........................................................................................................................ 786 Labeling Job Example ........................................................................................................................ 789 Processing Job Example .................................................................................................................... 790 IAM policies .......................................................................................................................................... 792 Amazon SNS ............................................................................................................................................. 802 Supported APIs ................................................................................................................................... 804 IAM policies .......................................................................................................................................... 804 Amazon SQS ............................................................................................................................................. 805 Supported APIs ................................................................................................................................... 807 IAM policies .......................................................................................................................................... 808 AWS Step Functions ................................................................................................................................ 809 Supported APIs ................................................................................................................................... 809 Examples ............................................................................................................................................... 809 IAM policies .......................................................................................................................................... 812 Securing state machines ............................................................................................................. 815 Data protection ........................................................................................................................................ 815 Data at rest encryption ..................................................................................................................... 817 Data in transit encryption ................................................................................................................ 837 Identity and Access Management ........................................................................................................ 837 Audience ............................................................................................................................................... 837 Authenticating with identities ......................................................................................................... 838 Managing access using policies ....................................................................................................... 841 Access Control ..................................................................................................................................... 844 How AWS Step Functions works with IAM .................................................................................... 844 Identity-based policy examples ....................................................................................................... 851 AWS managed policies ...................................................................................................................... 854 Creating a state machine IAM role ................................................................................................. 856 Creating granular permissions for non-admin users ................................................................... 858 Accessing cross-account AWS resources ........................................................................................ 861 Create VPC endpoints ........................................................................................................................ 866 IAM Policies for integrated services ............................................................................................... 869 Activities or no task workflows ....................................................................................................... 871 IAM policies for Distributed Maps ................................................................................................... 872 xvii AWS Step Functions Developer Guide Creating tag-based policies .............................................................................................................. 877 Troubleshooting identity and access .............................................................................................. 878 Compliance validation ............................................................................................................................ 880 Resilience ................................................................................................................................................... 881 Infrastructure security ............................................................................................................................. 881 Logging and monitoring ............................................................................................................. 883 Metrics in CloudWatch ............................................................................................................................ 883 CloudWatch metrics ........................................................................................................................... 884 Viewing metrics in CloudWatch ....................................................................................................... 894 Setting alarms in CloudWatch ......................................................................................................... 895 Automate event delivery ........................................................................................................................ 896 Step Functions events ....................................................................................................................... 897 Delivering Step Functions events .................................................................................................... 897 Triggering Step Functions state machines .................................................................................... 898 Events detail reference ...................................................................................................................... 899 API calls in CloudTrail ............................................................................................................................. 904 Data events in CloudTrail ................................................................................................................. 906 Management events in CloudTrail .................................................................................................. 907 Event examples ................................................................................................................................... 909 Logging in CloudWatch Logs ................................................................................................................ 911 Configure logging ............................................................................................................................... 911 CloudWatch Logs payloads .............................................................................................................. 912 IAM Policies for logging to CloudWatch Logs .............................................................................. 912 Event log levels ................................................................................................................................... 914 Trace data in X-Ray ................................................................................................................................. 918 Setup and configuration ................................................................................................................... 919 Concepts ............................................................................................................................................... 923 Service integrations ........................................................................................................................... 924 Viewing the X-Ray console ............................................................................................................... 925 Viewing X-Ray tracing information for Step Functions .............................................................. 925 Traces .................................................................................................................................................... 926 Service map ......................................................................................................................................... 926 Segments and subsegments ............................................................................................................ 928 Analytics ............................................................................................................................................... 929 Configuration ....................................................................................................................................... 929 What if there is no data in the trace map or service map? ....................................................... 930 xviii AWS Step Functions Developer Guide Events using User Notifications ............................................................................................................ 930 Testing and debugging ............................................................................................................... 931 Test with Test State ................................................................................................................................ 931 Data flow simulator (unsupported) ...................................................................................................... 931 Step Functions Local (unsupported) .................................................................................................... 931 Testing with TestState ............................................................................................................................ 932 Considerations about using the TestState API ............................................................................. 932 Using inspection levels in TestState API ........................................................................................ 933 IAM permissions for using TestState API ....................................................................................... 940 Testing a state (Console) .................................................................................................................. 941 Testing a state using AWS CLI ......................................................................................................... 942 Testing and debugging input and output data flow ................................................................... 948 Step Functions Local (unsupported) .................................................................................................... 952 Setting Up Step Functions Local and Docker ............................................................................... 953 Setting Up Step Functions Local - Java Version .......................................................................... 953 Configuring Step Functions Local Options ................................................................................... 955 Running Step Functions Local ......................................................................................................... 957 Tutorial: Testing using Step Functions and AWS SAM CLI Local ............................................... 959 Testing with mocked service integrations ..................................................................................... 963 Versions and aliases .................................................................................................................... 981 Versions ...................................................................................................................................................... 982 Publishing a state machine version (Console) .............................................................................. 983 Managing versions with APIs ........................................................................................................... 983 Running a state machine version from the console .................................................................... 984 Aliases ......................................................................................................................................................... 985 Creating a state machine alias (Console) ...................................................................................... 986 Managing aliases with APIs .............................................................................................................. 986 Alias routing configuration ............................................................................................................... 987 Running a state machine using an alias (Console) ...................................................................... 988 Versions and alias authorization ........................................................................................................... 988 Scoping down permissions ............................................................................................................... 989 Associating executions with a version or alias ................................................................................... 990 Viewing executions started with a version or an alias ................................................................ 991 Deployment example .............................................................................................................................. 994 Gradual deployment of versions .......................................................................................................... 997 Handling errors .......................................................................................................................... 1007 xix AWS Step Functions Developer Guide Error names ............................................................................................................................................ 1007 Retrying after an error ......................................................................................................................... 1010 Retry field examples ........................................................................................................................ 1012 Fallback states ........................................................................................................................................ 1014 Error output ....................................................................................................................................... 1016 Cause payloads and service integrations .................................................................................... 1016 State machine examples using Retry and using Catch .................................................................. 1017 Handling a failure using Retry ...................................................................................................... 1017 Handling a failure using Catch ...................................................................................................... 1019 Handling a timeout using Retry .................................................................................................... 1020 Handling a timeout using Catch ................................................................................................... 1021 Troubleshooting ......................................................................................................................... 1022 General issues ......................................................................................................................................... 1022 I'm unable to create a state machine. ......................................................................................... 1022 I'm unable to use a JsonPath to reference the previous task’s output. ................................. 1022 There was a delay in state transitions. ........................................................................................ 1023 When I start new Standard Workflow executions, they fail with the ExecutionLimitExceeded error. .............................................................................................. 1023 A failure on one branch in a parallel state causes the whole execution to fail. ................... 1023 Service integrations .............................................................................................................................. 1023 My job is complete in the downstream service, but in
step-functions-dg-007
step-functions-dg.pdf
7
1019 Handling a timeout using Retry .................................................................................................... 1020 Handling a timeout using Catch ................................................................................................... 1021 Troubleshooting ......................................................................................................................... 1022 General issues ......................................................................................................................................... 1022 I'm unable to create a state machine. ......................................................................................... 1022 I'm unable to use a JsonPath to reference the previous task’s output. ................................. 1022 There was a delay in state transitions. ........................................................................................ 1023 When I start new Standard Workflow executions, they fail with the ExecutionLimitExceeded error. .............................................................................................. 1023 A failure on one branch in a parallel state causes the whole execution to fail. ................... 1023 Service integrations .............................................................................................................................. 1023 My job is complete in the downstream service, but in Step Functions the task state remains "In progress" or its completion is delayed. .................................................................. 1023 I want to return a JSON output from a nested state machine execution. ............................ 1024 I can't invoke a Lambda function from another account. ........................................................ 1024 I'm unable to see task tokens passed from .waitForTaskToken states. .......................... 1025 Activities .................................................................................................................................................. 1026 My state machine execution is stuck at an activity state. ........................................................ 1026 My activity worker times out while waiting for a task token. ................................................. 1026 Express workflows ................................................................................................................................. 1027 My application times out before receiving a response from a StartSyncExecution API call. ...................................................................................................................................................... 1027 I'm unable to see the execution history in order to troubleshoot Express Workflow failures. ............................................................................................................................................... 1027 Best practices ............................................................................................................................. 1029 Optimizing with Express Workflows .................................................................................................. 1029 Nest workflows ................................................................................................................................. 1029 xx AWS Step Functions Developer Guide Convert to Express workflow type ............................................................................................... 1030 Tagging resources .................................................................................................................................. 1031 Tagging for Cost Allocation ........................................................................................................... 1032 Tagging for Security ........................................................................................................................ 1032 Managing tags in the Step Functions console ........................................................................... 1033 Managing tags with Step Functions API Actions ....................................................................... 1033 Using timeouts to avoid stuck executions ........................................................................................ 1034 Using Amazon S3 to pass large data ................................................................................................ 1035 Avoiding execution history quota ...................................................................................................... 1037 Handling Lambda exceptions .............................................................................................................. 1038 Avoiding latency for activity task tasks ............................................................................................ 1039 Log resource policy limits .................................................................................................................... 1040 Service quotas ........................................................................................................................... 1041 General quotas ....................................................................................................................................... 1042 Quotas related to accounts ................................................................................................................. 1042 Quotas related to HTTP Task ............................................................................................................. 1043 Quotas related to state throttling ..................................................................................................... 1044 Quotas related to API action throttling ........................................................................................... 1045 Quota related to TestState API ..................................................................................................... 1046 Other quotas ..................................................................................................................................... 1046 Quotas related to state machine executions ................................................................................... 1050 Quotas related to task executions ..................................................................................................... 1052 Quotas related to versions and aliases ............................................................................................. 1053 Restrictions related to tagging ........................................................................................................... 1053 Recent feature launches ............................................................................................................ 1055 Document history ...................................................................................................................... 1056 xxi AWS Step Functions Developer Guide What is Step Functions? Managing state and transforming data Learn about Passing data between states with variables and Transforming data with JSONata. With AWS Step Functions, you can create workflows, also called State machines, to build distributed applications, automate processes, orchestrate microservices, and create data and machine learning pipelines. Step Functions is based on state machines and tasks. In Step Functions, state machines are called workflows, which are a series of event-driven steps. Each step in a workflow is called a state. For example, a Task state represents a unit of work that another AWS service performs, such as calling another AWS service or API. Instances of running workflows performing tasks are called executions in Step Functions. The work in your state machine tasks can also be done using Activities which are workers that exist outside of Step Functions. 1 AWS Step Functions Developer Guide In the Step Functions' console, you can visualize, edit, and debug your application’s workflow. You can examine the state of each step in your workflow to make sure that your application runs in order and as expected. Depending on your use case, you can have Step Functions call AWS services, such as Lambda, to perform tasks. You can have Step Functions control AWS services, such as AWS Glue, to create extract, transform, and load workflows. You also can create long-running, automated workflows for applications that require human interaction. For a complete list of AWS Regions where Step Functions is available, see the AWS Region Table. 2 AWS Step Functions Developer Guide Learn how to use Step Functions Start with the Getting started tutorial in this guide. For advanced topics and use cases, see the modules in The Step Functions Workshop. Standard and Express workflows types Step Functions has two workflow types: • Standard workflows are ideal for long-running, auditable workflows, as they show execution history and visual debugging. Standard workflows have exactly-once workflow execution and can run for up to one year. This means that each step in a Standard workflow will execute exactly once. • Express workflows are ideal for high-event-rate workloads, such as streaming data processing and IoT data ingestion. Express workflows have at-least-once workflow execution and can run for up to five minutes. This means that one or more steps in an Express Workflow can potentially run more than once, while each step
step-functions-dg-008
step-functions-dg.pdf
8
Functions has two workflow types: • Standard workflows are ideal for long-running, auditable workflows, as they show execution history and visual debugging. Standard workflows have exactly-once workflow execution and can run for up to one year. This means that each step in a Standard workflow will execute exactly once. • Express workflows are ideal for high-event-rate workloads, such as streaming data processing and IoT data ingestion. Express workflows have at-least-once workflow execution and can run for up to five minutes. This means that one or more steps in an Express Workflow can potentially run more than once, while each step in the workflow executes at least once. Standard workflows Express workflows 2,000 per second execution rate 4,000 per second state transition rate 100,000 per second execution rate Nearly unlimited state transition rate Priced by state transition Priced by number and duration of executions Show execution history and visual debugging Show execution history and visual debugging based on log level See execution history in Step Functions Send execution history to CloudWatch Standard and Express workflows types 3 AWS Step Functions Developer Guide Standard workflows Express workflows Support integrations with all services. Support Request Response pattern for all services Support integrations with all services. Support optimized integrati ons with some services. Support Request Response pattern for all services Support Run a Job and/or Wait for Callback patterns in specific services (see following section for details) For more information on Step Functions pricing and choosing workflow type, see the following: • AWS Step Functions pricing • Choosing workflow type in Step Functions Integrating with other services Step Functions integrates with multiple AWS services. To call other AWS services, you can use two integration types: • AWS SDK integrations provide a way to call any AWS service directly from your state machine, giving you access to thousands of API actions. • Optimized integrations provide custom options for using those services in your state machines. To combine Step Functions with other services, there are three service integration patterns: • Request Response (default) Call a service, and let Step Functions progress to the next state after it gets an HTTP response. • Run a job (.sync) Integrating with other services 4 AWS Step Functions Developer Guide Call a service, and have Step Functions wait for a job to complete. • Wait for a callback with a task token (.waitForTaskToken) Call a service with a task token, and have Step Functions wait until the task token returns with a callback. Standard Workflows and Express Workflows support the same integrations but not the same integration patterns. • Standard Workflows support Request Response integrations. Certain services support Run a Job (.sync), or Wait for Callback (.waitForTaskToken) , and both in some cases. See the following optimized integrations table for details. • Express Workflows only support Request Response integrations. To help decide between the two types, see Choosing workflow type in Step Functions. AWS SDK integrations in Step Functions Integrated service Request Response Run a Job - .sync Wait for Callback - .waitForTaskToken Over two hundred services Standard & Express Not supported Standard Optimized integrations in Step Functions Integrated service Request Response Run a Job - .sync Wait for Callback - .waitForTaskToken Amazon API Gateway Standard & Express Not supported Standard Amazon Athena Standard & Express Standard Not supported AWS Batch Standard & Express Standard Not supported Amazon Bedrock Standard & Express Standard Standard Integrating with other services 5 AWS Step Functions Developer Guide Integrated service Request Response Run a Job - .sync Wait for Callback - .waitForTaskToken AWS CodeBuild Standard & Express Standard Not supported Amazon DynamoDB Standard & Express Not supported Not supported Amazon ECS/Fargate Standard & Express Standard Amazon EKS Standard & Express Standard Standard Standard Amazon EMR Standard & Express Standard Not supported Amazon EMR on EKS Standard & Express Standard Not supported Amazon EMR Serverless Standard & Express Standard Not supported Amazon EventBridge Standard & Express Not supported Standard AWS Glue Standard & Express Standard Not supported AWS Glue DataBrew Standard & Express Standard Not supported AWS Lambda Standard & Express Not supported Standard AWS Elemental MediaConvert Amazon SageMaker AI Standard & Express Standard Not supported Standard & Express Standard Not supported Amazon SNS Standard & Express Not supported Standard Amazon SQS Standard & Express Not supported Standard AWS Step Functions Standard & Express Standard Standard Integrating with other services 6 AWS Step Functions Developer Guide Example use cases for workflows Step Functions manages your application's components and logic, so you can write less code and focus on building and updating your application quickly. The following image shows six use cases for Step Functions workflows. Example use cases for workflows 7 AWS Step Functions Developer Guide Example use cases for workflows 8 AWS Step Functions Developer Guide 1. Orchestrate tasks – You can create workflows
step-functions-dg-009
step-functions-dg.pdf
9
& Express Not supported Standard Amazon SQS Standard & Express Not supported Standard AWS Step Functions Standard & Express Standard Standard Integrating with other services 6 AWS Step Functions Developer Guide Example use cases for workflows Step Functions manages your application's components and logic, so you can write less code and focus on building and updating your application quickly. The following image shows six use cases for Step Functions workflows. Example use cases for workflows 7 AWS Step Functions Developer Guide Example use cases for workflows 8 AWS Step Functions Developer Guide 1. Orchestrate tasks – You can create workflows that orchestrate a series of tasks, or steps, in a specific order. For example, Task A might be a Lambda function which provides inputs for another Lambda function in Task B. The last step in your workflow provides the final result. 2. Choose tasks based on data – Using a Choice state, you can have Step Functions make decisions based on the state’s input. For example, imagine that a customer requests a credit limit increase. If the request is more than your customer’s pre-approved credit limit, you can have Step Functions send your customer's request to a manager for sign-off. If the request is less than your customer’s pre-approved credit limit, you can have Step Functions approve the request automatically. 3. Error handling (Retry / Catch) – You can retry failed tasks, or catch failed tasks and automatically run alternative steps. For example, after a customer requests a username, perhaps the first call to your validation service fails, so your workflow may retry the request. When the second request is successful, the workflow can proceed. Or, perhaps the customer requested a username that is invalid or unavailable, a Catch statement could lead to a Step Functions workflow step that suggests an alternative username. For examples of Retry and Catch, see Handling errors in Step Functions workflows. 4. Human in the loop – Step Functions can include human approval steps in the workflow. For example, imagine a banking customer attempts to send funds to a friend. With a callback and a task token, you can have Step Functions wait until the customers friend confirms the transfer, and then Step Functions will continue the workflow to notify the banking customer that the transfer has completed. For an example, see Create a callback pattern example with Amazon SQS, Amazon SNS, and Lambda. 5. Process data in parallel steps – Using a Parallel state, Step Functions can process input data in parallel steps. For example, a customer might need to convert a video file into several display resolutions, so viewers can watch the video on multiple devices. Your workflow could send the original video file to several Lambda functions or use the optimized AWS Elemental MediaConvert integration to process a video into multiple display resolutions at the same time. 6. Dynamically process data elements – Using a Map state, Step Functions can run a set of workflow steps on each item in a dataset. The iterations run in parallel, which makes it possible to process a dataset quickly. For example, when your customer orders thirty items, your system needs to apply the same workflow to prepare each item for delivery. After all items have been Example use cases for workflows 9 AWS Step Functions Developer Guide gathered and packaged for delivery, the next step might be to quickly send your customer a confirmation email with tracking information. For an example starter template, see Process data with a Map. Example use cases for workflows 10 AWS Step Functions Developer Guide Discover use cases for Step Functions workflows With AWS Step Functions, you can build workflows that manage state over time, make decisions based on incoming data, and handle errors and exceptions. Use case categories • Data processing • Machine learning • Microservice orchestration • IT and security automation Data processing As the volume of data grows from diverse sources, organizations need to process their data faster so they can quickly make well-informed business decisions. To process data at scale, organizations need to elastically provision resources to manage the information they receive from mobile devices, applications, satellites, marketing and sales, operational data stores, infrastructure, and more. With horizontal scaling and fault-tolerant workflows, Step Functions can operate millions of concurrent executions. You can process your data faster using parallel executions with Parallel workflow state state. Or, you can use the dynamic parallelism of the Map workflow state state to iterate over large data sets in a data stores, such as Amazon S3 buckets. Step Functions also provide the capability to retry failed executions, or choose a specific path to handle errors without managing complex error handling processes. Step Functions directly integrates with other data processing services provided by AWS such as AWS Batch for batch processing, Amazon
step-functions-dg-010
step-functions-dg.pdf
10
With horizontal scaling and fault-tolerant workflows, Step Functions can operate millions of concurrent executions. You can process your data faster using parallel executions with Parallel workflow state state. Or, you can use the dynamic parallelism of the Map workflow state state to iterate over large data sets in a data stores, such as Amazon S3 buckets. Step Functions also provide the capability to retry failed executions, or choose a specific path to handle errors without managing complex error handling processes. Step Functions directly integrates with other data processing services provided by AWS such as AWS Batch for batch processing, Amazon EMR for big data processing, AWS Glue for data preparation, Athena for data analysis, and AWS Lambda for compute. Examples of the types of data processing workflows that customers use Step Functions to accomplish include: File, video, and image processing • Take a collection of video files and convert them to other sizes or resolutions that are ideal for the device they will be displayed on, such as mobile phones, laptops, or a television. Data processing 11 AWS Step Functions Developer Guide • Take a large collection of photos uploaded by users and convert them into thumbnails or various resolution images that can then be displayed on users’ websites. • Take semi-structured data, such as a CSV file, and combine it with unstructured data, such as an invoice, to produce a business report that is sent to business stakeholders monthly. • Take earth observing data collected from satellites, convert it into formats that align with each other and then add other data sources collected on earth for additional insight. • Take the transportation logs from various modes of transportation for products and look for optimizations using Monte Carlo Simulations and then send reports back to the organizations and people that are relying on you to ship their goods. Coordinate extract, transform and load (ETL) jobs: • Combine sales opportunity records with marketing metric datasets through a series of data preparation steps using AWS Glue, and produce business intelligence reports that can be used across the organization. • Create, start, and terminate an Amazon EMR cluster for big data processing. Batch processing and High Performance Computing (HPC) workloads: • Build a genomics secondary analysis pipeline that processes raw whole genome sequences into variant calls. Align raw files to a reference sequence, and call variants on a specified list of chromosomes using dynamic parallelism. • Find efficiencies in the production of your next mobile device or other electronics by simulating various layouts using different electric and chemical compounds. Run large batch processing of your workloads through various simulations to get the optimal design. Machine learning Machine learning provides a way for organizations to quickly analyze collected data to identify patterns and make decisions with minimal human intervention. Machine learning starts with an initial set of data, known as training data. Training data increases a machine learning model’s prediction accuracy and acts as the foundation through which the model learns. After the trained model is considered accurate enough to meet business needs, you can deploy the model into production. The AWS Step Functions Data Science Project on Github is an open-source library Machine learning 12 AWS Step Functions Developer Guide that provides workflows to preprocess data, train, and then publish your models using Amazon SageMaker AI and Step Functions. Preprocessing existing data sets is how an organization often creates training data. This preprocessing method adds information, such as by labeling objects in an image, annotating text or processing audio. To preprocess data you can use AWS Glue, or you can create an SageMaker AI notebook instance that runs in a Jupyter Notebook. After your data is ready, it can be uploaded to Amazon S3 for access. As machine learning models are trained, you can make adjustments to each model’s parameters to improve accuracy. Step Functions provides a way to orchestrate end-to-end machine learning workflows on SageMaker AI. These workflows can include data preprocessing, post-processing, feature engineering, data validation, and model evaluation. After the model has been deployed to production, you can refine and test new approaches to continually improve business outcomes. You can create production-ready workflows directly in Python, or you can use the Step Functions Data Science SDK to copy that workflow, experiment with new options, and place the refined workflow in production. Some types of machine learning workflows that customers use Step Functions for include: Fraud Detection • Identify and prevent fraudulent transactions, such as credit fraud, from occurring. • Detect and prevent account takeovers using trained machine learning models. • Identify promotional abuse, including the creation of fake accounts, so you can quickly take action. Personalization and Recommendations • Recommend products to targeted customers based upon what is predicted to attract their interest. • Predict whether a customer will upgrade
step-functions-dg-011
step-functions-dg.pdf
11
the Step Functions Data Science SDK to copy that workflow, experiment with new options, and place the refined workflow in production. Some types of machine learning workflows that customers use Step Functions for include: Fraud Detection • Identify and prevent fraudulent transactions, such as credit fraud, from occurring. • Detect and prevent account takeovers using trained machine learning models. • Identify promotional abuse, including the creation of fake accounts, so you can quickly take action. Personalization and Recommendations • Recommend products to targeted customers based upon what is predicted to attract their interest. • Predict whether a customer will upgrade their account from a free tier to a paid subscription. Data Enrichment • Use data enrichment as part of preprocessing to provide better training data for more accurate machine learning models. • Annotate text and audio excerpts to add syntactical information, such as sarcasm and slang. Machine learning 13 AWS Step Functions Developer Guide • Label additional objects in images to provide critical information for the model to learn from, such as whether an object is an apple, a basketball, a rock, or an animal. Microservice orchestration Step Functions gives you options to manage your microservice workflows. Microservice architecture breaks applications into loosely coupled services. Benefits include improved scalability, increased resiliency, and faster time to market. Each microservice is independent, making it easy to scale up a single service or function without needing to scale the entire application. Individual services are loosely coupled, so that independent teams can focus on a single business process, without needing to understand the entire application. Microservices also provide individual components that suit your business needs, giving you flexibility without rewriting your entire workflow. Different teams can use the programming languages and frameworks of their choice to work with their microservice. For long-running workflows you can use Standard Workflows with AWS Fargate integration to orchestrate applications running in containers. For short-duration, high-volume workflows that need an immediate response, Synchronous Express Workflows are ideal. One example are web- based or mobile applications, which require the completion of a series of steps before they return a response. You can directly trigger a Synchronous Express Workflows from Amazon API Gateway, and the connection is held open until the workflow completes or timeouts. For short duration workflows that do not require an immediate response, Step Functions provides Asynchronous Express Workflows. Examples of some API orchestrations that use Step Functions include: Synchronous or real-time workflows • Change a value in a record; such as updating an employee’s last name and making the change immediately visible. • Update an order during checkout, for example, adding, removing, or changing the quantity of an item; then immediately showing the updated cart to your customer. • Run a quick processing job and immediately return the result back to the requester. Container Orchestration Microservice orchestration 14 AWS Step Functions Developer Guide • Run jobs on Kubernetes with Amazon Elastic Kubernetes Service or on Amazon Elastic Container Service (ECS) with Fargate and integrate with other AWS services, such as sending notifications with Amazon SNS, as part of the same workflow. IT and security automation With Step Functions, you can create workflows that automatically scale and react to errors in your workflow. Your workflows can automatically retry failed tasks and use an exponential backoff to handle errors. Error handling is essential in IT automation scenarios to manage complex and time-consuming operations, such as upgrading and patching software, deploying security updates to address vulnerabilities, selecting infrastructure, synchronizing data, and routing support tickets. By automating repetitive and time-consuming tasks, your organization can complete routine operations quickly and consistently at scale. Your focus can shift to strategic efforts such as feature development, complex support requests, and innovation while meeting your operational demands. When human intervention is required for the workflow to proceed, for example approving a substantial credit increase, you can define branching logic in Step Functions, so that requests under a limit are automatically approved, and requests of the limit require human approval. When human approval is required, Step Functions can pause the workflow, wait for a human response, then continue the workflow after a response is received. Some examples automation workflows include the following: IT automation • Auto-remediate incidents like open SSH ports, low disk space, or when public access an Amazon S3 bucket is granted public access. • Automate the deployment of AWS CloudFormation StackSets. Security automation • Automate the response to a scenario where a user and user access key has been exposed. • Auto-remediate security incident responses according to policy actions, such as restricting action to specific ARNs. • Warn employees of phishing emails within seconds of receiving them. IT and security automation 15 AWS Step Functions Human Approval Developer Guide • Automate machine learning model training, then get approval of the model by a
step-functions-dg-012
step-functions-dg.pdf
12
incidents like open SSH ports, low disk space, or when public access an Amazon S3 bucket is granted public access. • Automate the deployment of AWS CloudFormation StackSets. Security automation • Automate the response to a scenario where a user and user access key has been exposed. • Auto-remediate security incident responses according to policy actions, such as restricting action to specific ARNs. • Warn employees of phishing emails within seconds of receiving them. IT and security automation 15 AWS Step Functions Human Approval Developer Guide • Automate machine learning model training, then get approval of the model by a data scientist before deploying the updated model. • Automate customer feedback routing based on sentiment analysis so negative comments are quickly escalated for review. IT and security automation 16 AWS Step Functions Developer Guide Learn how to get started with Step Functions With the Step Functions service, you can orchestrate complex application workflows. To get started, you'll use Workflow Studio to create and run a built-in Hello World workflow. You'll review the auto-generated Amazon States Language (ASL) definition in code. Finally, you'll drag-and-drop a service integration to do sentiment analysis. After you complete this tutorial, you'll know how to use Workflow Studio to create, configure, run, and update a workflow using both the Design and Code modes. Estimated duration: 20-30 minutes What you will build Your first state machine will start with flow states. Flow states are used to direct and control your workflow. After you learn how to run the workflow, you will add an Action to integrate the Amazon Comprehend service with a Task state. The following diagram shows a visual of the complete state machine that you will build. When you first create the Hello World state machine, it will not need additional resources to run. The Step Functions console will create all the states and an IAM role in a single click. Later, when you add the service integration, you will need to create a role with a custom permission policy. What you will build 17 AWS Step Functions Developer Guide What you will build 18 AWS Step Functions Developer Guide Step 1 - Create your state machine In Step Functions, workflows are called state machines. We'll use both terms interchangeably. Your workflows will contain states that either take action or control the flow of your state machines. 1. Go to the Step Functions console. 2. In the Step Functions console, choose "Step Functions" from the upper left navigation, or the breadcrumbs, then choose Get started: 3. From the options, choose Run Hello World: Step 1 - Create your state machine 19 AWS Step Functions Tip Developer Guide We recommend stepping through the short in-console walk through to become familiar with the UI. Overview of Workflow Studio With Workflow Studio for Step Functions, you can visually drag-and-drop states onto a canvas to build workflows. You can add and edit states, configure steps, transform results, and set up error handling. The following screenshot shows four important areas of the interface that you will use to build your state machines. Modes - Workflow Studio provides three modes of operation and defaults to the visual design mode. Overview of Workflow Studio 20 AWS Step Functions Developer Guide • Design - a visual editing mode, where you can drag-and-drop states into your workflow. • Code - a mode that focuses on the Amazon States Language code, also known as ASL code. You can edit ASL code directly and see changes reflected in the visual design. • Config - configuration options including the name and type of the state machine (Standard or Express), assigned role when the workflow runs, logging, tracing, versioning, encryption, and tags. States browser contains the following three tabs: • Actions - a list of AWS APIs that you can drag-and-drop into your workflow. Each action represents a Task workflow state. • Flow - flow states to control the order of steps in your workflow. • Patterns - ready-to-use, reusable building blocks, such as iteratively processing data in an Amazon S3 bucket. Canvas and workflow graph is where you drag-and-drop states on to your workflow graph, change the order of states, and select states to configure and test. Inspector panel is where you view and edit the properties of any state selected on the canvas. You can turn on the Definition toggle to show the code for the currently selected state. Overview of the state machine The Hello World workflow starts with a Pass state which passes its input to its output, without performing work. Pass states can be used to generate static JSON output or transform JSON input before passing the data to the next state. Pass states are useful when constructing and debugging state machines. The next state, a Choice state, uses the data in IsHelloWorldExample
step-functions-dg-013
step-functions-dg.pdf
13
Inspector panel is where you view and edit the properties of any state selected on the canvas. You can turn on the Definition toggle to show the code for the currently selected state. Overview of the state machine The Hello World workflow starts with a Pass state which passes its input to its output, without performing work. Pass states can be used to generate static JSON output or transform JSON input before passing the data to the next state. Pass states are useful when constructing and debugging state machines. The next state, a Choice state, uses the data in IsHelloWorldExample to choose the next branch of the workflow. If the first rule matches, the workflow pauses in a Wait state, then runs two tasks in a Parallel state, before moving on to a checkpoint and the successful end of the workflow. When there is no match, the workflow defaults to the Fail state before stopping the state machine. Wait states can be useful when you want to delay before performing more work. Perhaps your workflow will wait 30 seconds after an order entry, so your customer has time to notice and fix an incorrect shipping address. Parallel states can run multiple processes on your data. Perhaps the workflow will print an order ticket, update inventory, and increase a daily sales report simultaneously. Overview of the state machine 21 AWS Step Functions Developer Guide View the workflow code (ASL) Your first state machine is in fact quite detailed, so explore further by reviewing the code. State machines are defined using Amazon States Language (ASL), an open source specification that describes a JSON-based language to describe state machines declaratively. To view the entire state machine definition 1. Choose the { } Code button to view the ASL code. 2. View the code on the left and compare with the state machine graph on the right. 3. Select some states on the canvas to review. For example, pick the Choice state. View the workflow code (ASL) 22 AWS Step Functions Developer Guide Did you notice how the state's definition is highlighted in the code view? To view code in the Inspector 1. 2. 3. 4. Switch back to Design mode. Expand the Inspector panel on the right. Select the Choice state from the workflow graph on the Canvas. In the Inspector panel, choose the Definition toggle. Try choosing other states. See how the ASL code for each state you select is scrolled into view and highlighted? (Actually) Create the state machine Warning: name your state machine now! You cannot rename a state machine after you create it. Choose a name before you save your state machine. (Actually) Create the state machine 23 AWS Step Functions Developer Guide Until now, you've been working on a draft of your state machine. No resources have been created yet. To rename and create your state machine 1. Choose Config mode. 2. 3. For state machine name, enter MyFirstStateMachine For permissions, accept the default to Create a new role. 4. Choose the Create button to actually create your state machine. You should see notifications that your state machine and a new IAM role have been created. You will be automatically presented with the option to start the state machine. You'll do that in the next step! (Actually) Create the state machine 24 AWS Step Functions Developer Guide Workflow creation achieved! Step Functions created your workflow and IAM role. Now, you are ready to start your state machine. Step 2 - Start your state machine After your state machine has been created, you can start your workflow running. Workflows optionally take Input that can be used in the state, sent to integrated services, and passed to the next state. The Hello World state machine is self-contained and does not need input. To start the state machine 1. 2. Enter hello001 for the name of the execution. Leave the input field empty. 3. Choose the Start execution button. Step 2 - Start your state machine 25 AWS Step Functions Developer Guide Review the execution details Immediately after starting, you should see the first two states have succeeded. After a short wait, the rest of the state transitions will run to complete the workflow. Are you wondering how the Choice state (Is Hello World Example?) decided to branch to the Wait for X Seconds state? 1. Hint: the first step in the state machine contains the data needed for the branch decision 2. 3. In the Graph View, you can monitor progress during execution and explore details for each state. Select the first Pass state (named Set Variables and State Output), then review the Input/ Output tab. You should see that State input is blank, but State output contains JSON that sets the value of IsHelloWorldExample to true. Review the execution
step-functions-dg-014
step-functions-dg.pdf
14
complete the workflow. Are you wondering how the Choice state (Is Hello World Example?) decided to branch to the Wait for X Seconds state? 1. Hint: the first step in the state machine contains the data needed for the branch decision 2. 3. In the Graph View, you can monitor progress during execution and explore details for each state. Select the first Pass state (named Set Variables and State Output), then review the Input/ Output tab. You should see that State input is blank, but State output contains JSON that sets the value of IsHelloWorldExample to true. Review the execution details 26 AWS Step Functions Developer Guide Switch from the Graph view to the Table view to see a list of states by name, type, and status. Tip Take note of the Duration and Timeline fields in the previous screenshot. At a glance, you can see which states take more time than others. There are two more views to explore on this Executions Details page: Event view and State view. Review the execution details 27 AWS Step Functions Developer Guide The Event view is a detailed granular view of the flow from state to state. Expand the first PassStateEntered and PassStateExited events in the Event View table to see how the state takes no input, assigns a variable called CheckpointCount the value of zero, and produces the output you saw previously. Lastly, you have the State view which is similar to the Table view. In the State view table, you can selectively expand states to see just the Inputs and Outputs for each state: Review the execution details 28 AWS Step Functions Developer Guide Congratulations! You've run your first Step Functions state machine! Using a Pass state to add static data into a workflow is a common pattern, especially for troubleshooting. In the next step, you'll update the workflow so you can dynamically set your state machine input. Step 3 - Process external input Setting the value of IsHelloWorldExample to a constant value inside the workflow is not realistic. You should expect your state machine to respond to varying input data. In this step, we'll show you how external JSON data can be used as input to your workflow: Step 3 - Process external input 29 AWS Step Functions Developer Guide Remove the hard-coded input First, replace the hard-coded value in the Output of the first Pass state. 1. 2. Edit your Hello World state machine by selecting the Edit state machine button located at the top right of the page. Select the first Pass state after Start (named Set Variables and State Output), then select the Output tab. 3. Replace the Output with following JSON: { "IsHelloWorldExample": "{% $states.input.hello_world %}", "ExecutionWaitTimeInSeconds": "{% $states.input.wait %}" } 4. Save the state machine. The updated state output will pull input data from the reserved $states variable using a JSONata expression. Those values will be passed to the next state as output to become the input for the next state. Run the updated workflow, with input data Next, run the workflow and provide external input data as JSON. Remove the hard-coded input 30 AWS Step Functions Developer Guide 1. Choose the Execute button to run the workflow. 2. For the Name, use the randomly generated ID. 3. Use the following JSON for the input field: { "wait" : 20, "hello_world": true } 4. Choose the Start execution button. Your state machine execution should wait a lot longer (20 seconds), but eventually it should succeed using the input you provided. In the Graph view, review the Input/Output for the first Pass State. Notice how the input you provided was converted into outputs. Also, take a look at the Execution input and output at the top of the execution details page. Both locations show the input that you used to start the execution. Tip What do you expect if you run a new execution with hello_world set to false? Try it! Review workflow executions Now that you've run your workflow a few times, review the execution details to review runs of your workflow. To review execution details 1. Choose State machines from the navigation breadcrumbs or left-hand menu. 2. Choose your state machine. In the Executions tab, you should see a list of executions, similar to the following screenshot: Review workflow executions 31 AWS Step Functions Developer Guide One final note: workflow execution names must be unique and cannot be reused. Although we suggested a short name (hello001) in this tutorial, we recommend using a naming convention that will always be unique for your production workloads. Tip Congratulations! You've modified your workflow to process external input that can vary every time you run your workflow. Step 4 - Integrate a service Step Functions state machines can call over 220 AWS services using AWS SDK integrations.
step-functions-dg-015
step-functions-dg.pdf
15
Executions tab, you should see a list of executions, similar to the following screenshot: Review workflow executions 31 AWS Step Functions Developer Guide One final note: workflow execution names must be unique and cannot be reused. Although we suggested a short name (hello001) in this tutorial, we recommend using a naming convention that will always be unique for your production workloads. Tip Congratulations! You've modified your workflow to process external input that can vary every time you run your workflow. Step 4 - Integrate a service Step Functions state machines can call over 220 AWS services using AWS SDK integrations. AWS services provide over 10,000 potential API actions for your state machines. In this step, you will integrate an Amazon Comprehend task for sentiment analysis to process your state machine input. Service integrations use one of three service integration patterns: 1. Request a Response (default) - wait for HTTP response, then immediately proceed to the next state. 2. Run a Job (.sync) - wait for a job to complete before moving to the next step. 3. Wait for Callback (.waitForTaskToken) - pause a workflow until a task token is returned by an external process. Step 4 - Integrate a service 32 AWS Step Functions Developer Guide For your first integration, you will use the Request Response (default) integration pattern. How do integrations work? A Task state represents a single unit of work performed by a state machine. All work in your state machine is done by tasks. A task typically performs work by passing input to the API actions of other services which then perform their own work. You can specify how a Task performs, using a number of fields including: Credentials, Retry, Catch, TimeoutSeconds, and more. You can learn more about Tasks in the section called “Task”. To use AWS SDK integrations, you specify the service name and API to call. Some integrations also require parameters. You can use Amazon States Language to specify an AWS API action in the Resource field of a task state. You may optionally add a service integration type to the service name. To specify an API action, you will use the following resource name template: arn:aws:states:::aws-sdk:serviceName:apiAction.[serviceIntegrationPattern] Parameter name case Note that API actions will be camelCase (lowercase initial), but ParameterNames will be Pascal case (Uppercase initial). Examples of resource names How do integrations work? 33 AWS Step Functions Developer Guide • arn:aws:states:::aws-sdk:ec2:describeInstances will return the results from calling the Amazon EC2 describeInstances API. • arn:aws:states:::aws-sdk:s3:listBuckets will return the results from calling the Amazon S3 listBuckets API. • arn:aws:states:::aws-sdk:sfn:startExecution will start a nested Step Functions state machine execution and return the results of that workflow. When Step Functions calls another service using the Task state, the default pattern is Request Response. With the Request Response integration pattern, Step Functions calls a service, receives a response, and immediately proceeds to the next state. Step 4.1 - Add sentiment analysis state 1. 2. Edit your MyFirstStateMachine state machine. From the Actions panel in the States browser, search for DetectSentiment. 3. Drag & drop Comprehend DetectSentiment onto the Default branch of the Choice state. 4. 5. Select and delete the Fail state. From the Flow tab in the States browser, drag the Success state after DetectSentiment. Step 4.2 - Configure the sentiment analysis state 1. 2. Select the Comprehend step to configure it in the Inspector panel. Select the Arguments & Output tab, then replace the Arguments with the following JSON: { "LanguageCode": "en", "Text": "{% %}" } 3. Place your cursor between the percent signs: {% %} and type: $ Step 4.1 - Add sentiment analysis state 34 AWS Step Functions Developer Guide 4. Use auto-complete in the editor to choose states, then type . and choose context, then type . and choose Execution, then type . and choose Input, finally, type .feedback_comment to retrieve initial input from the Context Object. After choosing those auto-complete options, you should have the following JSON for your states Arguments: { "LanguageCode": "en", "Text": "{% $states.context.Execution.Input.feedback_comment %}" } Using editor auto-complete With editor auto-complete, you can explore your options. Auto-complete will list your variables, the reserved $states variable which contains the context object, and available functions with their definitions! Step 4.3 - Configure an identity policy Before you can run the workflow, you need to create a role and policy to allow the state machine to perform API calls to the external service. To create an IAM role for Step Functions 1. Go to the IAM console in a new tab and select Roles. 2. Choose Create a new role. 3. 4. 5. For Trusted entity type choose AWS Service. For Use case choose Step Functions. For Add permissions choose Next to accept the default policy. You will add a policy for Comprehend after creating the role. Step 4.3 -
step-functions-dg-016
step-functions-dg.pdf
16
4.3 - Configure an identity policy Before you can run the workflow, you need to create a role and policy to allow the state machine to perform API calls to the external service. To create an IAM role for Step Functions 1. Go to the IAM console in a new tab and select Roles. 2. Choose Create a new role. 3. 4. 5. For Trusted entity type choose AWS Service. For Use case choose Step Functions. For Add permissions choose Next to accept the default policy. You will add a policy for Comprehend after creating the role. Step 4.3 - Configure an identity policy 35 AWS Step Functions Developer Guide 6. For Name, enter HelloWorldWorkflowRole. 7. Choose Create role. To add a policy to the HelloWorldWorkflowRole for Amazon Comprehend 1. Select and edit the HelloWorldWorkflowRole role. 2. Choose Add permission then Create inline policy. 3. 4. 5. Select Comprehend for the service. In Read choose DetectSentiment, then Next For Policy name enter DetectSentimentPolicy, then Create policy. You should have created a policy as JSON, similar to the following: { "Version": "2012-10-17", "Statement": [ { "Action": [ "comprehend:DetectSentiment" ], "Resource": [ "*" ], "Effect": "Allow" } ] } To attach the an IAM role to the Step Functions state machine 1. Return to editing your state machine and select the Config tab. 2. 3. From the Execution role dropdown, choose HelloWorldWorkflowRole. Save your state machine. Step 4.4 - Run your state machine Start executing your state machine with the following JSON for input: Step 4.4 - Run your state machine 36 AWS Step Functions Developer Guide { "hello_world": false, "wait": 42, "feedback_comment" : "This getting started with Step Functions workshop is a challenge!" } Troubleshooting a permissions error... Without the correct policy, you will receive a permissions error, similar to the following: User: arn:aws:sts::account-id:assumed-role/StepFunctions-MyStateMachine-role is not authorized to perform: comprehend:DetectSentiment because no identity-based policy allows the comprehend:DetectSentiment action (Service: Comprehend, Status Code: 400, Request ID: a1b2c3d4-5678-90ab-cdef- EXAMPLE11111) The previous error message is telling you that your state machine is not authorized to use the external service. Go back a step and make sure you have configured an identity policy. Practice what you've learned! Before you dive into more complex workflows, practice what you've learned with the following tasks: • Review the DetectSentiment step. Take a look at the input/output in the various views to see the results of sentiment detection. • Find the duration of the DetectSentiment state in the table view. • Change the comment in the JSON input, then re-run your state machine. To learn more about sentiment analysis results, see Amazon Comprehend - Sentiment. One way to think about Request Response integration is the response generally represents only an acknowledgement of the request. However, in some integrations, such as sentiment analysis, the acknowledgement actually represents completion of the task. Step 4.4 - Run your state machine 37 AWS Step Functions Developer Guide The key learning is the Task state does not wait for the underlying job in Request Response integrations. To wait for a response, you'll need to explore the Run a Job (.sync) service integration pattern. Congratulations! You created your first state machine and integrated a sentiment analysis task using the Request Response pattern. We value your feedback! If you found this getting started tutorial helpful, or you have suggestions to improve the tutorial, let us know by using the feedback options on this page. Clean up resources Take the following steps to clean up the resources you created: 1. Navigate to the Step Functions page in the AWS Console. 2. Select State machines from the navigation pane on the left. 3. Choose the MyFirstStateMachine 4. To delete the IAM roles 1 - Follow the link for the IAM role to go to the IAM role page in a new tab. Delete the custom related role. 2 - In IAM Roles, search for the auto-generated role containing MyFirstStateMachine. Delete the auto-generated role. 5. Return to your Step Functions console tab and select the Actions drop down, then select Delete to delete the state machine. Your state machine and related role should now be deleted successfully. Clean up resources 38 AWS Step Functions Developer Guide Learn about state machines in Step Functions Step Functions is based on state machines, which are also called workflows. Workflows are comprised of a series of event-driven steps. You define a workflow using Amazon States Language, also known as ASL. You can optionally use Workflow Studio, a visual workflow designer, to build and edit your workflows. Each step in a workflow is called a state. There are two types of states: Flow states and Task states: Flow states Flow states control the flow of execution of the steps. For example, Choice states provide conditional logic; Wait states pause workflow execution; Map states run
step-functions-dg-017
step-functions-dg.pdf
17
machines in Step Functions Step Functions is based on state machines, which are also called workflows. Workflows are comprised of a series of event-driven steps. You define a workflow using Amazon States Language, also known as ASL. You can optionally use Workflow Studio, a visual workflow designer, to build and edit your workflows. Each step in a workflow is called a state. There are two types of states: Flow states and Task states: Flow states Flow states control the flow of execution of the steps. For example, Choice states provide conditional logic; Wait states pause workflow execution; Map states run child workflows for each item in a dataset; and Parallel states create separate branches in your workflows. Task states Task states represent a unit of work that another AWS service performs, such as calling another AWS service or API. Tasks states are also known as Actions. You can choose hundreds of actions to perform work in AWS and external services. (Note: You can also use workers that run outside of Step Functions to perform tasks. For more info, see Activities.) 39 AWS Step Functions Developer Guide Executions and handling errors When you run your workflows, Step Functions creates a workflow instance called an execution. You can monitor the status of your workflow executions. If an execution experiences an error, the workflow might catch the error. Depending on your use case, you might redrive the execution later to resume the workflow. Passing data You can optionally provide input data in the form of JSON text to your workflows. Each step can pass data to subsequent steps using variables and state output. Data stored in variables can be 40 AWS Step Functions Developer Guide used by later steps. State output becomes the input for the very next step. To learn more about passing data, see the section called “Passing data with variables”. At the end of workflows, your state machine can optionally produce output, also in the form of JSON. Transforming data States and state machines can transform data using a query language. The recommended query language is JSONata; however, state machines created prior to re:Invent 2024 use JSONPath. For backward compatibility, your state machines or individual states must opt-in to using JSONata for their query language. You can recognize JSONata state machines and individual states by the QueryLanguage field set to "JSONata". State machines and states that use JSONPath, lack the QueryLanguage field. States that use JSONPath will have state fields such as InputPath, Parameters, ResultSelector, ResultPath, and OutputPath. In JSONPath state machine definitions, you will also see field names that end in .$ and values prefixed with $. and $$., both of which represent paths. In the paths, you might see various intrinsic functions, such as States.MathAdd. Intrinsic functions are only used in JSONPath. JSONata states use Arguments and Output fields. In these optional fields, you might see JSONata expressions that look like the following: "{% $type = 'local' %}". With JSONata, you can use expressions, operators, and functions. To learn more, see the section called “Transforming data”. Note You can use only one query language per state. You cannot mix JSONPath and JSONata within a single step. Key concepts The following provides an overview of the key Step Functions terms for context. Term Description Workflow A sequence of steps that often reflect a business process. Key concepts 41 AWS Step Functions Term States Developer Guide Description Individual steps in your state machine that can make decisions based on their input, perform actions from those inputs, and pass output to other states. For more information, see Discovering workflow states to use in Step Functions. Workflow Studio A visual workflow designer that helps you to prototype and build workflows faster. For more information, see Developing workflows in Step Functions Workflow Studio. State machine A workflow defined using JSON text representing the individual states or steps in the workflow along with fields, such as StartAt, TimeoutSeconds , and Version. For more information, see State machine structure in Amazon States Language for Step Functions workflows. Amazon States Language A JSON-based, structured language used to define your state machines. With ASL, you define a collection of states that can do work (Task state), determine which states to transition to next (Choice state), and stop an execution with an error (Fail state). For more information, see Using Amazon States Language to define Step Functions workflows. Input and output configuration States in a workflow receive JSON data as input and usually pass JSON data as output to the next state. Step Functions provides filters to control the data flow between states. For more information, see Processing input and output in Step Functions. Service integration You can call AWS service API actions from your workflow. For more information, see Integrating services with Step Functions. Key concepts 42
step-functions-dg-018
step-functions-dg.pdf
18
which states to transition to next (Choice state), and stop an execution with an error (Fail state). For more information, see Using Amazon States Language to define Step Functions workflows. Input and output configuration States in a workflow receive JSON data as input and usually pass JSON data as output to the next state. Step Functions provides filters to control the data flow between states. For more information, see Processing input and output in Step Functions. Service integration You can call AWS service API actions from your workflow. For more information, see Integrating services with Step Functions. Key concepts 42 AWS Step Functions Developer Guide Term Description Service integration type Service integration pattern • AWS SDK integrations – Standard way to call any of over two hundred AWS services and over nine thousand API actions directly from your state machine. • Optimized integrations – Custom integrations that streamline calling and exchanging data with certain services. For example, Lambda Invoke will automatically convert the Payload field of the response from an escaped JSON string into a JSON object. When calling an AWS service, you use one of the following service integration patterns: • Request a response (default) – Call a service and move to the next state immediately after receiving an HTTP response. • Run a job (.sync) – Call a service and have Step Functions wait for a job to complete. • Wait for a callback with a task token (.waitForTaskToken) – Call a service with a task token and have Step Functions wait until the task token returns with a callback. Execution State machine executions are instances where you run your workflow to perform tasks. For more information, see Starting state machine executions in Step Functions. State Machine Data State machine data takes the following forms: • The initial input into a state machine • Data passed between states • The output from a state machine This section describes how state machine data is formatted and used in AWS Step Functions. Topics State Machine Data 43 AWS Step Functions • Data Format • State Machine Input/Output • State Input/Output Data Format Developer Guide State machine data is represented by JSON text. You can provide values to a state machine using any data type supported by JSON. Note • Numbers in JSON text format conform to JavaScript semantics. These numbers typically correspond to double-precision IEEE-854 values. • The following is valid JSON text: • Standalone, quote-delimited strings • Objects • Arrays • Numbers • Boolean values • null • The output of a state becomes the input for the next state. However, you can restrict states to work on a subset of the input data by using Input and Output Processing. State Machine Input/Output You can give your initial input data to an AWS Step Functions state machine in one of two ways. You can pass the data to a StartExecution action when you start an execution. You can also pass the data to the state machine from the Step Functions console. Initial data is passed to the state machine's StartAt state. If no input is provided, the default is an empty object ({}). The output of the execution is returned by the last state (terminal). This output appears as JSON text in the execution's result. Data Format 44 AWS Step Functions Developer Guide For Standard Workflows, you can retrieve execution results from the execution history using external callers, such as the DescribeExecution action. You can view execution results on the Step Functions console. For Express Workflows, if you enabled logging, you can retrieve results from CloudWatch Logs, or view and debug the executions in the Step Functions console. For more information, see Using CloudWatch Logs to log execution history in Step Functions and Viewing execution details in the Step Functions console. You should also consider quotas related to your state machine. For more information, see Service quotas State Input/Output Each state's input consists of JSON text from the preceding state or, for the StartAt state, the input into the execution. Certain flow-control states echo their input to their output. In the following example, the state machine adds two numbers together. 1. Define the AWS Lambda function. function Add(input) { var numbers = JSON.parse(input).numbers; var total = numbers.reduce( function(previousValue, currentValue, index, array) { return previousValue + currentValue; }); return JSON.stringify({ result: total }); } 2. Define the state machine. { "Comment": "An example that adds two numbers together.", "StartAt": "Add", "Version": "1.0", "TimeoutSeconds": 10, "States": { "Add": { "Type": "Task", "Resource": "arn:aws:lambda:region:123456789012:function:Add", "End": true State Input/Output 45 AWS Step Functions } } } 3. Start an execution with the following JSON text. { "numbers": [3, 4] } Developer Guide The Add state receives the JSON text and passes it to the Lambda function. The Lambda function returns the result of
step-functions-dg-019
step-functions-dg.pdf
19
var numbers = JSON.parse(input).numbers; var total = numbers.reduce( function(previousValue, currentValue, index, array) { return previousValue + currentValue; }); return JSON.stringify({ result: total }); } 2. Define the state machine. { "Comment": "An example that adds two numbers together.", "StartAt": "Add", "Version": "1.0", "TimeoutSeconds": 10, "States": { "Add": { "Type": "Task", "Resource": "arn:aws:lambda:region:123456789012:function:Add", "End": true State Input/Output 45 AWS Step Functions } } } 3. Start an execution with the following JSON text. { "numbers": [3, 4] } Developer Guide The Add state receives the JSON text and passes it to the Lambda function. The Lambda function returns the result of the calculation to the state. The state returns the following value in its output. { "result": 7 } Because Add is also the final state in the state machine, this value is returned as the state machine's output. If the final state returns no output, then the state machine returns an empty object ({}). For more information, see Processing input and output in Step Functions. Invoke AWS Step Functions from other services You can configure several other services to invoke state machines. Based on the state machine's workflow type, you can invoke state machines asynchronously or synchronously. To invoke state machines synchronously, use the StartSyncExecution API call or Amazon API Gateway integration with Express Workflows. With asynchronous invocation, Step Functions pauses the workflow execution until a task token is returned. However, waiting for a task token does make the workflow synchronous. Services that you can configure to invoke Step Functions include: • AWS Lambda, using the StartExecution call. • Amazon API Gateway • Amazon EventBridge • AWS CodePipeline Invoke Step Functions 46 AWS Step Functions • AWS IoT Rules Engine • AWS Step Functions Developer Guide Step Functions invocations are governed by the StartExecution quota. For more information, see: • Step Functions service quotas Transitions in state machines When you start a new execution of your state machine, the system begins with the state referenced in the top-level StartAt field. This field, given as a string, must exactly match, including case, the name of a state in the workflow. After a state runs, AWS Step Functions uses the value of the Next field to determine the next state to advance to. Next fields also specify state names as strings. This string is case-sensitive and must match the name of a state specified in the state machine description exactly For example, the following state includes a transition to NextState. "SomeState" : { ..., "Next" : "NextState" } Most states permit only a single transition rule with the Next field. However, certain flow-control states, such as a Choice state, allow you to specify multiple transition rules, each with its own Next field. The Amazon States Language provides details about each of the state types you can specify, including information about how to specify transitions. States can have multiple incoming transitions from other states. The process repeats until it either reaches a terminal state (a state with "Type": Succeed, "Type": Fail, or "End": true), or a runtime error occurs. When you redrive an execution, it's considered as a state transition. In addition, all states that are rerun in a redrive are also considered as state transitions. Transitions in state machines 47 AWS Step Functions Developer Guide The following rules apply to states within a state machine: • States can occur in any order within the enclosing block. However, the order in which they're listed doesn't affect the order in which they're run. That order is determined by the contents of the states. • Within a state machine, there can be only one state designated as the start state. The start state is defined by the value of the StartAt field in the top-level structure. • Depending on your state machine logic — for example, if your state machine has multiple logic branches — you may have more than one end state. • If your state machine consists of only one state, it can be both the start and end state. Transitions in Distributed Map state When you use the Map state in Distributed mode, you'll be charged one state transition for each child workflow execution that the Distributed Map state starts. When you use the Map state in Inline mode, you aren't charged a state transition for each iteration of the Inline Map state. You can optimize cost by using the Map state in Distributed mode and include a nested workflow in the Map state definition. The Distributed Map state also adds more value when you start child workflow executions of type Express. Step Functions stores the response and status of the Express child workflow executions, which reduces the need to store execution data in CloudWatch Logs. You can also get access to flow controls available with a Distributed Map state, such as
step-functions-dg-020
step-functions-dg.pdf
20
use the Map state in Inline mode, you aren't charged a state transition for each iteration of the Inline Map state. You can optimize cost by using the Map state in Distributed mode and include a nested workflow in the Map state definition. The Distributed Map state also adds more value when you start child workflow executions of type Express. Step Functions stores the response and status of the Express child workflow executions, which reduces the need to store execution data in CloudWatch Logs. You can also get access to flow controls available with a Distributed Map state, such as defining error thresholds or batching a group of items. For information about Step Functions pricing, see AWS Step Functions pricing. Read Consistency in Step Functions State machine updates in AWS Step Functions are eventually consistent. All StartExecution calls within a few seconds will use the updated definition and roleArn (the Amazon Resource Name for the IAM role). Executions started immediately after calling UpdateStateMachine might use the previous state machine definition and roleArn. For more information, see the following: • UpdateStateMachine in the AWS Step Functions API Reference Transitions in Distributed Map state 48 AWS Step Functions Developer Guide Learn about Activities in Step Functions With Step Functions activities, you can set up a task in your state machine where the actual work is performed by a worker running outside of Step Functions. For example you could have a worker program running on Amazon Elastic Compute Cloud (Amazon EC2), Amazon Elastic Container Service (Amazon ECS), or even mobile devices. Overview In AWS Step Functions, activities are a way to associate code running somewhere (known as an activity worker) with a specific task in a state machine. You can create an activity using the Step Functions console, or by calling CreateActivity. This provides an Amazon Resource Name (ARN) for your task state. Use this ARN to poll the task state for work in your activity worker. Note Activities are not versioned and are expected to be backward compatible. If you must make a backward-incompatible change to an activity, create a new activity in Step Functions using a unique name. An activity worker can be an application running on an Amazon EC2 instance, an AWS Lambda function, a mobile device: any application that can make an HTTP connection, hosted anywhere. 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. GetActivityTask returns a response including input (a string of JSON input for the task) and a taskToken (a unique identifier for the task). 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. APIs Related to Activity Tasks Step Functions provides APIs for creating and listing activities, requesting a task, and for managing the flow of your state machine based on the results of your worker. The following are the Step Functions APIs that are related to activities: Overview 49 Developer Guide AWS Step Functions • CreateActivity • GetActivityTask • ListActivities • SendTaskFailure • SendTaskHeartbeat • SendTaskSuccess Note Polling for activity tasks with GetActivityTask can cause latency in some implementations. See Avoiding latency when polling for activity tasks. Waiting for an Activity Task to Complete Configure how long a state waits by setting TimeoutSeconds in the task definition. To keep the task active and waiting, periodically send a heartbeat from your activity worker using SendTaskHeartbeat within the time configured in TimeoutSeconds. By configuring a long timeout duration and actively sending a heartbeat, an activity in Step Functions can wait up to a year for an execution to complete. For example, if you need a workflow that waits for the outcome of a long process, do the following: 1. Create an activity by using the console, or by using CreateActivity. Make a note of the activity ARN. 2. Reference that ARN in an activity task state in your state machine definition and set TimeoutSeconds. 3. Implement an activity worker that polls for work by using GetActivityTask, referencing that activity ARN. 4. Use SendTaskHeartbeat periodically within the time you set in HeartbeatSeconds in your state machine task definition to keep the task from timing out. 5. Start an execution of your state machine. 6. Start your activity worker process. Waiting for an Activity Task to Complete 50 AWS Step Functions Developer Guide The execution pauses at the activity task state and waits for your activity worker to poll for a task. Once a taskToken is provided to your activity worker, your workflow will wait for SendTaskSuccess or SendTaskFailure to provide
step-functions-dg-021
step-functions-dg.pdf
21
that polls for work by using GetActivityTask, referencing that activity ARN. 4. Use SendTaskHeartbeat periodically within the time you set in HeartbeatSeconds in your state machine task definition to keep the task from timing out. 5. Start an execution of your state machine. 6. Start your activity worker process. Waiting for an Activity Task to Complete 50 AWS Step Functions Developer Guide The execution pauses at the activity task state and waits for your activity worker to poll for a task. Once a taskToken is provided to your activity worker, your workflow will wait for SendTaskSuccess or SendTaskFailure to provide a status. If the execution doesn't receive either of these or a SendTaskHeartbeat call before the time configured in TimeoutSeconds, the execution will fail and the execution history will contain an ExecutionTimedOut event. Example: Activity Worker in Ruby The following example activity worker code implements a consumer-producer pattern with a configurable number of threads for pollers and activity workers. The poller threads are constantly long polling the activity task in Step Functions. When an activity task is retrieved, it is passed through a bounded blocking queue for the activity thread to pick up. • For more information, see the AWS SDK for Ruby API Reference. • To download this code and related resources, see the step-functions-ruby-activity-worker repository on GitHub. The following code is the main entry point for this example Ruby activity worker. require_relative '../lib/step_functions/activity' credentials = Aws::SharedCredentials.new region = 'us-west-2' activity_arn = 'ACTIVITY_ARN' activity = StepFunctions::Activity.new( credentials: credentials, region: region, activity_arn: activity_arn, workers_count: 1, pollers_count: 1, heartbeat_delay: 30 ) # Start method block contains your custom implementation to process the input activity.start do |input| { result: :SUCCESS, echo: input['value'] } end Example: Activity Worker in Ruby 51 AWS Step Functions Developer Guide You must specify your activity ARN and region. The code includes defaults that you can set, such as number of threads and heartbeat delay. Item Description require_relative region workers_count pollers_count Relative path to the following example activity worker code. AWS Region of your activity. The number of threads for your activity worker. For most implementations, between 10 and 20 threads should be sufficient. The longer the activity takes to process, the more threads it might need. As an estimate, multiply the number of process activities per second by the 99th percentile activity processing latency, in seconds. The number of threads for your pollers. Between 10 and 20 threads should be sufficien t for most implementations. heartbeat_delay The delay in seconds between heartbeats. input Implementation logic of your activity. Next Steps For a more detailed look at creating state machines that use an activity workers, see: • Creating an Activity state machine using Step Functions Next Steps 52 AWS Step Functions Developer Guide Choosing workflow type in Step Functions When you create a state machine, you must choose a Type of either Standard (default) or Express, referred to commonly as a standard workflow or an express workflow. You define both state machine types using the Using Amazon States Language to define Step Functions workflows. Both standard and express workflows can start in response to events, such as HTTP requests from Amazon API Gateway, IoT rules, and over 140 other event sources in Amazon EventBridge. Workflow type is immutable The workflow type can not be updated after you create a state machine. Standard Workflows are ideal for long-running (up to one year), durable, and auditable workflows. You can retrieve the full execution history using the Step Functions API for up to 90 days after your execution completes. Standard Workflows follow an exactly-once model, where your tasks and states are never run more than once, unless you have specified Retry behavior in ASL. The exactly-once model makes Standard Workflows suited to orchestrating non-idempotent actions, such as starting an Amazon EMR cluster or processing payments. Standard Workflow executions are billed according to the number of state transitions processed. Express Workflows are ideal for high-volume, event-processing workloads such as IoT data ingestion, streaming data processing and transformation, and mobile application backends. They can run for up to five minutes. Express Workflows use an at-least-once model, so an execution could potentially run more than once. The at-least-once model makes Express Workflows better suited for orchestrating idempotent actions, such as transforming input data to store in Amazon DynamoDB using a PUT action. Express Workflow executions are billed by number of executions, total duration of execution, and memory consumed during execution. 53 AWS Step Functions Tip Developer Guide To deploy an example Express workflow, see Processing data in parallel in The AWS Step Functions Workshop. Comparison of Standard and Express workflow types Type / Category Standard Workflows Express Workflows: Synchronous and Asynchron ous Maximum duration One year Five minutes Supported execution start rate For information about quotas related to supported For information about quotas related
step-functions-dg-022
step-functions-dg.pdf
22
for orchestrating idempotent actions, such as transforming input data to store in Amazon DynamoDB using a PUT action. Express Workflow executions are billed by number of executions, total duration of execution, and memory consumed during execution. 53 AWS Step Functions Tip Developer Guide To deploy an example Express workflow, see Processing data in parallel in The AWS Step Functions Workshop. Comparison of Standard and Express workflow types Type / Category Standard Workflows Express Workflows: Synchronous and Asynchron ous Maximum duration One year Five minutes Supported execution start rate For information about quotas related to supported For information about quotas related to supported execution start rate, see execution start rate, see Quotas related to API action Quotas related to API action throttling. Supported state transition rate For information about quotas related to supported state transition rate, see Quotas related to state throttling. throttling. No limit Pricing Execution history Priced by number of state transitions. A state transition Priced by the number of executions you run, their is counted each time a step in your execution is completed. duration, and memory consumption. Executions can be listed and described with Step Functions APIs. Executions can be visually debugged through the console. They can also be inspected in CloudWatch Logs by enabling logging on your state machine. Unlimited execution history, that is, as many execution history entries are maintained as you can generate within a 5-minute period. Executions can be inspected in CloudWatch Logs or the 54 AWS Step Functions Developer Guide Type / Category Standard Workflows Express Workflows: Synchronous and Asynchron ous For more information Step Functions console by about debugging Standard Workflow executions in the enabling logging on your state machine. console, see Standard and Express console experienc e differences and Viewing workflow runs. Execution semantics Exactly-once workflow execution. For more information about debugging Express Workflow executions in the console, see Standard and Express console experience differences and Viewing workflow runs. Asynchronous Express Workflows: At-least-once workflow execution. Synchronous Express Workflows: At-most-once workflow execution. Service integrations Supports all service integrati ons and patterns. Supports all service integrati ons. Note Express Workflows do not support Job-run (.sync) or Callback (.waitForT askToken ) service integration patterns. Distributed Map Activities Supported Supported Not supported Not supported 55 AWS Step Functions Developer Guide Optimize workflow type For a comparison and an example cost impact analysis, see Choosing the workflow type in the Large-scale data processing with Step Functions workshop. Synchronous and Asynchronous Express Workflows in Step Functions There are two types of Express Workflows that you can choose: Asynchronous Express Workflows and Synchronous Express Workflows. • Asynchronous Express Workflows return confirmation that the workflow was started, but don't wait for the workflow to complete. To get the result, you must poll the service's CloudWatch Logs. You can use Asynchronous Express Workflows when you don't require immediate response output, such as messaging services or data processing that other services don't depend on. You can start Asynchronous Express Workflows in response to an event, by a nested workflow in Step Functions, or by using the StartExecution API call. • Synchronous Express Workflows start a workflow, wait until it completes, and then return the result. Synchronous Express Workflows can be used to orchestrate microservices. With Synchronous Express Workflows, you can develop applications without the need to develop additional code to handle errors, retries, or run parallel tasks. You can run Synchronous Express Workflows invoked from Amazon API Gateway, AWS Lambda, or by using the StartSyncExecution API call. Note If you run Step Functions Express Workflows synchronously from the console, the StartSyncExecution request expires after 60 seconds. To run the Express Workflows synchronously for a duration of up to five minutes, make the StartSyncExecution request using the AWS SDK or AWS Command Line Interface (AWS CLI) instead of the Step Functions console. Express Workflow types 56 AWS Step Functions Developer Guide Synchronous Express execution API calls don't contribute to existing account capacity limits. Step Functions provides capacity on demand and automatically scales with sustained workload. Surges in workload may be throttled until capacity is available. Execution guarantees in Step Functions workflows Standard Workflows Asynchronous Express Workflows Synchronous Express Workflows Exactly-once workflow execution At-least-once workflow execution At-most-once workflow execution Execution state internall y persists between state Execution state doesn't persist between state Execution state doesn't persist between state transitions. transitions. transitions. Automatically returns an idempotent response on Idempotency is not automatic ally managed. Starting Idempotency is not automatic ally managed. Step Functions starting an execution with the multiple workflows with waits once an execution same name as a currently- the same name results starts and returns the state running workflow. The new in concurrent execution machine's result on completio workflow doesn't start and an s. Can result in loss of n. Workflows don't restart if exception is thrown once the internal workflow
step-functions-dg-023
step-functions-dg.pdf
23
y persists between state Execution state doesn't persist between state Execution state doesn't persist between state transitions. transitions. transitions. Automatically returns an idempotent response on Idempotency is not automatic ally managed. Starting Idempotency is not automatic ally managed. Step Functions starting an execution with the multiple workflows with waits once an execution same name as a currently- the same name results starts and returns the state running workflow. The new in concurrent execution machine's result on completio workflow doesn't start and an s. Can result in loss of n. Workflows don't restart if exception is thrown once the internal workflow state if an exception occurs. currently-running workflow is state machine logic is not complete. idempotent. Execution history data removed after 90 days. Workflow names can be reused after removal of out- of-date execution data. Execution history is not captured by Step Functions . Logging must be enabled through Amazon CloudWatch Logs. Execution history is not captured by Step Functions . Logging must be enabled through Amazon CloudWatch Logs. To meet compliance, organizational, or regulator y requirements, you can reduce the execution history Execution guarantees 57 Asynchronous Express Workflows Synchronous Express Workflows Developer Guide AWS Step Functions Standard Workflows retention period to 30 days by sending a quota request. To do this, use the AWS Support Center Console and create a new case. Execution guarantees 58 AWS Step Functions Developer Guide Using Amazon States Language to define Step Functions workflows The Amazon States Language is a JSON-based, structured language used to define your state machine, a collection of states, that can do work (Task states), determine which states to transition to next (Choice states), stop an execution with an error (Fail states), and so on. For more information, see the Amazon States Language Specification and Statelint, a tool that validates Amazon States Language code. To create a state machine on the Step Functions console using Amazon States Language, see Getting Started. Note If you define your state machines outside the Step Functions' console, such as in an editor of your choice, you must save your state machine definitions with the extension .asl.json. Example Amazon States Language Specification (JSONata) { "Comment": "An example of the Amazon States Language using a choice state.", "QueryLanguage": "JSONata", "StartAt": "FirstState", "States": { "FirstState": { "Type": "Task", "Assign": { "foo" : "{% $states.input.foo_input %}" }, "Resource": "arn:aws:lambda:region:123456789012:function:FUNCTION_NAME", "Next": "ChoiceState" }, "ChoiceState": { "Type": "Choice", "Default": "DefaultState", "Choices": [ { Example Amazon States Language Specification (JSONata) 59 AWS Step Functions Developer Guide "Next": "FirstMatchState", "Condition": "{% $foo = 1 %}" }, { "Next": "SecondMatchState", "Condition": "{% $foo = 2 %}" } ] }, "FirstMatchState": { "Type" : "Task", "Resource": "arn:aws:lambda:region:123456789012:function:OnFirstMatch", "Next": "NextState" }, "SecondMatchState": { "Type" : "Task", "Resource": "arn:aws:lambda:region:123456789012:function:OnSecondMatch", "Next": "NextState" }, "DefaultState": { "Type": "Fail", "Error": "DefaultStateError", "Cause": "No Matches!" }, "NextState": { "Type": "Task", "Resource": "arn:aws:lambda:region:123456789012:function:FUNCTION_NAME", "End": true } } } Example Amazon States Language Specification (JSONata) 60 AWS Step Functions Developer Guide State machine structure in Amazon States Language for Step Functions workflows Managing state and transforming data Learn about Passing data between states with variables and Transforming data with JSONata. State machines are defined using JSON text that represents a structure containing the following fields. Comment (Optional) A human-readable description of the state machine. QueryLanguage (Optional; when omitted, defaults to JSONPath) • The name of the query language used by the state machine. Allowed values are JSONPath and JSONata. • If not provided for the state machine, the default value for each state is JSONPath. • When the top-level state machine query language is JSONPath, individual states can override the query language by setting QueryLanguage to JSONata. Given this approach, you can incrementally convert a state machine from JSONPath to JSONata one state at a time. • Note: You cannot revert a top-level JSONata-based state machine to a mix of JSONata and JSONPath states. StartAt (Required) A string that must exactly match (is case sensitive) the name of one of the state objects. TimeoutSeconds (Optional) The maximum number of seconds an execution of the state machine can run. If it runs longer than the specified time, the execution fails with a States.Timeout Error Name. Version (Optional) The version of the Amazon States Language used in the state machine (default is "1.0"). States (Required) An object containing a comma-delimited set of states. State machine structure 61 AWS Step Functions Developer Guide The States field contains States. { "State1" : { }, "State2" : { }, ... } A state machine is defined by the states it contains and the relationships between them. The following is an example. { "Comment": "A Hello World example of the Amazon States Language using a Pass state", "StartAt": "HelloWorld", "States": { "HelloWorld": { "Type": "Pass", "Result": "Hello World!", "End": true } } } When an execution of this state
step-functions-dg-024
step-functions-dg.pdf
24
used in the state machine (default is "1.0"). States (Required) An object containing a comma-delimited set of states. State machine structure 61 AWS Step Functions Developer Guide The States field contains States. { "State1" : { }, "State2" : { }, ... } A state machine is defined by the states it contains and the relationships between them. The following is an example. { "Comment": "A Hello World example of the Amazon States Language using a Pass state", "StartAt": "HelloWorld", "States": { "HelloWorld": { "Type": "Pass", "Result": "Hello World!", "End": true } } } When an execution of this state machine is launched, the system begins with the state referenced in the StartAt field ("HelloWorld"). If this state has an "End": true field, the execution stops and returns a result. Otherwise, the system looks for a "Next": field and continues with that state next. This process repeats until the system reaches a terminal state (a state with "Type": "Succeed", "Type": "Fail", or "End": true), or a runtime error occurs. The following rules apply to states within a state machine: • States can occur in any order within the enclosing block, but the order in which they're listed doesn't affect the order in which they're run. The contents of the states determines this order. • Within a state machine, there can be only one state that's designated as the start state, designated by the value of the StartAt field in the top-level structure. This state is the one that is executed first when the execution starts. State machine structure 62 AWS Step Functions Developer Guide • Any state for which the End field is true is considered an end (or terminal) state. Depending on your state machine logic—for example, if your state machine has multiple branches of execution—you might have more than one end state. • If your state machine consists of only one state, it can be both the start state and the end state. Common state fields in workflows The following fields are common to all state elements. Type (Required) The state's type. QueryLanguage (Optional; when omitted, defaults to JSONPath) • The name of the query language used by the state. Allowed values are JSONPath and JSONata. • When the top-level state machine query language is JSONPath, individual states can override the query language by setting QueryLanguage to JSONata. Given this approach, you can incrementally convert a state machine from JSONPath to JSONata one state at a time. Next The name of the next state that is run when the current state finishes. Some state types, such as Choice, allow multiple transition states. If the current state is the last state in your workflow, or a terminal state, such as Succeed workflow state or Fail workflow state, you don't need to specify the Next field. End Designates this state as a terminal state (ends the execution) if set to true. There can be any number of terminal states per state machine. Only one of Next or End can be used in a state. Some state types, such as Choice, or terminal states, such as Succeed workflow state and Fail workflow state, don't support or use the End field. Comment (Optional) Holds a human-readable description of the state. Common state fields 63 AWS Step Functions Assign (Optional) Developer Guide Used to store variables. The Assign field accepts a JSON object with key/value pairs that define variable names and their assigned values. Any string value, including those inside objects or arrays, will be evaluated as JSONata when surrounded by {% %} characters For more information, see the section called “Passing data with variables”. Output (Optional, JSONata only) Used to specify and transform output from the state. When specified, the value overrides the state output default. The output field accepts any JSON value (object, array, string, number, boolean, null). Any string value, including those inside objects or arrays, will be evaluated as JSONata if surrounded by {% %} characters. Output also accepts a JSONata expression directly, for example: "Output": "{% jsonata expression %}" For more information, see Input and Output Processing. InputPath (Optional, JSONPath only) A path that selects a portion of the state's input to be passed to the state's task for processing. If omitted, it has the value $ which designates the entire input. For more information, see Input and Output Processing. OutputPath (Optional, JSONPath only) A path that selects a portion of the state's output to be passed to the next state. If omitted, it has the value $ which designates the entire output. For more information, see Input and Output Processing. Intrinsic functions for JSONPath states in Step Functions Managing state and transforming data Learn about Passing data between states with variables and Transforming data with JSONata. Intrinsic functions 64 AWS Step Functions Warning Developer Guide Intrinsic functions
step-functions-dg-025
step-functions-dg.pdf
25
for processing. If omitted, it has the value $ which designates the entire input. For more information, see Input and Output Processing. OutputPath (Optional, JSONPath only) A path that selects a portion of the state's output to be passed to the next state. If omitted, it has the value $ which designates the entire output. For more information, see Input and Output Processing. Intrinsic functions for JSONPath states in Step Functions Managing state and transforming data Learn about Passing data between states with variables and Transforming data with JSONata. Intrinsic functions 64 AWS Step Functions Warning Developer Guide Intrinsic functions are only available to states that use the JSONPath query language. For JSONata, see the section called “Transforming data”. The Amazon States Language provides several intrinsic functions, also known as intrinsics, for use in fields that accept JSONPath. With intrinsics, you can perform basic data processing operations without using a Task state. Intrinsics look similar to functions in programming languages. They can be used to help payload builders process the data going to and from the Resource field of a Task state that uses the JSONPath query language. In Amazon States Language, intrinsic functions are grouped into the following categories, based on the type of data processing task that you want to perform: • Intrinsics for arrays • Intrinsics for data encoding and decoding • Intrinsic for hash calculation • Intrinsics for JSON data manipulation • Intrinsics for Math operations • Intrinsic for String operation • Intrinsic for unique identifier generation • Intrinsic for generic operation To use intrinsic functions, you must specify .$ in the key value in your state machine definitions, as shown in the following example: "KeyId.$": "States.Array($.Id)" You can nest up to 10 intrinsic functions within a field in your workflows. The following example shows a field named myArn that includes nine nested intrinsic functions: "myArn.$": "States.Format('{}.{}.{}', States.ArrayGetItem(States.StringSplit(States.ArrayGetItem(States.StringSplit($.ImageRecipe.Arn, '/'), 2), '.'), 0), Intrinsic functions 65 AWS Step Functions Developer Guide States.ArrayGetItem(States.StringSplit(States.ArrayGetItem(States.StringSplit($.ImageRecipe.Arn, '/'), 2), '.'), 1))" QueryLanguage required for intrinsic functions To use intrinsic functions, the state machine must use the JSONPath query language. States that use JSONata cannot use intrinsic functions; however, JSONata and Step Functions provide equivalent options. Fields that support intrinsic functions The following states support intrinsic functions in the following fields: • Pass state : Parameters • Task state : Parameters, ResultSelector, Credentials • Parallel state: Parameters, ResultSelector • Map state: Parameters, ResultSelector Intrinsics for arrays Use the following intrinsics for performing array manipulations. States.Array The States.Array intrinsic function takes zero or more arguments. The interpreter returns a JSON array containing the values of the arguments in the order provided. For example, given the following input: { "Id": 123456 } You could use "BuildId.$": "States.Array($.Id)" Which would return the following result: Fields that support intrinsic functions 66 AWS Step Functions Developer Guide “BuildId”: [123456] States.ArrayPartition Use the States.ArrayPartition intrinsic function to partition a large array. You can also use this intrinsic to slice the data and then send the payload in smaller chunks. This intrinsic function takes two arguments. The first argument is an array, while the second argument defines the chunk size. The interpreter chunks the input array into multiple arrays of the size specified by chunk size. The length of the last array chunk may be less than the length of the previous array chunks if the number of remaining items in the array is smaller than the chunk size. Input validation • You must specify an array as the input value for the function's first argument. • You must specify a non-zero, positive integer for the second argument representing the chunk size value. If you specify a non-integer value for the second argument, Step Functions will round it off to the nearest integer. • The input array can't exceed Step Functions' payload size limit of 256 KiB. For example, given the following input array: {"inputArray": [1,2,3,4,5,6,7,8,9] } You could use the States.ArrayPartition function to divide the array into chunks of four values: "inputArray.$": "States.ArrayPartition($.inputArray,4)" Which would return the following array chunks: {"inputArray": [ [1,2,3,4], [5,6,7,8], [9]] } In the previous example, the States.ArrayPartition function outputs three arrays. The first two arrays each contain four values, as defined by the chunk size. A third array contains the remaining value and is smaller than the defined chunk size. Intrinsics for arrays 67 AWS Step Functions States.ArrayContains Developer Guide Use the States.ArrayContains intrinsic function to determine if a specific value is present in an array. For example, you can use this function to detect if there was an error in a Map state iteration. This intrinsic function takes two arguments. The first argument is an array, while the second argument is the value to be searched for within the array. Input validation • You must specify an array as the input value for
step-functions-dg-026
step-functions-dg.pdf
26
size. A third array contains the remaining value and is smaller than the defined chunk size. Intrinsics for arrays 67 AWS Step Functions States.ArrayContains Developer Guide Use the States.ArrayContains intrinsic function to determine if a specific value is present in an array. For example, you can use this function to detect if there was an error in a Map state iteration. This intrinsic function takes two arguments. The first argument is an array, while the second argument is the value to be searched for within the array. Input validation • You must specify an array as the input value for function's first argument. • You must specify a valid JSON object as the second argument. • The input array can't exceed Step Functions' payload size limit of 256 KiB. For example, given the following input array: { "inputArray": [1,2,3,4,5,6,7,8,9], "lookingFor": 5 } You could use the States.ArrayContains function to find the lookingFor value within the inputArray: "contains.$": "States.ArrayContains($.inputArray, $.lookingFor)" Because the value stored in lookingFor is included in the inputArray, States.ArrayContains returns the following result: {"contains": true } States.ArrayRange Use the States.ArrayRange intrinsic function to create a new array containing a specific range of elements. The new array can contain up to 1000 elements. This function takes three arguments. The first argument is the first element of the new array, the second argument is the final element of the new array, and the third argument is the increment value between the elements in the new array. Intrinsics for arrays 68 AWS Step Functions Input validation Developer Guide • You must specify integer values for all of the arguments. If you specify a non-integer value for any of the arguments, Step Functions will round it off to the nearest integer. • You must specify a non-zero value for the third argument. • The newly generated array can't contain more than 1000 items. For example, the following use of the States.ArrayRange function will create an array with a first value of 1, a final value of 9, and values in between the first and final values increase by two for each item: "array.$": "States.ArrayRange(1, 9, 2)" Which would return the following array: {"array": [1,3,5,7,9] } States.ArrayGetItem This intrinsic function returns a specified index's value. This function takes two arguments. The first argument is an array of values and the second argument is the array index of the value to return. For example, use the following inputArray and index values: { "inputArray": [1,2,3,4,5,6,7,8,9], "index": 5 } From these values, you can use the States.ArrayGetItem function to return the value in the index position 5 within the array: "item.$": "States.ArrayGetItem($.inputArray, $.index)" In this example, States.ArrayGetItem would return the following result: Intrinsics for arrays 69 AWS Step Functions { "item": 6 } States.ArrayLength Developer Guide The States.ArrayLength intrinsic function returns the length of an array. It has one argument, the array to return the length of. For example, given the following input array: { "inputArray": [1,2,3,4,5,6,7,8,9] } You can use States.ArrayLength to return the length of inputArray: "length.$": "States.ArrayLength($.inputArray)" In this example, States.ArrayLength would return the following JSON object that represents the array length: { "length": 9 } States.ArrayUnique The States.ArrayUnique intrinsic function removes duplicate values from an array and returns an array containing only unique elements. This function takes an array, which can be unsorted, as its sole argument. For example, the following inputArray contains a series of duplicate values: {"inputArray": [1,2,3,3,3,3,3,3,4] } You could use the States.ArrayUnique function as and specify the array you want to remove duplicate values from: "array.$": "States.ArrayUnique($.inputArray)" The States.ArrayUnique function would return the following array containing only unique elements, removing all duplicate values: Intrinsics for arrays 70 AWS Step Functions Developer Guide {"array": [1,2,3,4] } Intrinsics for data encoding and decoding Use the following intrinsic functions to encode or decode data based on the Base64 encoding scheme. States.Base64Encode Use the States.Base64Encode intrinsic function to encode data based on MIME Base64 encoding scheme. You can use this function to pass data to other AWS services without using an AWS Lambda function. This function takes a data string of up to 10,000 characters to encode as its only argument. For example, consider the following input string: {"input": "Data to encode" } You can use the States.Base64Encode function to encode the input string as a MIME Base64 string: "base64.$": "States.Base64Encode($.input)" The States.Base64Encode function returns the following encoded data in response: {"base64": "RGF0YSB0byBlbmNvZGU=" } States.Base64Decode Use the States.Base64Decode intrinsic function to decode data based on MIME Base64 decoding scheme. You can use this function to pass data to other AWS services without using a Lambda function. This function takes a Base64 encoded data string of up to 10,000 characters to decode as its only argument. For example, given the following input: Intrinsics for data encoding and decoding 71 AWS Step Functions Developer
step-functions-dg-027
step-functions-dg.pdf
27
} You can use the States.Base64Encode function to encode the input string as a MIME Base64 string: "base64.$": "States.Base64Encode($.input)" The States.Base64Encode function returns the following encoded data in response: {"base64": "RGF0YSB0byBlbmNvZGU=" } States.Base64Decode Use the States.Base64Decode intrinsic function to decode data based on MIME Base64 decoding scheme. You can use this function to pass data to other AWS services without using a Lambda function. This function takes a Base64 encoded data string of up to 10,000 characters to decode as its only argument. For example, given the following input: Intrinsics for data encoding and decoding 71 AWS Step Functions Developer Guide {"base64": "RGF0YSB0byBlbmNvZGU=" } You can use the States.Base64Decode function to decode the base64 string to a human- readable string: "data.$": "States.Base64Decode($.base64)" The States.Base64Decode function would return the following decoded data in response: {"data": "Decoded data" } Intrinsic for hash calculation States.Hash Use the States.Hash intrinsic function to calculate the hash value of a given input. You can use this function to pass data to other AWS services without using a Lambda function. This function takes two arguments. The first argument is the data you want to calculate the hash value of. The second argument is the hashing algorithm to use to perform the hash calculation. The data you provide must be an object string containing 10,000 characters or less. The hashing algorithm you specify can be any of the following algorithms: • MD5 • SHA-1 • SHA-256 • SHA-384 • SHA-512 For example, you can use this function to calculate the hash value of the Data string using the specified Algorithm: { "Data": "input data", "Algorithm": "SHA-1" } Intrinsic for hash calculation 72 AWS Step Functions Developer Guide You can use the States.Hash function to calculate the hash value: "output.$": "States.Hash($.Data, $.Algorithm)" The States.Hash function returns the following hash value in response: {"output": "aaff4a450a104cd177d28d18d7485e8cae074b7" } Intrinsics for JSON data manipulation Use these functions to perform basic data processing operations on JSON objects. States.JsonMerge Use the States.JsonMerge intrinsic function to merge two JSON objects into a single object. This function takes three arguments. The first two arguments are the JSON objects that you want to merge. The third argument is a boolean value of false. This boolean value determines if the deep merging mode is enabled. Currently, Step Functions only supports the shallow merging mode; therefore, you must specify the boolean value as false. In the shallow mode, if the same key exists in both JSON objects, the latter object's key overrides the same key in the first object. Additionally, objects nested within a JSON object are not merged when you use shallow merging. For example, you can use the States.JsonMerge function to merge the following JSON objects that share the key a. { "json1": { "a": {"a1": 1, "a2": 2}, "b": 2 }, "json2": { "a": {"a3": 1, "a4": 2}, "c": 3 } } You can specify the json1 and json2 objects as inputs in the States.JsonMerge function to merge them together: "output.$": "States.JsonMerge($.json1, $.json2, false)" The States.JsonMerge returns the following merged JSON object as result. In the merged JSON object output, the json2 object's key a replaces the json1 object's key a. Also, the Intrinsics for JSON data manipulation 73 AWS Step Functions Developer Guide nested object in json1 object's key a is discarded because shallow mode doesn't support merging nested objects. { "output": { "a": {"a3": 1, "a4": 2}, "b": 2, "c": 3 } } States.StringToJson The States.StringToJson function takes a reference path to an escaped JSON string as its only argument. The interpreter applies a JSON parser and returns the input's parsed JSON form. For example, you can use this function to escape the following input string: { "escapedJsonString": "{\"foo\": \"bar\"}" } Use the States.StringToJson function and specify the escapedJsonString as the input argument: States.StringToJson($.escapedJsonString) The States.StringToJson function returns the following result: { "foo": "bar" } States.JsonToString The States.JsonToString function takes only one argument, which is the path that contains the JSON data to return as an unescaped string. The interpreter returns a string that contains JSON text representing the data specified by the Path. For example, you can provide the following JSON Path containing an escaped value: Intrinsics for JSON data manipulation 74 AWS Step Functions Developer Guide { "unescapedJson": { "foo": "bar" } } Provide the States.JsonToString function with the data contained within unescapedJson: States.JsonToString($.unescapedJson) The States.JsonToString function returns the following response: {\"foo\": \"bar\"} Intrinsics for Math operations Use these functions to perform Math operations. States.MathRandom Use the States.MathRandom intrinsic function to return a random number between the specified start number (inclusive) and end number (exclusive). You can use this function to distribute a specific task between two or more resources. This function takes three arguments. The first argument is the start number, the second argument is the end number, and the last argument
step-functions-dg-028
step-functions-dg.pdf
28
Functions Developer Guide { "unescapedJson": { "foo": "bar" } } Provide the States.JsonToString function with the data contained within unescapedJson: States.JsonToString($.unescapedJson) The States.JsonToString function returns the following response: {\"foo\": \"bar\"} Intrinsics for Math operations Use these functions to perform Math operations. States.MathRandom Use the States.MathRandom intrinsic function to return a random number between the specified start number (inclusive) and end number (exclusive). You can use this function to distribute a specific task between two or more resources. This function takes three arguments. The first argument is the start number, the second argument is the end number, and the last argument controls the optional seed value, Note that if you use this function with the same seed value, it will return identical numbers. Important Because the States.MathRandom function does not return cryptographically secure random numbers, we recommend that you don't use it for security sensitive applications. Input validation Intrinsics for Math operations 75 AWS Step Functions Developer Guide • You must specify integer values for the start number and end number arguments. If you specify a non-integer value for the start number or end number argument, Step Functions will round it off to the nearest integer. For example, to generate a random number between one and 999, you can use the following input values: { "start": 1, "end": 999 } To generate the random number, provide the start and end values to the States.MathRandom function: "random.$": "States.MathRandom($.start, $.end)" The States.MathRandom function returns the following random number as a response: {"random": 456 } States.MathAdd Use the States.MathAdd intrinsic function to return the sum of two numbers. For example, you can use this function to increment values inside a loop without invoking a Lambda function. Input validation • You must specify integer values for all the arguments. If you specify a non-integer value for one or both the arguments, Step Functions will round it off to the nearest integer. • You must specify integer values in the range of -2147483648 and 2147483647. For example, you can use the following values to subtract one from 111: { Intrinsics for Math operations 76 AWS Step Functions "value1": 111, "step": -1 } Developer Guide Then, use the States.MathAdd function defining value1 as the starting value, and step as the value to increment value1 by: "value1.$": "States.MathAdd($.value1, $.step)" The States.MathAdd function would return the following number in response: {"value1": 110 } Intrinsic for String operation States.StringSplit Use the States.StringSplit intrinsic function to split a string into an array of values. This function takes two arguments. The first argument is a string and the second argument is the delimiting character that the function will use to divide the string. Example - Split an input string using a single delimiting character For this example, use States.StringSplit to divide the following inputString, which contains a series of comma separated values: { "inputString": "1,2,3,4,5", "splitter": "," } Use the States.StringSplit function and define inputString as the first argument, and the delimiting character splitter as the second argument: "array.$": "States.StringSplit($.inputString, $.splitter)" The States.StringSplit function returns the following string array as result: Intrinsic for String operation 77 AWS Step Functions Developer Guide {"array": ["1","2","3","4","5"] } Example - Split an input string using multiple delimiting characters For this example, use States.StringSplit to divide the following inputString, which contains multiple delimiting characters: { "inputString": "This.is+a,test=string", "splitter": ".+,=" } Use the States.StringSplit function as follows: { "myStringArray.$": "States.StringSplit($.inputString, $.splitter)" } The States.StringSplit function returns the following string array as result: {"myStringArray": [ "This", "is", "a", "test", "string" ]} Intrinsic for unique identifier generation States.UUID Use the States.UUID intrinsic function to return a version 4 universally unique identifier (v4 UUID) generated using random numbers. For example, you can use this function to call other AWS services or resources that need a UUID parameter or insert items in a DynamoDB table. The States.UUID function is called with no arguments specified: "uuid.$": "States.UUID()" Intrinsic for unique identifier generation 78 AWS Step Functions Developer Guide The function returns a randomly generated UUID, as in the following example: {"uuid": "ca4c1140-dcc1-40cd-ad05-7b4aa23df4a8" } Intrinsic for generic operation States.Format Use the States.Format intrinsic function to construct a string from both literal and interpolated values. This function takes one or more arguments. The value of the first argument must be a string, and may include zero or more instances of the character sequence {}. There must be as many remaining arguments in the intrinsic function invocation as there are occurrences of {}. The interpreter returns the string defined in the first argument with each {} replaced by the value of the positionally-corresponding argument in the Intrinsic invocation. For example, you can use the following inputs of an individual's name, and a template sentence to have their name inserted into: { "name": "Arnav", "template": "Hello, my name is {}." } Use the States.Format function and specify
step-functions-dg-029
step-functions-dg.pdf
29
the first argument must be a string, and may include zero or more instances of the character sequence {}. There must be as many remaining arguments in the intrinsic function invocation as there are occurrences of {}. The interpreter returns the string defined in the first argument with each {} replaced by the value of the positionally-corresponding argument in the Intrinsic invocation. For example, you can use the following inputs of an individual's name, and a template sentence to have their name inserted into: { "name": "Arnav", "template": "Hello, my name is {}." } Use the States.Format function and specify the template string and the string to insert in place of the {} characters: States.Format('Hello, my name is {}.', $.name) or States.Format($.template, $.name) With either of the previous inputs, the States.Format function returns the completed string in response: Hello, my name is Arnav. Intrinsic for generic operation 79 AWS Step Functions Developer Guide Reserved characters in intrinsic functions The following characters are reserved for intrinsic functions, and must be escaped with a backslash ('\') if you want them to appear in the Value: '{}, and \. If the character \ needs to appear as part of the value without serving as an escape character, you must escape it with a backslash. The following escaped character sequences are used with intrinsic functions: • The literal string \' represents '. • The literal string \{ represents {. • The literal string \} represents }. • The literal string \\ represents \. In JSON, backslashes contained in a string literal value must be escaped with another backslash. The equivalent list for JSON is: • The escaped string \\\' represents \'. • The escaped string \\\{ represents \{. • The escaped string \\\} represents \}. • The escaped string \\\\ represents \\. Note If an open escape backslash \ is found in the intrinsic invocation string, the interpreter will return a runtime error. You must use square bracket notation for a Path passed as an argument to an Intrinsic Function if the field name contains any character that is not included in the member-name-shorthand definition of the JsonPath ABNF rule. If your Path contains non-alphanumeric characters, besides _, you must use square bracket notation. For example, $.abc.['def ghi']. Reserved characters in intrinsic functions 80 AWS Step Functions Developer Guide Discovering workflow states to use in Step Functions States are elements in your state machine. A state is referred to by its name, which can be any string, but which must be unique within the scope of the entire state machine. States take input from the invocation or a previous state. States can filter the input and then manipulate the output that is sent to the next state. The following is an example state named HelloWorld that invokes an AWS Lambda function. "HelloWorld": { "Type": "Task", "Resource": "arn:aws:lambda:region:123456789012:function:HelloFunction", "Next": "AfterHelloWorldState", "Comment": "Run the HelloWorld Lambda function" } Individual states can make decisions based on their input, perform actions from those inputs, and pass output to other states. In AWS Step Functions, you define your workflows in the Amazon States Language (ASL). The Step Functions console provides a graphical representation of your state machine to help visualize your application's logic. The following screenshot shows some of the most popular Actions and the seven Flow states from Workflow Studio: 81 AWS Step Functions Developer Guide States share many common features: • A Type field indicating what type of state it is. • An optional Comment field to hold a human-readable comment about, or description of, the state. • Each state (except Succeed or Fail states) requires a Next field that specifies the next state in the workflow. Choice states can actually have more than one Next within each Choice Rule. Alternatively, a state can become a terminal state by setting the End field to true. Certain state types require additional fields, or may redefine common field usage. To access log information for workflows • After you have created and run Standard workflows, you can access information about each state, its input and output, when it was active and for how long, by viewing the Execution Details page in the Step Functions console. 82 AWS Step Functions Developer Guide • After you have created and Express Workflow executions and if logging is enabled, you can see execution history in the Step Functions console or Amazon CloudWatch Logs. For information about viewing and debugging executions, see Viewing workflow runs and the section called “Logging in CloudWatch Logs”. Reference list of workflow states States are separated in Workflow Studio into Actions, also known as Task states, and seven Flow states. Using Task states, or actions in Workflow Studio, you can call third party services, invoke functions, and use hundreds of AWS service endpoints. With Flow states, you can direct and
step-functions-dg-030
step-functions-dg.pdf
30
Guide • After you have created and Express Workflow executions and if logging is enabled, you can see execution history in the Step Functions console or Amazon CloudWatch Logs. For information about viewing and debugging executions, see Viewing workflow runs and the section called “Logging in CloudWatch Logs”. Reference list of workflow states States are separated in Workflow Studio into Actions, also known as Task states, and seven Flow states. Using Task states, or actions in Workflow Studio, you can call third party services, invoke functions, and use hundreds of AWS service endpoints. With Flow states, you can direct and control your workflow. All states take input from the previous state, and many provide input filtering, and filtering/transformation for output that is passed to the next state in your workflow. • Task workflow state: Add a single unit of work to be performed by your state machine. • Choice workflow state: Add a choice between branches of execution to your workflow. • Parallel workflow state: Add parallel branches of execution to your workflow. • Map workflow state: Dynamically iterate steps for each element of an input array. Unlike a Parallel flow state, a Map state will execute the same steps for multiple entries of an array in the state input. • Pass workflow state: Pass state input through to the output. Optionally, filter, transform, and add fixed data into the output. • Wait workflow state: Pause your workflow for a certain amount of time or until a specified time or date. • Succeed workflow state: Stops your workflow with a success. • Fail workflow state: Stops your workflow with a failure. Task workflow state Managing state and transforming data Learn about Passing data between states with variables and Transforming data with JSONata. Reference list of workflow states 83 AWS Step Functions Developer Guide A Task state ("Type": "Task") represents a single unit of work performed by a state machine. A task performs work by using an activity or an AWS Lambda function, by integrating with other supported AWS services, or by invoking a HTTPS API, such as Stripe. The Amazon States Language represents tasks by setting a state's type to Task and by providing the task with the Amazon Resource Name (ARN) of the activity, Lambda function, or the HTTPS API endpoint. Invoke a function with JSONata Arguments The following Task state definition (JSONata) invokes a Lambda function named priceWatcher. Note the use of JSONata expressions to query input data to use in Arguments and the task result in the assign field. "Get Current Price": { "Type": "Task", "QueryLanguage" : "JSONata", "Resource": "arn:aws:states:::lambda:invoke", "Next": "Check Price", "Arguments": { "Payload": { "product": "{% $states.context.Execution.Input.product %}" }, "FunctionName": "arn:aws:lambda:<region>:account-id:function:priceWatcher:$LATEST" }, "Assign": { "currentPrice": "{% $states.result.Payload.current_price %}" } } Invoke a function with JSONPath Parameters The following Task state definition (JSONPath) invokes a Lambda function named HelloFunction. "Lambda Invoke": { "Type": "Task", "Resource": "arn:aws:states:::lambda:invoke", "Parameters": { "Payload.$": "$", "FunctionName": "arn:aws:lambda:region:account-id:function:HelloFunction:$LATEST" Task 84 AWS Step Functions }, "End": true } Task types Developer Guide Step Functions supports the following task types that you can specify in a Task state definition: • Activity • Lambda functions • A supported AWS service • An HTTP Task You specify a task type by providing its ARN in the Resource field of a Task state definition. The following example shows the syntax of the Resource field. All Task types except the one that invokes an HTTPS API, use the following syntax. For information about syntax of the HTTP Task, see Call HTTPS APIs in Step Functions workflows. In your Task state definition, replace the italicized text in the following syntax with the AWS resource-specific information. arn:partition:service:region:account:task_type:name The following list explains the individual components in this syntax: • partition is the AWS Step Functions partition to use, most commonly aws. • service indicates the AWS service used to execute the task, and can be one of the following values: • states for an activity. • lambda for a Lambda function. If you integrate with other AWS services, for example, Amazon SNS or Amazon DynamoDB, use sns or dynamodb. • region is the AWS Region code in which the Step Functions activity or state machine type, Lambda function, or any other AWS resource has been created. • account is the AWS account ID in which you've defined the resource. • task_type is the type of task to run. It can be one of the following values: • activity – An activity. Task types 85 AWS Step Functions Developer Guide • function – A Lambda function. • servicename – The name of a supported connected service (see Integrating services with Step Functions). • name is the registered resource name (activity name, Lambda function name, or service API action). Note Step Functions doesn't support referencing ARNs across partitions or regions. For example,
step-functions-dg-031
step-functions-dg.pdf
31
other AWS resource has been created. • account is the AWS account ID in which you've defined the resource. • task_type is the type of task to run. It can be one of the following values: • activity – An activity. Task types 85 AWS Step Functions Developer Guide • function – A Lambda function. • servicename – The name of a supported connected service (see Integrating services with Step Functions). • name is the registered resource name (activity name, Lambda function name, or service API action). Note Step Functions doesn't support referencing ARNs across partitions or regions. For example, aws-cn can't invoke tasks in the aws partition, and the other way around. The following sections provide more detail about each task type. Activity Activities represent workers (processes or threads), implemented and hosted by you, that perform a specific task. They are supported only by Standard Workflows, not Express Workflows. Activity Resource ARNs use the following syntax. arn:partition:states:region:account:activity:name Note You must create activities with Step Functions (using a CreateActivity, API action, or the Step Functions console) before their first use. For more information about creating an activity and implementing workers, see Activities. Lambda functions Lambda tasks execute a function using AWS Lambda. To specify a Lambda function, use the ARN of the Lambda function in the Resource field. Depending on the type of integration (Optimized integration or AWS SDK integration) you use for specifying a Lambda function, the syntax of your Lambda function's Resource field varies. Task types 86 AWS Step Functions Developer Guide The following Resource field syntax is an example of an optimized integration with a Lambda function. "arn:aws:states:::lambda:invoke" The following Resource field syntax is an example of an AWS SDK integration with a Lambda function. "arn:aws:states:::aws-sdk:lambda:invoke" The following Task state definition shows an example of an optimized integration with a Lambda function named HelloWorld. "LambdaState": { "Type": "Task", "Resource": "arn:aws:states:::lambda:invoke", "OutputPath": "$.Payload", "Parameters": { "Payload.$": "$", "FunctionName": "arn:aws:lambda:region:function:HelloWorld:$LATEST" }, "Next": "NextState" } After the Lambda function specified in the Resource field completes, its output is sent to the state identified in the Next field ("NextState"). A supported AWS service When you reference a connected resource, Step Functions directly calls the API actions of a supported service. Specify the service and action in the Resource field. Connected service Resource ARNs use the following syntax. arn:partition:states:region:placeholder-account:servicename:APIname Note To create a synchronous connection to a connected resource, append .sync to the APIname entry in the ARN. For more information, see Integrating services. Task types 87 Developer Guide AWS Step Functions For example: { "StartAt": "BATCH_JOB", "States": { "BATCH_JOB": { "Type": "Task", "Resource": "arn:aws:states:::batch:submitJob.sync", "Parameters": { "JobDefinition": "preprocessing", "JobName": "PreprocessingBatchJob", "JobQueue": "SecondaryQueue", "Parameters.$": "$.batchjob.parameters", "RetryStrategy": { "attempts": 5 } }, "End": true } } } Task state fields In addition to the common state fields, Task states have the following fields. Resource (Required) A URI, especially an ARN that uniquely identifies the specific task to execute. Arguments (Optional, JSONata only) Used to pass information to the API actions of connected resources. Values can include JSONata expressions. For more information, see Transforming data with JSONata in Step Functions. Output (Optional, JSONata only) Used to specify and transform output from the state. When specified, the value overrides the state output default. The output field accepts any JSON value (object, array, string, number, boolean, null). Any string value, including those inside objects or arrays, will be evaluated as JSONata if surrounded by {% %} characters. Task state fields 88 AWS Step Functions Developer Guide Output also accepts a JSONata expression directly, for example: "Output": "{% jsonata expression %}" For more information, see Input and Output Processing. Parameters (Optional, JSONPath only) Used to pass information to the API actions of connected resources. The parameters can use a mix of static JSON and JsonPath. For more information, see Passing parameters to a service API in Step Functions. Credentials (Optional) Specifies a target role the state machine's execution role must assume before invoking the specified Resource. Alternatively, you can also specify a JSONPath value or an intrinsic function that resolves to an IAM role ARN at runtime based on the execution input. If you specify a JSONPath value, you must prefix it with the $. notation. For examples of using this field in the Task state, see Task state's Credentials field examples. For an example of using this field to access a cross-account AWS resource from your state machine, see Accessing cross-account AWS resources in Step Functions. Note This field is supported by the Task types that use Lambda functions and a supported AWS service. ResultPath (Optional, JSONPath only) Specifies where (in the input) to place the results of executing the task that's specified in Resource. The input is then filtered as specified by the OutputPath field (if present) before being used as the state's output. For
step-functions-dg-032
step-functions-dg.pdf
32
examples of using this field in the Task state, see Task state's Credentials field examples. For an example of using this field to access a cross-account AWS resource from your state machine, see Accessing cross-account AWS resources in Step Functions. Note This field is supported by the Task types that use Lambda functions and a supported AWS service. ResultPath (Optional, JSONPath only) Specifies where (in the input) to place the results of executing the task that's specified in Resource. The input is then filtered as specified by the OutputPath field (if present) before being used as the state's output. For more information, see Input and Output Processing. ResultSelector (Optional, JSONPath only) Pass a collection of key value pairs, where the values are static or selected from the result. For more information, see ResultSelector. Retry (Optional) An array of objects, called Retriers, that define a retry policy if the state encounters runtime errors. For more information, see State machine examples using Retry and using Catch. Task state fields 89 AWS Step Functions Catch (Optional) Developer Guide An array of objects, called Catchers, that define a fallback state. This state is executed if the state encounters runtime errors and its retry policy is exhausted or isn't defined. For more information, see Fallback States. TimeoutSeconds (Optional) Specifies the maximum time an activity or a task can run before it times out with the States.Timeout error and fails. The timeout value must be positive, non-zero integer. The default value is 99999999. The timeout count begins after a task starts, for example, when ActivityStarted or LambdaFunctionStarted events are logged in the execution event history. For Activities, the count begins when GetActivityTask receives a token and ActivityStarted is logged in the execution event history. When a task starts, Step Functions waits for a success or failure response from the task or activity worker within the specified TimeoutSeconds duration. If the task or activity worker fails to respond within this time, Step Functions marks the workflow execution as failed. Note HTTP task timeout has a maximum of 60 seconds, even if TimeoutSeconds exceeds that limit. See the section called “Quotas related to HTTP Task” TimeoutSecondsPath (Optional, JSONPath only) If you want to provide a timeout value dynamically from the state input using a reference path, use TimeoutSecondsPath. When resolved, the reference path must select fields whose values are positive integers. Note A Task state cannot include both TimeoutSeconds and TimeoutSecondsPath. HTTP task timeout has a maximum of 60 seconds, even if the TimeoutSecondsPath value exceeds that limit. Task state fields 90 AWS Step Functions HeartbeatSeconds (Optional) Developer Guide Determines the frequency of heartbeat signals an activity worker sends during the execution of a task. Heartbeats indicate that a task is still running and it needs more time to complete. Heartbeats prevent an activity or task from timing out within the TimeoutSeconds duration. HeartbeatSeconds must be a positive, non-zero integer value less than the TimeoutSeconds field value. The default value is 99999999. If more time than the specified seconds elapses between heartbeats from the task, the Task state fails with a States.Timeout error. For Activities, the count begins when GetActivityTask receives a token and ActivityStarted is logged in the execution event history. HeartbeatSecondsPath (Optional, JSONPath only) If you want to provide a heartbeat value dynamically from the state input using a reference path, use HeartbeatSecondsPath. When resolved, the reference path must select fields whose values are positive integers. Note A Task state cannot include both HeartbeatSeconds and HeartbeatSecondsPath. A Task state must set either the End field to true if the state ends the execution, or must provide a state in the Next field that is run when the Task state is complete. Task state definition examples The following examples show how you can specify the Task state definition based on your requirement. • Specifying Task state timeouts and heartbeat intervals • Static timeout and heartbeat notification example • Dynamic task timeout and heartbeat notification example • Using Credentials field • Specifying hard-coded IAM role ARN Task state definition examples 91 AWS Step Functions Developer Guide • Specifying JSONPath as IAM role ARN • Specifying an intrinsic function as IAM role ARN Task state timeouts and heartbeat intervals It's a good practice to set a timeout value and a heartbeat interval for long-running activities. This can be done by specifying the timeout and heartbeat values, or by setting them dynamically. Static timeout and heartbeat notification example When HelloWorld completes, the next state (here called NextState) will be run. If this task fails to complete within 300 seconds, or doesn't send heartbeat notifications in intervals of 60 seconds, the task is marked as failed. "ActivityState": { "Type": "Task", "Resource": "arn:aws:states:region:123456789012:activity:HelloWorld", "TimeoutSeconds": 300, "HeartbeatSeconds": 60, "Next": "NextState" } Dynamic task timeout and heartbeat notification example In this example, when the
step-functions-dg-033
step-functions-dg.pdf
33
It's a good practice to set a timeout value and a heartbeat interval for long-running activities. This can be done by specifying the timeout and heartbeat values, or by setting them dynamically. Static timeout and heartbeat notification example When HelloWorld completes, the next state (here called NextState) will be run. If this task fails to complete within 300 seconds, or doesn't send heartbeat notifications in intervals of 60 seconds, the task is marked as failed. "ActivityState": { "Type": "Task", "Resource": "arn:aws:states:region:123456789012:activity:HelloWorld", "TimeoutSeconds": 300, "HeartbeatSeconds": 60, "Next": "NextState" } Dynamic task timeout and heartbeat notification example In this example, when the AWS Glue job completes, the next state will be run. If this task fails to complete within the interval set dynamically by the AWS Glue job, the task is marked as failed. "GlueJobTask": { "Type": "Task", "Resource": "arn:aws:states:::glue:startJobRun.sync", "Parameters": { "JobName": "myGlueJob" }, "TimeoutSecondsPath": "$.params.maxTime", "Next": "NextState" } Task state definition examples 92 AWS Step Functions Developer Guide Task state's Credentials field examples Specifying hard-coded IAM role ARN The following example specifies a target IAM role that a state machine's execution role must assume to access a cross-account Lambda function named Echo. In this example, the target role ARN is specified as a hard-coded value. { "StartAt": "Cross-account call", "States": { "Cross-account call": { "Type": "Task", "Resource": "arn:aws:states:::lambda:invoke", "Credentials": { "RoleArn": "arn:aws:iam::111122223333:role/LambdaRole" }, "Parameters": { "FunctionName": "arn:aws:lambda:us-east-2:111122223333:function:Echo" }, "End": true } } } Specifying JSONPath as IAM role ARN The following example specifies a JSONPath value, which will resolve to an IAM role ARN at runtime. { "StartAt": "Lambda", "States": { "Lambda": { "Type": "Task", "Resource": "arn:aws:states:::lambda:invoke", "Credentials": { "RoleArn.$": "$.roleArn" }, ... } } Task state definition examples 93 AWS Step Functions } Developer Guide Specifying an intrinsic function as IAM role ARN The following example uses the States.Format intrinsic function, which resolves to an IAM role ARN at runtime. { "StartAt": "Lambda", "States": { "Lambda": { "Type": "Task", "Resource": "arn:aws:states:::lambda:invoke", "Credentials": { "RoleArn.$": "States.Format('arn:aws:iam::{}:role/ROLENAME', $.accountId)" }, ... } } } Choice workflow state Managing state and transforming data Learn about Passing data between states with variables and Transforming data with JSONata. A Choice state ("Type": "Choice") adds conditional logic to a state machine. In addition to most of the common state fields, Choice states contains the following additional fields. Choices (Required) An array of Choice Rules that determines which state the state machine transitions to next. When a Choice state is run, it evaluates each Choice Rule to true or false. Based on the result of this evaluation, Step Functions transitions to the next state in the workflow. Choice 94 AWS Step Functions Developer Guide You must define at least one rule in the Choice state. Default (Optional, Recommended) The name of the state to transition to if none of the transitions in Choices is taken. Important Choice states don't support the End field. In addition, they use Next only inside their Choices field. Choice Rules (JSONata) A Choice state must have a Choices field whose value is a non-empty array of Choice Rules, which contain the following fields when using JSONata: • Condition field – a JSONata expression that evaluates to true/false. • Next field – a value that must match a state name in the state machine. The following example checks whether the numerical value is equal to 1. { "Condition": "{% $foo = 1 %}", "Next": "NumericMatchState" } The following example checks whether the typevariable is equal to local. { "Condition": "{% $type = 'local' %}", "Next": "StringMatchState" } The following example checks whether the string is greater than MyStringABC. { "Condition": "{% $foo > 'MyStringABC' %}", "Next": "StringGreaterMatchState" Choice Rules (JSONata) 95 AWS Step Functions } Developer Guide The following example checks whether the string is not null. { "Condition" : "{% $possiblyNullValue != null and $possiblyNullValue = 42 %}", "Next": "NotNullAnd42" } Choice Rules (JSONPath) A Choice state must have a Choices field whose value is a non-empty array of Choice Rules, which contain the following fields when using JSONPath: • A comparison – Two fields that specify an input variable to compare, the type of comparison, and the value to compare the variable to. Choice Rules support comparison between two variables. Within a Choice Rule, the value of variable can be compared with another value from the state input by appending Path to name of supported comparison operators. The values of Variable and Path fields in a comparison must be valid Reference Paths. • A Next field – The value of this field must match a state name in the state machine. The following example checks whether the numerical value is equal to 1. { "Variable": "$.foo", "NumericEquals": 1, "Next": "FirstMatchState" } The following example checks whether the string is equal to MyString. { "Variable": "$.foo", "StringEquals": "MyString", "Next": "FirstMatchState" } The
step-functions-dg-034
step-functions-dg.pdf
34
a Choice Rule, the value of variable can be compared with another value from the state input by appending Path to name of supported comparison operators. The values of Variable and Path fields in a comparison must be valid Reference Paths. • A Next field – The value of this field must match a state name in the state machine. The following example checks whether the numerical value is equal to 1. { "Variable": "$.foo", "NumericEquals": 1, "Next": "FirstMatchState" } The following example checks whether the string is equal to MyString. { "Variable": "$.foo", "StringEquals": "MyString", "Next": "FirstMatchState" } The following example checks whether the string is greater than MyStringABC. Choice Rules (JSONPath) 96 AWS Step Functions Developer Guide { "Variable": "$.foo", "StringGreaterThan": "MyStringABC", "Next": "FirstMatchState" } The following example checks whether the string is null. { "Variable": "$.possiblyNullValue", "IsNull": true } The following example shows how the StringEquals rule is only evaluated when $.keyThatMightNotExist exists because of the preceding IsPresent Choice Rule. "And": [ { "Variable": "$.keyThatMightNotExist", "IsPresent": true }, { "Variable": "$.keyThatMightNotExist", "StringEquals": "foo" } ] The following example checks whether a pattern with a wildcard matches. { "Variable": "$.foo", "StringMatches": "log-*.txt" } The following example checks whether the timestamp is equal to 2001-01-01T12:00:00Z. { "Variable": "$.foo", "TimestampEquals": "2001-01-01T12:00:00Z", "Next": "FirstMatchState" Choice Rules (JSONPath) 97 AWS Step Functions } Developer Guide The following example compares a variable with another value from the state input. { "Variable": "$.foo", "StringEqualsPath": "$.bar" } Step Functions examines each of the Choice Rules in the order listed in the Choices field. Then it transitions to the state specified in the Next field of the first Choice Rule in which the variable matches the value according to the comparison operator. The following comparison operators are supported: • And • BooleanEquals,BooleanEqualsPath • IsBoolean • IsNull • IsNumeric • IsPresent • IsString • IsTimestamp • Not • NumericEquals,NumericEqualsPath • NumericGreaterThan,NumericGreaterThanPath • NumericGreaterThanEquals,NumericGreaterThanEqualsPath • NumericLessThan,NumericLessThanPath • NumericLessThanEquals,NumericLessThanEqualsPath • Or • StringEquals,StringEqualsPath • StringGreaterThan,StringGreaterThanPath • StringGreaterThanEquals,StringGreaterThanEqualsPath Choice Rules (JSONPath) 98 AWS Step Functions Developer Guide • StringLessThan,StringLessThanPath • StringLessThanEquals,StringLessThanEqualsPath • StringMatches • TimestampEquals,TimestampEqualsPath • TimestampGreaterThan,TimestampGreaterThanPath • TimestampGreaterThanEquals,TimestampGreaterThanEqualsPath • TimestampLessThan,TimestampLessThanPath • TimestampLessThanEquals,TimestampLessThanEqualsPath For each of these operators, the corresponding value must be of the appropriate type: string, number, Boolean, or timestamp. Step Functions doesn't attempt to match a numeric field to a string value. However, because timestamp fields are logically strings, it's possible that a field considered to be a timestamp can be matched by a StringEquals comparator. Note For interoperability, don't assume that numeric comparisons work with values outside the magnitude or precision that the IEEE 754-2008 binary64 data type represents. In particular, integers outside of the range [-253+1, 253-1] might fail to compare in the expected way. Timestamps (for example, 2016-08-18T17:33:00Z) must conform to RFC3339 profile ISO 8601, with further restrictions: • An uppercase T must separate the date and time portions. • An uppercase Z must denote that a numeric time zone offset isn't present. To understand the behavior of string comparisons, see the Java compareTo documentation. The values of the And and Or operators must be non-empty arrays of Choice Rules that must not themselves contain Next fields. Likewise, the value of a Not operator must be a single Choice Rule that must not contain Next fields. You can create complex, nested Choice Rules using And, Not, and Or. However, the Next field can appear only in a top-level Choice Rule. String comparison against patterns with one or more wildcards (“*”) can be performed with the StringMatches comparison operator. The wildcard character is escaped by using the Choice Rules (JSONPath) 99 AWS Step Functions Developer Guide standard \\ (Ex: “\\*”). No characters other than “*” have any special meaning during matching. Parallel workflow state Managing state and transforming data Learn about Passing data between states with variables and Transforming data with JSONata. The Parallel state ("Type": "Parallel") can be used to add separate branches of execution in your state machine. In addition to the common state fields, Parallel states include these additional fields. Branches (Required) An array of objects that specify state machines to execute in parallel. Each such state machine object must have fields named States and StartAt, whose meanings are exactly like those in the top level of a state machine. Parameters (Optional, JSONPath only) Used to pass information to the state machines defined in the Branches array. Arguments (Optional, JSONata only) Used to pass information to the API actions of connected resources. Values can include JSONata expressions. For more information, see Transforming data with JSONata in Step Functions. Output (Optional, JSONata only) Used to specify and transform output from the state. When specified, the value overrides the state output default. The output field accepts any JSON value (object, array, string, number, boolean, null). Any string value, including those inside objects or arrays,
step-functions-dg-035
step-functions-dg.pdf
35
in the top level of a state machine. Parameters (Optional, JSONPath only) Used to pass information to the state machines defined in the Branches array. Arguments (Optional, JSONata only) Used to pass information to the API actions of connected resources. Values can include JSONata expressions. For more information, see Transforming data with JSONata in Step Functions. Output (Optional, JSONata only) Used to specify and transform output from the state. When specified, the value overrides the state output default. The output field accepts any JSON value (object, array, string, number, boolean, null). Any string value, including those inside objects or arrays, will be evaluated as JSONata if surrounded by {% %} characters. Parallel 100 AWS Step Functions Developer Guide Output also accepts a JSONata expression directly, for example: "Output": "{% jsonata expression %}" For more information, see the section called “Transforming data”. Assign (Optional) Used to store variables. The Assign field accepts a JSON object with key/value pairs that define variable names and their assigned values. Any string value, including those inside objects or arrays, will be evaluated as JSONata when surrounded by {% %} characters For more information, see the section called “Passing data with variables”. ResultPath (Optional, JSONPath only) Specifies where (in the input) to place the output of the branches. The input is then filtered as specified by the OutputPath field (if present) before being used as the state's output. For more information, see Input and Output Processing. ResultSelector (Optional, JSONPath only) Pass a collection of key value pairs, where the values are static or selected from the result. For more information, see ResultSelector. Retry (Optional) An array of objects, called Retriers, that define a retry policy in case the state encounters runtime errors. For more information, see State machine examples using Retry and using Catch. Catch (Optional) An array of objects, called Catchers, that define a fallback state that is executed if the state encounters runtime errors and its retry policy is exhausted or isn't defined. For more information, see Fallback States. A Parallel state causes AWS Step Functions to execute each branch, starting with the state named in that branch's StartAt field, as concurrently as possible, and wait until all branches terminate (reach a terminal state) before processing the Parallel state's Next field. Parallel State Example { Parallel State Example 101 AWS Step Functions Developer Guide "Comment": "Parallel Example.", "StartAt": "LookupCustomerInfo", "States": { "LookupCustomerInfo": { "Type": "Parallel", "End": true, "Branches": [ { "StartAt": "LookupAddress", "States": { "LookupAddress": { "Type": "Task", "Resource": "arn:aws:lambda:region:account-id:function:AddressFinder", "End": true } } }, { "StartAt": "LookupPhone", "States": { "LookupPhone": { "Type": "Task", "Resource": "arn:aws:lambda:region:account-id:function:PhoneFinder", "End": true } } } ] } } } In this example, the LookupAddress and LookupPhone branches are executed in parallel. Here is how the visual workflow looks in the Step Functions console. Parallel State Example 102 AWS Step Functions Developer Guide Each branch must be self-contained. A state in one branch of a Parallel state must not have a Next field that targets a field outside of that branch, nor can any other state outside the branch transition into that branch. Parallel State Input and Output Processing A Parallel state provides each branch with a copy of its own input data (subject to modification by the InputPath field). It generates output that is an array with one element for each branch, containing the output from that branch. There is no requirement that all elements be of the same type. The output array can be inserted into the input data (and the whole sent as the Parallel state's output) by using a ResultPath field in the usual way (see Input and Output Processing). { "Comment": "Parallel Example.", "StartAt": "FunWithMath", Parallel State Input and Output Processing 103 AWS Step Functions "States": { "FunWithMath": { "Type": "Parallel", "End": true, "Branches": [ { "StartAt": "Add", "States": { "Add": { "Type": "Task", Developer Guide "Resource": "arn:aws:states:region:123456789012:activity:Add", "End": true } } }, { "StartAt": "Subtract", "States": { "Subtract": { "Type": "Task", "Resource": "arn:aws:states:region:123456789012:activity:Subtract", "End": true } } } ] } } } If the FunWithMath state was given the array [3, 2] as input, then both the Add and Subtract states receive that array as input. The output of the Add and Subtract tasks would be the sum of and difference between the array elements 3 and 2, which is 5 and 1, while the output of the Parallel state would be an array. [ 5, 1 ] Parallel State Input and Output Processing 104 AWS Step Functions Tip Developer Guide If the Parallel or Map state you use in your state machines returns an array of arrays, you can transform them into a flat array with the ResultSelector field. For more information, see Flattening an array of arrays. Error Handling If any branch fails, because of an unhandled error or by transitioning
step-functions-dg-036
step-functions-dg.pdf
36
tasks would be the sum of and difference between the array elements 3 and 2, which is 5 and 1, while the output of the Parallel state would be an array. [ 5, 1 ] Parallel State Input and Output Processing 104 AWS Step Functions Tip Developer Guide If the Parallel or Map state you use in your state machines returns an array of arrays, you can transform them into a flat array with the ResultSelector field. For more information, see Flattening an array of arrays. Error Handling If any branch fails, because of an unhandled error or by transitioning to a Fail state, the entire Parallel state is considered to have failed and all its branches are stopped. If the error is not handled by the Parallel state itself, Step Functions stops the execution with an error. Note When a parallel state fails, invoked Lambda functions continue to run and activity workers processing a task token are not stopped. • To stop long-running activities, use heartbeats to detect if its branch has been stopped by Step Functions, and stop workers that are processing tasks. Calling SendTaskHeartbeat, SendTaskSuccess, or SendTaskFailure will throw an error if the state has failed. See Heartbeat Errors. • Running Lambda functions cannot be stopped. If you have implemented a fallback, use a Wait state so that cleanup work happens after the Lambda function has finished. Map workflow state Use the Map state to run a set of workflow steps for each item in a dataset. The Map state's iterations run in parallel, which makes it possible to process a dataset quickly. Map states can use a variety of input types, including a JSON array, a list of Amazon S3 objects, or a CSV file. Step Functions provides two types of processing modes for using the Map state in your workflows: Inline mode and Distributed mode. Error Handling 105 AWS Step Functions Tip Developer Guide To deploy an example of a workflow that uses a Map state, see Processing arrays of data with Choice and Map in The AWS Step Functions Workshop. Map state processing modes Step Functions provides the following processing modes for the Map state depending on how you want to process the items in a dataset. • Inline – Limited-concurrency mode. In this mode, each iteration of the Map state runs in the context of the workflow that contains the Map state. Step Functions adds the execution history of these iterations to the parent workflow's execution history. By default, Map states run in Inline mode. In this mode, the Map state accepts only a JSON array as input. Also, this mode supports up to 40 concurrent iterations. For more information, see Using Map state in Inline mode in Step Functions workflows. • Distributed – High-concurrency mode. In this mode, the Map state runs each iteration as a child workflow execution, which enables high concurrency of up to 10,000 parallel child workflow executions. Each child workflow execution has its own, separate execution history from that of the parent workflow. In this mode, the Map state can accept either a JSON array or an Amazon S3 data source, such as a CSV file, as its input. For more information, see Distributed mode. The mode you should use depends on how you want to process the items in a dataset. Use the Map state in Inline mode if your workflow's execution history won't exceed 25,000 entries, or if you don't require more than 40 concurrent iterations. Use the Map state in Distributed mode when you need to orchestrate large-scale parallel workloads that meet any combination of the following conditions: • The size of your dataset exceeds 256 KiB. Map processing modes 106 AWS Step Functions Developer Guide • The workflow's execution event history would exceed 25,000 entries. • You need a concurrency of more than 40 concurrent iterations. Inline mode and Distributed mode differences The following table highlights the differences between the Inline and Distributed modes. Inline mode Distributed mode Supported data sources Accepts a JSON array passed from a previous step in the workflow as input. Accepts the following data sources as input: • JSON array passed from a previous step in the workflow • JSON file in an Amazon S3 bucket that contains an array • CSV file in an Amazon S3 bucket • Amazon S3 object list • Amazon S3 inventory Map iterations In this mode, each iteration of the Map state runs in the context of the workflow that In this mode, the Map state runs each iteration as a child workflow execution, which enables contains the Map state. Step Functions adds the execution history of these iterations to the high concurrency of up to 10,000 parallel child workflow executions. Each child workflow parent workflow's execution history. execution has its own, separate
step-functions-dg-037
step-functions-dg.pdf
37
JSON file in an Amazon S3 bucket that contains an array • CSV file in an Amazon S3 bucket • Amazon S3 object list • Amazon S3 inventory Map iterations In this mode, each iteration of the Map state runs in the context of the workflow that In this mode, the Map state runs each iteration as a child workflow execution, which enables contains the Map state. Step Functions adds the execution history of these iterations to the high concurrency of up to 10,000 parallel child workflow executions. Each child workflow parent workflow's execution history. execution has its own, separate execution history from that of the parent workflow. Maximum concurrency for parallel iterations Lets you run up to 40 iterations as concurren tly as possible. Input payload and event history sizes Lets you run up to 10,000 parallel child workflow executions to process millions of data items at one time. Map processing modes 107 AWS Step Functions Inline mode Distributed mode Developer Guide Enforces a limit of 256 KiB on the input payload size and 25,000 entries in the execution event history. Lets you overcome the payload size limitation because the Map state can read input directly from Amazon S3 data sources. In this mode, you can also overcome execution history limitations because the child workflow executions started by the Map state maintain their own, separate execution histories from the parent workflow's execution history. Monitoring and observability You can review the workflow's execution history from the console or by invoking the When you run a Map state in Distributed mode, Step Functions creates a Map Run GetExecutionHistory API action. resource. A Map Run refers to a set of child You can also view the execution history through CloudWatch and X-Ray. workflow executions that a Distributed Map state starts. You can view a Map Run in the Step Functions console. You can also invoke the DescribeMapRun API action. A Map Run also emits metrics to CloudWatch. For more information, see Viewing a Distribut ed Map Run execution in Step Functions. Using Map state in Inline mode in Step Functions workflows Managing state and transforming data Learn about Passing data between states with variables and Transforming data with JSONata. By default, Map states runs in Inline mode. In Inline mode, the Map state accepts only a JSON array as input. It receives this array from a previous step in the workflow. In this mode, each iteration of Inline mode 108 AWS Step Functions Developer Guide the Map state runs in the context of the workflow that contains the Map state. Step Functions adds the execution history of these iterations to the parent workflow's execution history. In this mode, the Map state supports up to 40 concurrent iterations. A Map state set to Inline is known as an Inline Map state. Use the Map state in Inline mode if your workflow's execution history won't exceed 25,000 entries, or if you don't require more than 40 concurrent iterations. For an introduction to using the Inline Map state, see the tutorial Repeat actions with Inline Map. Contents • Key concepts in this topic • Inline Map state fields • Deprecated fields • Inline Map state example (JSONPath) • Inline Map state example with ItemSelector • Inline Map state input and output processing Key concepts in this topic Inline mode A limited-concurrency mode of the Map state. In this mode, each iteration of the Map state runs in the context of the workflow that contains the Map state. Step Functions adds the execution history of these iterations to the parent workflow's execution history. Map states run in the Inline mode by default. This mode accepts only a JSON array as input and supports up to 40 concurrent iterations. Inline Map state A Map state set to the Inline mode. Map workflow The set of steps that the Map state runs for each iteration. Map state iteration A repetition of the workflow defined inside of the Map state. Inline mode 109 AWS Step Functions Inline Map state fields Developer Guide To use the Inline Map state in your workflows, specify one or more of these fields. You specify these fields in addition to the common state fields. Type (Required) Sets the type of state, such as Map. ItemProcessor (Required) Contains the following JSON objects that specify the Map state processing mode and definition. The definition contains the set of steps to repeat for processing each array item. • ProcessorConfig – An optional JSON object that specifies the processing mode for the Map state. This object contains the Mode sub-field. This field defaults to INLINE, which uses the Map state in Inline mode. In this mode, the failure of any iteration causes the Map state to fail. All iterations stop when the Map state fails. • StartAt –
step-functions-dg-038
step-functions-dg.pdf
38
Type (Required) Sets the type of state, such as Map. ItemProcessor (Required) Contains the following JSON objects that specify the Map state processing mode and definition. The definition contains the set of steps to repeat for processing each array item. • ProcessorConfig – An optional JSON object that specifies the processing mode for the Map state. This object contains the Mode sub-field. This field defaults to INLINE, which uses the Map state in Inline mode. In this mode, the failure of any iteration causes the Map state to fail. All iterations stop when the Map state fails. • StartAt – Specifies a string that indicates the first state in a workflow. This string is case- sensitive and must match the name of one of the state objects. This state runs first for each item in the dataset. Any execution input that you provide to the Map state passes to the StartAt state first. • States – A JSON object containing a comma-delimited set of states. In this object, you define the Map workflow. Note • States within the ItemProcessor field can only transition to each other. No state outside the ItemProcessor field can transition to a state within it. • The ItemProcessor field replaces the now deprecated Iterator field. Although you can continue to include Map states that use the Iterator field, we highly recommend that you replace this field with ItemProcessor. Step Functions Local doesn't currently support the ItemProcessor field. We recommend that you use the Iterator field with Step Functions Local. Inline mode 110 AWS Step Functions Developer Guide Items (Optional, JSONata only) A JSON array or a JSONata expression that must evaluate to an array. ItemsPath (Optional, JSONPath only) Specifies a reference path using the JsonPath syntax. This path selects the JSON node that contains the array of items inside the state input. For more information, see ItemsPath (Map, JSONPath only). ItemSelector (Optional) Overrides the values of the input array items before they're passed on to each Map state iteration. In this field, you specify a valid JSON that contains a collection of key-value pairs. These pairs can contain any of the following: • Static values you define in your state machine definition. • Values selected from the state input using a path. • Values accessed from the context object. For more information, see ItemSelector (Map). The ItemSelector field replaces the now deprecated Parameters field. Although you can continue to include Map states that use the Parameters field, we highly recommend that you replace this field with ItemSelector. MaxConcurrency (Optional) Specifies an integer value that provides the upper bound on the number of Map state iterations that can run in parallel. For example, a MaxConcurrency value of 10 limits the Map state to 10 concurrent iterations running at one time. In JSONata states, you can specify a JSONata expression that evaluates to an integer. Note Concurrent iterations may be limited. When this occurs, some iterations won't begin until previous iterations are complete. The likelihood of this occurring increases when your input array has more than 40 items. To achieve a higher concurrency, consider Distributed mode. Inline mode 111 AWS Step Functions Developer Guide The default value is 0, which places no limit on concurrency. Step Functions invokes iterations as concurrently as possible. A MaxConcurrency value of 1 invokes the ItemProcessor once for each array element. Items in the array are processed in the order of their appearance in the input. Step Functions doesn't start a new iteration until it completes the previous iteration. MaxConcurrencyPath (Optional, JSONPath only) If you want to provide a maximum concurrency value dynamically from the state input using a reference path, use MaxConcurrencyPath. When resolved, the reference path must select a field whose value is a non-negative integer. Note A Map state cannot include both MaxConcurrency and MaxConcurrencyPath. ResultPath (Optional, JSONPath only) Specifies where in the input to store the output of the Map state's iterations. The Map state then filters the input as specified by the OutputPath field, if specified. Then, it uses the filtered input as the state's output. For more information, see Input and Output Processing. ResultSelector (Optional, JSONPath only) Pass a collection of key value pairs, where the values are either static or selected from the result. For more information, see ResultSelector. Tip If the Parallel or Map state you use in your state machines returns an array of arrays, you can transform them into a flat array with the ResultSelector field. For more information, see Flattening an array of arrays. Retry (Optional) An array of objects, called Retriers, that define a retry policy. States use a retry policy when they encounter runtime errors. For more information, see State machine examples using Retry and using Catch. Inline mode 112 AWS Step Functions Note Developer Guide If you define Retriers
step-functions-dg-039
step-functions-dg.pdf
39
are either static or selected from the result. For more information, see ResultSelector. Tip If the Parallel or Map state you use in your state machines returns an array of arrays, you can transform them into a flat array with the ResultSelector field. For more information, see Flattening an array of arrays. Retry (Optional) An array of objects, called Retriers, that define a retry policy. States use a retry policy when they encounter runtime errors. For more information, see State machine examples using Retry and using Catch. Inline mode 112 AWS Step Functions Note Developer Guide If you define Retriers for the Inline Map state, the retry policy applies to all Map state iterations, instead of only failed iterations. For example, your Map state contains two successful iterations and one failed iteration. If you have defined the Retry field for the Map state, the retry policy applies to all three Map state iterations instead of only the failed iteration. Catch (Optional) An array of objects, called Catchers, that define a fallback state. States run a catcher if they encounter runtime errors and either don't have a retry policy, or their retry policy is exhausted. For more information, see Fallback States. Output (Optional, JSONata only) Used to specify and transform output from the state. When specified, the value overrides the state output default. The output field accepts any JSON value (object, array, string, number, boolean, null). Any string value, including those inside objects or arrays, will be evaluated as JSONata if surrounded by {% %} characters. Output also accepts a JSONata expression directly, for example: "Output": "{% jsonata expression %}" For more information, see the section called “Transforming data”. Assign (Optional) Used to store variables. The Assign field accepts a JSON object with key/value pairs that define variable names and their assigned values. Any string value, including those inside objects or arrays, will be evaluated as JSONata when surrounded by {% %} characters For more information, see the section called “Passing data with variables”. Inline mode 113 AWS Step Functions Deprecated fields Note Developer Guide Although you can continue to include Map states that use the following fields, we highly recommend that you replace Iterator with ItemProcessor and Parameters with ItemSelector. Iterator Specifies a JSON object that defines a set of steps that process each element of the array. Parameters Specifies a collection of key-value pairs, where the values can contain any of the following: • Static values that you define in your state machine definition. • Values selected from the input using a path. Inline Map state example (JSONPath) Consider the following input data for a Map state running in Inline mode. { "ship-date": "2016-03-14T01:59:00Z", "detail": { "delivery-partner": "UQS", "shipped": [ { "prod": "R31", "dest-code": 9511, "quantity": 1344 }, { "prod": "S39", "dest-code": 9511, "quantity": 40 }, { "prod": "R31", "dest-code": 9833, "quantity": 12 }, { "prod": "R40", "dest-code": 9860, "quantity": 887 }, { "prod": "R40", "dest-code": 9511, "quantity": 1220 } ] } } Given the previous input, the Map state in the following example invokes an AWS Lambda function named ship-val once for each item of the array in the shipped field. "Validate All": { Inline mode 114 AWS Step Functions Developer Guide "Type": "Map", "InputPath": "$.detail", "ItemProcessor": { "ProcessorConfig": { "Mode": "INLINE" }, "StartAt": "Validate", "States": { "Validate": { "Type": "Task", "Resource": "arn:aws:states:::lambda:invoke", "OutputPath": "$.Payload", "Parameters": { "FunctionName": "arn:aws:lambda:us-east-2:account-id:function:ship- val:$LATEST" }, "End": true } } }, "End": true, "ResultPath": "$.detail.shipped", "ItemsPath": "$.shipped" } Each iteration of the Map state sends an item in the array, selected with the ItemsPath field, as input to the ship-val Lambda function. The following values are an example of input the Map state sends to an invocation of the Lambda function: { "prod": "R31", "dest-code": 9511, "quantity": 1344 } When complete, the output of the Map state is a JSON array, where each item is the output of an iteration. In this case, this array contains the output of the ship-val Lambda function. Inline Map state example with ItemSelector Suppose that the ship-val Lambda function in the previous example also needs information about the shipment's courier. This information is in addition to the items in the array for each Inline mode 115 AWS Step Functions Developer Guide iteration. You can include information from the input, along with information specific to the current iteration of the Map state. Note the ItemSelector field in the following example: "Validate-All": { "Type": "Map", "InputPath": "$.detail", "ItemsPath": "$.shipped", "MaxConcurrency": 0, "ResultPath": "$.detail.shipped", "ItemSelector": { "parcel.$": "$$.Map.Item.Value", "courier.$": "$.delivery-partner" }, "ItemProcessor": { "StartAt": "Validate", "States": { "Validate": { "Type": "Task", "Resource": "arn:aws:lambda:region:account-id:function:ship-val", "End": true } } }, "End": true } The ItemSelector block replaces the input to the iterations with a JSON node. This node contains both the current item data from the Context object and the courier information
step-functions-dg-040
step-functions-dg.pdf
40
Step Functions Developer Guide iteration. You can include information from the input, along with information specific to the current iteration of the Map state. Note the ItemSelector field in the following example: "Validate-All": { "Type": "Map", "InputPath": "$.detail", "ItemsPath": "$.shipped", "MaxConcurrency": 0, "ResultPath": "$.detail.shipped", "ItemSelector": { "parcel.$": "$$.Map.Item.Value", "courier.$": "$.delivery-partner" }, "ItemProcessor": { "StartAt": "Validate", "States": { "Validate": { "Type": "Task", "Resource": "arn:aws:lambda:region:account-id:function:ship-val", "End": true } } }, "End": true } The ItemSelector block replaces the input to the iterations with a JSON node. This node contains both the current item data from the Context object and the courier information from the Map state input's delivery-partner field. The following is an example of input to a single iteration. The Map state passes this input to an invocation of the ship-val Lambda function. { "parcel": { "prod": "R31", "dest-code": 9511, "quantity": 1344 }, "courier": "UQS" } Inline mode 116 AWS Step Functions Developer Guide In the previous Inline Map state example, the ResultPath field produces output in the same format as the input. However, it overwrites the detail.shipped field with an array in which each element is the output of each iteration's ship-val Lambda invocation. For more information about using the Inline Map state state and its fields, see the following. • Repeat actions with Inline Map • Processing input and output in Step Functions • ItemsPath (Map, JSONPath only) • Context object data for Map states Inline Map state input and output processing For a given Map state, InputPath selects a subset of the state's input. The input of a Map state must include a JSON array. The Map state runs the ItemProcessor section once for each item in the array. If you specify the ItemsPath field, the Map state selects where in the input to find the array to iterate over. If not specified, the value of ItemsPath is $, and the ItemProcessor section expects that the array is the only input. If you specify the ItemsPath field, its value must be a Reference Path. The Map state applies this path to the effective input after it applies the InputPath. The ItemsPath must identify a field whose value is a JSON array. The input to each iteration, by default, is a single element of the array field identified by the ItemsPath value. You can override this value with the ItemSelector (Map) field. When complete, the output of the Map state is a JSON array, where each item is the output of an iteration. For more information about Inline Map state inputs and outputs, see the following: • Repeat actions with Inline Map • Inline Map state example with ItemSelector • Processing input and output in Step Functions • Context object data for Map states • Process data from a queue with a Map state in Step Functions Inline mode 117 AWS Step Functions Developer Guide Using Map state in Distributed mode for large-scale parallel workloads in Step Functions Managing state and transforming data Learn about Passing data between states with variables and Transforming data with JSONata. With Step Functions, you can orchestrate large-scale parallel workloads to perform tasks, such as on-demand processing of semi-structured data. These parallel workloads let you concurrently process large-scale data sources stored in Amazon S3. For example, you might process a single JSON or CSV file that contains large amounts of data. Or you might process a large set of Amazon S3 objects. To set up a large-scale parallel workload in your workflows, include a Map state in Distributed mode. The Map state processes items in a dataset concurrently. A Map state set to Distributed is known as a Distributed Map state. In Distributed mode, the Map state allows high-concurrency processing. In Distributed mode, the Map state processes the items in the dataset in iterations called child workflow executions. You can specify the number of child workflow executions that can run in parallel. Each child workflow execution has its own, separate execution history from that of the parent workflow. If you don't specify, Step Functions runs 10,000 parallel child workflow executions in parallel. The following illustration explains how you can set up large-scale parallel workloads in your workflows. Distributed mode 118 AWS Step Functions Developer Guide Learn in a workshop Learn how serverless technologies such as Step Functions and Lambda can simplify management and scaling, offload undifferentiated tasks, and address the challenges of large-scale distributed data processing. Along the way, you will work with distributed map for high concurrency processing. The workshop also presents best practices for optimizing your workflows, and practical use cases for claims processing, vulnerability scanning, and Monte Carlo simulation. Workshop: Large-scale Data Processing with Step Functions Distributed mode 119 AWS Step Functions In this topic • Key terms • Distributed Map state definition example (JSONPath) • Permissions to run Distributed Map
step-functions-dg-041
step-functions-dg.pdf
41
Guide Learn in a workshop Learn how serverless technologies such as Step Functions and Lambda can simplify management and scaling, offload undifferentiated tasks, and address the challenges of large-scale distributed data processing. Along the way, you will work with distributed map for high concurrency processing. The workshop also presents best practices for optimizing your workflows, and practical use cases for claims processing, vulnerability scanning, and Monte Carlo simulation. Workshop: Large-scale Data Processing with Step Functions Distributed mode 119 AWS Step Functions In this topic • Key terms • Distributed Map state definition example (JSONPath) • Permissions to run Distributed Map • Distributed Map state fields • Setting failure thresholds for Distributed Map states in Step Functions • Learn more about distributed maps Developer Guide Key terms Distributed mode A processing mode of the Map state. In this mode, each iteration of the Map state runs as a child workflow execution that enables high concurrency. Each child workflow execution has its own execution history, which is separate from the parent workflow's execution history. This mode supports reading input from large-scale Amazon S3 data sources. Distributed Map state A Map state set to Distributed processing mode. Map workflow A set of steps that a Map state runs. Parent workflow A workflow that contains one or more Distributed Map states. Child workflow execution An iteration of the Distributed Map state. A child workflow execution has its own execution history, which is separate from the parent workflow's execution history. Map Run When you run a Map state in Distributed mode, Step Functions creates a Map Run resource. A Map Run refers to a set of child workflow executions that a Distributed Map state starts, and the runtime settings that control these executions. Step Functions assigns an Amazon Resource Name (ARN) to your Map Run. You can examine a Map Run in the Step Functions console. You can also invoke the DescribeMapRun API action. Distributed mode 120 AWS Step Functions Developer Guide Map Runs do not emit metrics to CloudWatch. However, child workflow executions of a Map Run do emit metrics to CloudWatch. These metrics will have a labelled State Machine ARN with the following format: arn:partition:states:region:account:stateMachine:stateMachineName/MapRunLabel or UUID For more information, see Viewing Map Runs. Distributed Map state definition example (JSONPath) Use the Map state in Distributed mode when you need to orchestrate large-scale parallel workloads that meet any combination of the following conditions: • The size of your dataset exceeds 256 KiB. • The workflow's execution event history would exceed 25,000 entries. • You need a concurrency of more than 40 concurrent iterations. The following Distributed Map state definition example specifies the dataset as a CSV file stored in an Amazon S3 bucket. It also specifies a Lambda function that processes the data in each row of the CSV file. Because this example uses a CSV file, it also specifies the location of the CSV column headers. To view the complete state machine definition of this example, see the tutorial Copying large-scale CSV data using Distributed Map. { "Map": { "Type": "Map", "ItemReader": { "ReaderConfig": { "InputType": "CSV", "CSVHeaderLocation": "FIRST_ROW" }, "Resource": "arn:aws:states:::s3:getObject", "Parameters": { "Bucket": "amzn-s3-demo-bucket", "Key": "csv-dataset/ratings.csv" } }, "ItemProcessor": { Distributed mode 121 AWS Step Functions Developer Guide "ProcessorConfig": { "Mode": "DISTRIBUTED", "ExecutionType": "EXPRESS" }, "StartAt": "LambdaTask", "States": { "LambdaTask": { "Type": "Task", "Resource": "arn:aws:states:::lambda:invoke", "OutputPath": "$.Payload", "Parameters": { "Payload.$": "$", "FunctionName": "arn:aws:lambda:us-east-2:account- id:function:processCSVData" }, "End": true } } }, "Label": "Map", "End": true, "ResultWriter": { "Resource": "arn:aws:states:::s3:putObject", "Parameters": { "Bucket": "amzn-s3-demo-destination-bucket", "Prefix": "csvProcessJobs" } } } } Permissions to run Distributed Map When you include a Distributed Map state in your workflows, Step Functions needs appropriate permissions to allow the state machine role to invoke the StartExecution API action for the Distributed Map state. The following IAM policy example grants the least privileges required to your state machine role for running the Distributed Map state. Distributed mode 122 AWS Step Functions Note Developer Guide Make sure that you replace stateMachineName with the name of the state machine in which you're using the Distributed Map state. For example, arn:aws:states:region:account-id:stateMachine:mystateMachine. { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "states:StartExecution" ], "Resource": [ "arn:aws:states:region:account-id:stateMachine:stateMachineName" ] }, { "Effect": "Allow", "Action": [ "states:DescribeExecution" ], "Resource": "arn:aws:states:region:account-id:execution:stateMachineName:*" } ] } In addition, you need to make sure that you have the least privileges necessary to access the AWS resources used in the Distributed Map state, such as Amazon S3 buckets. For information, see IAM policies for using Distributed Map states. Distributed Map state fields To use the Distributed Map state in your workflows, specify one or more of these fields. You specify these fields in addition to the common state fields. Type (Required) Sets the type of state, such as Map. Distributed mode 123 AWS Step Functions ItemProcessor (Required) Developer Guide Contains
step-functions-dg-042
step-functions-dg.pdf
42
[ "states:DescribeExecution" ], "Resource": "arn:aws:states:region:account-id:execution:stateMachineName:*" } ] } In addition, you need to make sure that you have the least privileges necessary to access the AWS resources used in the Distributed Map state, such as Amazon S3 buckets. For information, see IAM policies for using Distributed Map states. Distributed Map state fields To use the Distributed Map state in your workflows, specify one or more of these fields. You specify these fields in addition to the common state fields. Type (Required) Sets the type of state, such as Map. Distributed mode 123 AWS Step Functions ItemProcessor (Required) Developer Guide Contains the following JSON objects that specify the Map state processing mode and definition. • ProcessorConfig – JSON object that specifies the mode for processing items, with the following sub-fields: • Mode – Set to DISTRIBUTED to use the Map state in Distributed mode. Warning Distributed mode is supported in Standard workflows but not supported in Express workflows. • ExecutionType – Specifies the execution type for the Map workflow as either STANDARD or EXPRESS. You must provide this field if you specified DISTRIBUTED for the Mode sub- field. For more information about workflow types, see Choosing workflow type in Step Functions. • StartAt – Specifies a string that indicates the first state in a workflow. This string is case- sensitive and must match the name of one of the state objects. This state runs first for each item in the dataset. Any execution input that you provide to the Map state passes to the StartAt state first. • States – A JSON object containing a comma-delimited set of states. In this object, you define the Map workflow. ItemReader Specifies a dataset and its location. The Map state receives its input data from the specified dataset. In Distributed mode, you can use either a JSON payload passed from a previous state or a large- scale Amazon S3 data source as the dataset. For more information, see ItemReader (Map). Items (Optional, JSONata only) A JSON array or a JSONata expression that must evaluate to an array. ItemsPath (Optional, JSONPath only) Specifies a reference path using the JsonPath syntax to select the JSON node that contains an array of items inside the state input. Distributed mode 124 AWS Step Functions Developer Guide In Distributed mode, you specify this field only when you use a JSON array from a previous step as your state input. For more information, see ItemsPath (Map, JSONPath only). ItemSelector (Optional, JSONPath only) Overrides the values of individual dataset items before they're passed on to each Map state iteration. In this field, you specify a valid JSON input that contains a collection of key-value pairs. These pairs can either be static values that you define in your state machine definition, values selected from the state input using a path, or values accessed from the context object. For more information, see ItemSelector (Map). ItemBatcher (Optional) Specifies to process the dataset items in batches. Each child workflow execution then receives a batch of these items as input. For more information, see ItemBatcher (Map). MaxConcurrency (Optional) Specifies the number of child workflow executions that can run in parallel. The interpreter only allows up to the specified number of parallel child workflow executions. If you don't specify a concurrency value or set it to zero, Step Functions doesn't limit concurrency and runs 10,000 parallel child workflow executions. In JSONata states, you can specify a JSONata expression that evaluates to an integer. Note While you can specify a higher concurrency limit for parallel child workflow executions, we recommend that you don't exceed the capacity of a downstream AWS service, such as AWS Lambda. MaxConcurrencyPath (Optional, JSONPath only) If you want to provide a maximum concurrency value dynamically from the state input using a reference path, use MaxConcurrencyPath. When resolved, the reference path must select a field whose value is a non-negative integer. Note A Map state cannot include both MaxConcurrency and MaxConcurrencyPath. Distributed mode 125 AWS Step Functions Developer Guide ToleratedFailurePercentage (Optional) Defines the percentage of failed items to tolerate in a Map Run. The Map Run automatically fails if it exceeds this percentage. Step Functions calculates the percentage of failed items as the result of the total number of failed or timed out items divided by the total number of items. You must specify a value between zero and 100. For more information, see Setting failure thresholds for Distributed Map states in Step Functions. In JSONata states, you can specify a JSONata expression that evaluates to an integer. ToleratedFailurePercentagePath (Optional, JSONPath only) If you want to provide a tolerated failure percentage value dynamically from the state input using a reference path, use ToleratedFailurePercentagePath. When resolved, the reference path must select a field whose value is between zero and 100. ToleratedFailureCount (Optional) Defines the number of
step-functions-dg-043
step-functions-dg.pdf
43
the total number of failed or timed out items divided by the total number of items. You must specify a value between zero and 100. For more information, see Setting failure thresholds for Distributed Map states in Step Functions. In JSONata states, you can specify a JSONata expression that evaluates to an integer. ToleratedFailurePercentagePath (Optional, JSONPath only) If you want to provide a tolerated failure percentage value dynamically from the state input using a reference path, use ToleratedFailurePercentagePath. When resolved, the reference path must select a field whose value is between zero and 100. ToleratedFailureCount (Optional) Defines the number of failed items to tolerate in a Map Run. The Map Run automatically fails if it exceeds this number. For more information, see Setting failure thresholds for Distributed Map states in Step Functions. In JSONata states, you can specify a JSONata expression that evaluates to an integer. ToleratedFailureCountPath (Optional, JSONPath only) If you want to provide a tolerated failure count value dynamically from the state input using a reference path, use ToleratedFailureCountPath. When resolved, the reference path must select a field whose value is a non-negative integer. Label (Optional) A string that uniquely identifies a Map state. For each Map Run, Step Functions adds the label to the Map Run ARN. The following is an example of a Map Run ARN with a custom label named demoLabel: arn:aws:states:region:account-id:mapRun:demoWorkflow/ demoLabel:3c39a231-69bb-3d89-8607-9e124eddbb0b If you don't specify a label, Step Functions automatically generates a unique label. Distributed mode 126 AWS Step Functions Note Developer Guide Labels can't exceed 40 characters in length, must be unique within a state machine definition, and can't contain any of the following characters: • Whitespace • Wildcard characters (? *) • Bracket characters (< > { } [ ]) • Special characters (: ; , \ | ^ ~ $ # % & ` ") • Control characters (\\u0000 - \\u001f or \\u007f - \\u009f). Step Functions accepts names for state machines, executions, activities, and labels that contain non-ASCII characters. Because such characters will not work with Amazon CloudWatch, we recommend using only ASCII characters so you can track metrics in CloudWatch. ResultWriter (Optional) Specifies the Amazon S3 location where Step Functions writes all child workflow execution results. Step Functions consolidates all child workflow execution data, such as execution input and output, ARN, and execution status. It then exports executions with the same status to their respective files in the specified Amazon S3 location. For more information, see ResultWriter (Map). If you don't export the Map state results, it returns an array of all the child workflow execution results. For example: [1, 2, 3, 4, 5] ResultPath (Optional, JSONPath only) Specifies where in the input to place the output of the iterations. The input is then filtered as specified by the OutputPath field if present, before it is passed as the state's output. For more information, see Input and Output Processing. Distributed mode 127 AWS Step Functions ResultSelector (Optional) Developer Guide Pass a collection of key-value pairs, where the values are static or selected from the result. For more information, see ResultSelector. Tip If the Parallel or Map state you use in your state machines returns an array of arrays, you can transform them into a flat array with the ResultSelector field. For more information, see Flattening an array of arrays. Retry (Optional) An array of objects, called Retriers, that define a retry policy. An execution uses the retry policy if the state encounters runtime errors. For more information, see State machine examples using Retry and using Catch. Note If you define Retriers for the Distributed Map state, the retry policy applies to all of the child workflow executions the Map state started. For example, imagine your Map state started three child workflow executions, out of which one fails. When the failure occurs, the execution uses the Retry field, if defined, for the Map state. The retry policy applies to all the child workflow executions and not just the failed execution. If one or more child workflow executions fails, the Map Run fails. When you retry a Map state, it creates a new Map Run. Catch (Optional) An array of objects, called Catchers, that define a fallback state. Step Functions uses the Catchers defined in Catch if the state encounters runtime errors. When an error occurs, the execution first uses any retriers defined in Retry. If the retry policy isn't defined or is exhausted, the execution uses its Catchers, if defined. For more information, see Fallback States. Output (Optional, JSONata only) Used to specify and transform output from the state. When specified, the value overrides the state output default. Distributed mode 128 AWS Step Functions Developer Guide The output field accepts any JSON value (object, array, string, number, boolean, null). Any string value, including those inside objects or arrays, will
step-functions-dg-044
step-functions-dg.pdf
44
uses the Catchers defined in Catch if the state encounters runtime errors. When an error occurs, the execution first uses any retriers defined in Retry. If the retry policy isn't defined or is exhausted, the execution uses its Catchers, if defined. For more information, see Fallback States. Output (Optional, JSONata only) Used to specify and transform output from the state. When specified, the value overrides the state output default. Distributed mode 128 AWS Step Functions Developer Guide The output field accepts any JSON value (object, array, string, number, boolean, null). Any string value, including those inside objects or arrays, will be evaluated as JSONata if surrounded by {% %} characters. Output also accepts a JSONata expression directly, for example: "Output": "{% jsonata expression %}" For more information, see the section called “Transforming data”. Assign (Optional) Used to store variables. The Assign field accepts a JSON object with key/value pairs that define variable names and their assigned values. Any string value, including those inside objects or arrays, will be evaluated as JSONata when surrounded by {% %} characters For more information, see the section called “Passing data with variables”. Setting failure thresholds for Distributed Map states in Step Functions When you orchestrate large-scale parallel workloads, you can also define a tolerated failure threshold. This value lets you specify the maximum number of, or percentage of, failed items as a failure threshold for a Map Run. Depending on which value you specify, your Map Run fails automatically if it exceeds the threshold. If you specify both values, the workflow fails when it exceeds either value. Specifying a threshold helps you fail a specific number of items before the entire Map Run fails. Step Functions returns a States.ExceedToleratedFailureThreshold error when the Map Run fails because the specified threshold is exceeded. Note Step Functions may continue to run child workflows in a Map Run even after the tolerated failure threshold is exceeded, but before the Map Run fails. To specify the threshold value in Workflow Studio, select Set a tolerated failure threshold in Additional configuration under the Runtime settings field. Distributed mode 129 AWS Step Functions Tolerated failure percentage Developer Guide Defines the percentage of failed items to tolerate. Your Map Run fails if this value is exceeded. Step Functions calculates the percentage of failed items as the result of the total number of failed or timed out items divided by the total number of items. You must specify a value between zero and 100. The default percentage value is zero, which means that the workflow fails if any one of its child workflow executions fails or times out. If you specify the percentage as 100, the workflow won’t fail even if all child workflow executions fail. Alternatively, you can specify the percentage as a reference path to an existing key-value pair in your Distributed Map state input. This path must resolve to a positive integer between 0 and 100 at runtime. You specify the reference path in the ToleratedFailurePercentagePath sub-field. For example, given the following input: { "percentage": 15 } You can specify the percentage using a reference path to that input as follows: { ... "Map": { "Type": "Map", ... "ToleratedFailurePercentagePath": "$.percentage" ... } } Important You can specify either ToleratedFailurePercentage or ToleratedFailurePercentagePath, but not both in your Distributed Map state definition. Distributed mode 130 AWS Step Functions Tolerated failure count Developer Guide Defines the number of failed items to tolerate. Your Map Run fails if this value is exceeded. Alternatively, you can specify the count as a reference path to an existing key-value pair in your Distributed Map state input. This path must resolve to a positive integer at runtime. You specify the reference path in the ToleratedFailureCountPath sub-field. For example, given the following input: { "count": 10 } You can specify the number using a reference path to that input as follows: { ... "Map": { "Type": "Map", ... "ToleratedFailureCountPath": "$.count" ... } } Important You can specify either ToleratedFailureCount or ToleratedFailureCountPath, but not both in your Distributed Map state definition. Learn more about distributed maps To continue learning more about Distributed Map state, see the following resources: • Input and output processing To configure the input that a Distributed Map state receives and the output that it generates, Step Functions provides the following fields: • ItemReader (Map) Distributed mode 131 AWS Step Functions Developer Guide • ItemsPath (Map, JSONPath only) • ItemSelector (Map) • ItemBatcher (Map) • ResultWriter (Map) • How Step Functions parses input CSV files In addition to these fields, Step Functions also provides you the ability to define a tolerated failure threshold for Distributed Map. This value lets you specify the maximum number of, or percentage of, failed items as a failure threshold for a Map Run. For more information about configuring the tolerated failure threshold,
step-functions-dg-045
step-functions-dg.pdf
45
Map state receives and the output that it generates, Step Functions provides the following fields: • ItemReader (Map) Distributed mode 131 AWS Step Functions Developer Guide • ItemsPath (Map, JSONPath only) • ItemSelector (Map) • ItemBatcher (Map) • ResultWriter (Map) • How Step Functions parses input CSV files In addition to these fields, Step Functions also provides you the ability to define a tolerated failure threshold for Distributed Map. This value lets you specify the maximum number of, or percentage of, failed items as a failure threshold for a Map Run. For more information about configuring the tolerated failure threshold, see Setting failure thresholds for Distributed Map states in Step Functions. • Using Distributed Map state Refer the following tutorials and sample projects to get started with using Distributed Map state. • Copy large-scale CSV using Distributed Map • Processing batch data with a Lambda function in Step Functions • Processing individual items with a Lambda function in Step Functions • Sample project: Process a CSV file with Distributed Map • Sample project: Process data in an Amazon S3 bucket with Distributed Map • Examine Distributed Map state execution The Step Functions console provides a Map Run Details page, which displays all the information related to a Distributed Map state execution. For information about how to examine the information displayed on this page, see Viewing Map Runs. Pass workflow state Managing state and transforming data Learn about Passing data between states with variables and Transforming data with JSONata. A Pass state ("Type": "Pass") passes its input to its output, without performing work. Pass states are useful when constructing and debugging state machines. Pass 132 AWS Step Functions Developer Guide You can also use a Pass state to transform JSON state input using filters, and then pass the transformed data to the next state in your workflows. For information about input transformation, see Manipulate parameters in Step Functions workflows. In addition to the common state fields, Pass states allow the following fields. Assign (Optional, JSONata only) A collection of key-value pairs to assign data to variables. For more information, see the section called “Passing data with variables”. Output (Optional, JSONata only) Used to specify and transform output from the state. When specified, the value overrides the state output default. The output field accepts any JSON value (object, array, string, number, boolean, null). Any string value, including those inside objects or arrays, will be evaluated as JSONata if surrounded by {% %} characters. Output also accepts a JSONata expression directly, for example: "Output": "{% jsonata expression %}" For more information, see the section called “Transforming data”. Result (Optional, JSONPath only) Refers to the output of a virtual task that is passed on to the next state. If you include the ResultPath field in your state machine definition, Result is placed as specified by ResultPath and passed on to the next state. ResultPath (Optional, JSONPath only) Specifies where to place the output (relative to the input) of the virtual task specified in Result. The input is further filtered as specified by the OutputPath field (if present) before being used as the state's output. For more information, see Processing input and output. Parameters (Optional, JSONPath only) Creates a collection of key-value pairs that will be passed as input. You can specify Parameters as a static value or select from the input using a path. For more information, see the section called “Manipulate parameters with paths”. Pass 133 AWS Step Functions Developer Guide Pass State Example (JSONPath) Here is an example of a Pass state that injects some fixed data into the state machine, probably for testing purposes. "No-op": { "Type": "Pass", "Result": { "x-datum": 0.381018, "y-datum": 622.2269926397355 }, "ResultPath": "$.coords", "End": true } Suppose the input to this state is the following. { "georefOf": "Home" } Then the output would be this. { "georefOf": "Home", "coords": { "x-datum": 0.381018, "y-datum": 622.2269926397355 } } Wait workflow state Managing state and transforming data Learn about Passing data between states with variables and Transforming data with JSONata. Pass State Example (JSONPath) 134 AWS Step Functions Developer Guide A Wait state ("Type": "Wait") delays the state machine from continuing for a specified time. You can choose either a relative time, specified in seconds from when the state begins, or an absolute end time, specified as a timestamp. In addition to the common state fields, Wait states have one of the following fields. Seconds A time, in seconds, to wait before beginning the state specified in the Next field. You must specify time as an integer value from 0 to 99999999. In JSONata states, you can alternatively specify a JSONata expression which must evaluate to an integer in the stated range. Timestamp An absolute time to wait until beginning the state specified in the Next field. Timestamps must conform
step-functions-dg-046
step-functions-dg.pdf
46
relative time, specified in seconds from when the state begins, or an absolute end time, specified as a timestamp. In addition to the common state fields, Wait states have one of the following fields. Seconds A time, in seconds, to wait before beginning the state specified in the Next field. You must specify time as an integer value from 0 to 99999999. In JSONata states, you can alternatively specify a JSONata expression which must evaluate to an integer in the stated range. Timestamp An absolute time to wait until beginning the state specified in the Next field. Timestamps must conform to the RFC3339 profile of ISO 8601, with the further restrictions that an uppercase T must separate the date and time portions, and an uppercase Z must denote that a numeric time zone offset is not present, for example, 2024-08-18T17:33:00Z. In JSONata states, you can specify a JSONata expression which results in a string that conforms to the previous requirements. Note Currently, if you specify the wait time as a timestamp, Step Functions considers the time value up to seconds and truncates milliseconds. SecondsPath (Optional, JSONPath only) A path in the states input data to an integer value that specifies the time to wait, in seconds, before proceeding to the next state. TimestampPath (Optional, JSONPath only) A path in the states input data to an absolute date and time (timestamp) to wait before proceeding to the next state. Wait 135 AWS Step Functions Note Developer Guide You must specify exactly one of Seconds, Timestamp, SecondsPath, or TimestampPath. In addition, the maximum wait time that you can specify for Standard Workflows and Express workflows is one year and five minutes respectively. Wait State Examples The following Wait state introduces a 10-second delay into a state machine. "wait_ten_seconds": { "Type": "Wait", "Seconds": 10, "Next": "NextState" } In the next example, the Wait state waits until an absolute time: March 14, 2024, at 1:59 AM UTC. "wait_until" : { "Type": "Wait", "Timestamp": "2024-03-14T01:59:00Z", "Next": "NextState" } You don't have to hard-code the wait duration. For example, given the following input data: { "expirydate": "2024-03-14T01:59:00Z" } You can select the value of "expirydate" from the input using a reference path to select it from the input data. "wait_until" : { "Type": "Wait", "TimestampPath": "$.expirydate", "Next": "NextState" } Wait State Examples 136 AWS Step Functions Developer Guide Succeed workflow state A Succeed state ("Type": "Succeed") stops an execution successfully. The Succeed state is a useful target for Choice state branches that don't do anything but stop the execution. Because Succeed states are terminal states, they have no Next field, and don't need an End field, as shown in the following example. "SuccessState": { "Type": "Succeed" } In addition to the common state fields, Succeed states that use JSONata can include an Output field. Output (Optional, JSONata only) Used to specify and transform output from the state. When specified, the value overrides the state output default. The output field accepts any JSON value (object, array, string, number, boolean, null). Any string value, including those inside objects or arrays, will be evaluated as JSONata if surrounded by {% %} characters. Output also accepts a JSONata expression directly, for example: "Output": "{% jsonata expression %}" For more information, see the section called “Transforming data”. Fail workflow state Managing state and transforming data Learn about Passing data between states with variables and Transforming data with JSONata. A Fail state ("Type": "Fail") stops the execution of the state machine and marks it as a failure, unless it is caught by a Catch block. Succeed 137 AWS Step Functions Developer Guide The Fail state only allows the use of Type and Comment fields from the set of common state fields. In addition, the Fail state allows the following fields. Cause (Optional) A custom string that describes the cause of the error. You can specify this field for operational or diagnostic purposes. In JSONata states, you can also specify a JSONata expression. CausePath (Optional, JSONPath only) If you want to provide a detailed description about the cause of the error dynamically from the state input using a reference path, use CausePath. When resolved, the reference path must select a field that contains a string value. You can also specify CausePath using an intrinsic function that returns a string. These intrinsics are: States.Format, States.JsonToString, States.ArrayGetItem, States.Base64Encode, States.Base64Decode, States.Hash, and States.UUID. Important • You can specify either Cause or CausePath, but not both in your Fail state definition. • As an information security best practice, we recommend that you remove any sensitive information or internal system details from the cause description. Error (Optional) An error name that you can provide to perform error handling using Retry or Catch fields. You can also provide an error name for operational or diagnostic purposes. In JSONata states,
step-functions-dg-047
step-functions-dg.pdf
47
a string value. You can also specify CausePath using an intrinsic function that returns a string. These intrinsics are: States.Format, States.JsonToString, States.ArrayGetItem, States.Base64Encode, States.Base64Decode, States.Hash, and States.UUID. Important • You can specify either Cause or CausePath, but not both in your Fail state definition. • As an information security best practice, we recommend that you remove any sensitive information or internal system details from the cause description. Error (Optional) An error name that you can provide to perform error handling using Retry or Catch fields. You can also provide an error name for operational or diagnostic purposes. In JSONata states, you can also specify a JSONata expression. ErrorPath (Optional, JSONPath only) If you want to provide a name for the error dynamically from the state input using a reference path, use ErrorPath. When resolved, the reference path must select a field that contains a string value. Fail 138 AWS Step Functions Developer Guide You can also specify ErrorPath using an intrinsic function that returns a string. These intrinsics are: States.Format, States.JsonToString, States.ArrayGetItem, States.Base64Encode, States.Base64Decode, States.Hash, and States.UUID. Important • You can specify either Error or ErrorPath, but not both in your Fail state definition. • As an information security best practice, we recommend that you remove any sensitive information or internal system details from the error name. Because Fail states always exit the state machine, they have no Next field and don't require an End field. Fail state definition examples The following Fail state definition example specifies static Error and Cause field values. "FailState": { "Type": "Fail", "Cause": "Invalid response.", "Error": "ErrorA" } The following Fail state definition example uses reference paths dynamically to resolve the Error and Cause field values. "FailState": { "Type": "Fail", "CausePath": "$.Cause", "ErrorPath": "$.Error" } The following Fail state definition example uses the States.Format intrinsic function to specify the Error and Cause field values dynamically. "FailState": { "Type": "Fail", "CausePath": "States.Format('This is a custom error message for {}, caused by {}.', $.Error, $.Cause)", Fail state definition examples 139 AWS Step Functions Developer Guide "ErrorPath": "States.Format('{}', $.Error)" } Fail state definition examples 140 AWS Step Functions Developer Guide Tutorials and workshops for learning Step Functions Learn from this guide, workshops, and practical tutorials how to integrate and orchestrate services with Step Functions. 141 AWS Step Functions Developer Guide Tutorials for learning Step Functions For an introduction to Step Functions, see Getting started tutorial. Tutorials 142 AWS Step Functions Developer Guide For specific scenarios, see the following tutorials: • the section called “Create a state machine using AWS SAM” • the section called “Create a state machine with CloudFormation” • the section called “Using CDK to create an Express workflow” • the section called “Using CDK to create a Standard workflow” • the section called “Examine executions” • the section called “Create a state machine that uses Lambda” • the section called “Wait for human approval” • the section called “Repeat actions with Inline Map” • the section called “Copy large-scale CSV using Distributed Map” • the section called “Iterate a loop with Lambda” • the section called “Process batch data with Lambda” • the section called “Process individual items with Lambda” • the section called “Start a workflow from EventBridge” • the section called “Create an API using API Gateway” • the section called “Handle error conditions” • the section called “Create an Activity state machine” • the section called “View X-Ray traces” • the section called “Gather Amazon S3 bucket info” • the section called “Continue long-running workflows using Step Functions API (recommended)” • the section called “Using Lambda to continue a workflow” • the section called “Access cross-account resources” Learn with starter templates To deploy and learn from ready-to-run state machines for a variety of use cases, see Starter templates. Tutorials 143 AWS Step Functions Developer Guide Create a Step Functions state machine using AWS SAM In this guide, you download, build, and deploy a sample AWS SAM application that contains an AWS Step Functions state machine. This application creates a mock stock trading workflow which runs on a pre-defined schedule (note that the schedule is disabled by default to avoid incurring charges). The following diagram shows the components of this application: The following is a preview of commands that you run to create your sample application. For more details about each of these commands, see the sections later in this page # Step 1 - Download a sample application. For this tutorial you # will follow the prompts to select an AWS Quick Start Template # called 'Multi-step workflow' sam init # Step 2 - Build your application cd project-directory sam build # Step 3 - Deploy your application sam deploy --guided Prerequisites This guide assumes that you've completed the steps in the Installing the AWS SAM CLI for your OS. It assumes
step-functions-dg-048
step-functions-dg.pdf
48
is a preview of commands that you run to create your sample application. For more details about each of these commands, see the sections later in this page # Step 1 - Download a sample application. For this tutorial you # will follow the prompts to select an AWS Quick Start Template # called 'Multi-step workflow' sam init # Step 2 - Build your application cd project-directory sam build # Step 3 - Deploy your application sam deploy --guided Prerequisites This guide assumes that you've completed the steps in the Installing the AWS SAM CLI for your OS. It assumes that you've done the following: 1. Created an AWS account. Create a state machine using AWS SAM 144 AWS Step Functions 2. Configured IAM permissions. Developer Guide 3. Installed Homebrew. Note: Homebrew is only a prerequisite for Linux and macOS. 4. Installed the AWS SAM CLI. Note: Make sure you have version 0.52.0 or later. You can check which version you have by executing the command sam --version. Step 1: Download a Sample AWS SAM Application Command to run: sam init Follow the on-screen prompts to select the following: 1. Template: AWS Quick Start Templates 2. Language: Python, Ruby, NodeJS, Go, Java, or .NET 3. Project name: (name of your choice - default is sam-app) 4. Quick start application: Multi-step workflow What AWS SAM is doing: This command creates a directory with the name you provided for the 'Project name' prompt (default is sam-app). The specific contents of the directory will depend on the language you choose. Following are the directory contents when you choose one of the Python runtimes: ### README.md ### functions # ### __init__.py # ### stock_buyer # # ### __init__.py # # ### app.py # # ### requirements.txt # ### stock_checker # # ### __init__.py # # ### app.py # # ### requirements.txt # ### stock_seller Step 1: Download a Sample AWS SAM Application 145 AWS Step Functions Developer Guide # ### __init__.py # ### app.py # ### requirements.txt ### statemachine # ### stock_trader.asl.json ### template.yaml ### tests ### unit ### __init__.py ### test_buyer.py ### test_checker.py ### test_seller.py There are two especially interesting files that you can take a look at: • template.yaml: Contains the AWS SAM template that defines your application's AWS resources. • statemachine/stockTrader.asl.json: Contains the application's state machine definition, which is written in Using Amazon States Language to define Step Functions workflows. You can see the following entry in the template.yaml file, which points to the state machine definition file: Properties: DefinitionUri: statemachine/stock_trader.asl.json It can be helpful to keep the state machine definition as a separate file instead of embedding it in the AWS SAM template. For example, tracking changes to the state machine definition is easier if you don't include the definition in the template. You can use the Workflow Studio to create and maintain the state machine definition, and export the definition from the console directly to the Amazon States Language specification file without merging it into the template. For more information about the sample application, see the README.md file in the project directory. Step 2: Build Your Application Command to run: Step 2: Build Your Application 146 AWS Step Functions Developer Guide First change into the project directory (that is, the directory where the template.yaml file for the sample application is located; by default is sam-app), then run this command: sam build Example output: Build Succeeded Built Artifacts : .aws-sam/build Built Template : .aws-sam/build/template.yaml Commands you can use next ========================= [*] Invoke Function: sam local invoke [*] Deploy: sam deploy --guided What AWS SAM is doing: The AWS SAM CLI comes with abstractions for a number of Lambda runtimes to build your dependencies, and copies all build artifacts into staging folders so that everything is ready to be packaged and deployed. The sam build command builds any dependencies that your application has, and copies the build artifacts to folders under .aws-sam/build. Step 3: Deploy Your Application to the AWS Cloud Command to run: sam deploy --guided Follow the on-screen prompts. You can just respond with Enter to accept the default options provided in the interactive experience. What AWS SAM is doing: This command deploys your application to the AWS cloud. It take the deployment artifacts you build with the sam build command, packages and uploads them to an Amazon S3 bucket created Step 3: Deploy Your Application to the AWS Cloud 147 AWS Step Functions Developer Guide by AWS SAM CLI, and deploys the application using AWS CloudFormation. In the output of the deploy command you can see the changes being made to your AWS CloudFormation stack. You can verify the example Step Functions state machine was successfully deployed by following these steps: 1. Sign in to the AWS Management Console and open the Step Functions console at https:// 2.
step-functions-dg-049
step-functions-dg.pdf
49
It take the deployment artifacts you build with the sam build command, packages and uploads them to an Amazon S3 bucket created Step 3: Deploy Your Application to the AWS Cloud 147 AWS Step Functions Developer Guide by AWS SAM CLI, and deploys the application using AWS CloudFormation. In the output of the deploy command you can see the changes being made to your AWS CloudFormation stack. You can verify the example Step Functions state machine was successfully deployed by following these steps: 1. Sign in to the AWS Management Console and open the Step Functions console at https:// 2. 3. console.aws.amazon.com/states/. In the left navigation, choose State machines. Find and choose your new state machine in the list. It will be named StockTradingStateMachine-<unique-hash>. 4. Choose the Definition tab. You should now see a visual representation of your state machine. You can verify that the visual representation matches the state machine definition found in the statemachine/ stockTrader.asl.json file of your project directory. Troubleshooting SAM CLI error: "no such option: --guided" When executing sam deploy, you see the following error: Error: no such option: --guided This means that you are using an older version of the AWS SAM CLI that does not support the -- guided parameter. To fix this, you can either update your version of AWS SAM CLI to 0.33.0 or later, or omit the --guided parameter from the sam deploy command. SAM CLI error: "Failed to create managed resources: Unable to locate credentials" When executing sam deploy, you see the following error: Error: Failed to create managed resources: Unable to locate credentials Troubleshooting 148 AWS Step Functions Developer Guide This means that you have not set up AWS credentials to enable the AWS SAM CLI to make AWS service calls. To fix this, you must set up AWS credentials. For more information, see Setting Up AWS Credentials in the AWS Serverless Application Model Developer Guide. Clean Up If you no longer need the AWS resources you created by running this tutorial, you can remove them by deleting the AWS CloudFormation stack that you deployed. To delete the AWS CloudFormation stack created with this tutorial using the AWS Management Console, follow these steps: 1. Sign in to the AWS Management Console and open the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation. In the left navigation pane, choose Stacks. In the list of stacks, choose sam-app (or the name of stack you created). 2. 3. 4. Choose Delete. When done, the status of the of the stack will change to DELETE_COMPLETE. Alternatively, you can delete the AWS CloudFormation stack by executing the following AWS CLI command: aws cloudformation delete-stack --stack-name sam-app --region region Verify Deleted Stack For both methods of deleting the AWS CloudFormation stack, you can verify it was deleted by going to the https://console.aws.amazon.com/cloudformation, choosing Stacks in the left navigation pane, and choosing Deleted in the dropdown to the right of the search text box. You should see your stack name sam-app (or the name of the stack you created) in the list of deleted stacks. Examining state machine executions in Step Functions In this tutorial, you will learn how to inspect the execution information displayed on the Execution Details page and view the reason for a failed execution. Then, you'll learn how to access different Clean Up 149 AWS Step Functions Developer Guide iterations of a Map state execution. Finally, you'll learn how to configure the columns on the Table view and apply suitable filters to view only the information of interest to you. In this tutorial, you create a Standard type state machine, which obtains the price of a set of fruits. To do this, the state machine uses three AWS Lambda functions which return a random list of four fruits, the price of each fruit, and the average cost of the fruits. The Lambda functions are designed to throw an error if the price of the fruits is less than or equal to a threshold value. Note While the following procedure contains instructions for how to examine the details of a Standard workflow execution, you can also examine the details for Express workflow executions. For information about the differences between the execution details for Standard and Express workflow types, see Standard and Express console experience differences. Step 1: Create and test the required Lambda functions 1. Open the Lambda console and then perform steps 1 through 4 in the Step 1: Create a Lambda function section. Make sure to name the Lambda function GetListOfFruits. 2. After you create your Lambda function, copy the function's Amazon Resource Name (ARN) displayed in the upper-right corner of the page. To copy the ARN, click the copy icon to copy the Lambda function's Amazon Resource Name. The following is an example ARN, where function-name is the name of the Lambda function
step-functions-dg-050
step-functions-dg.pdf
50
workflow types, see Standard and Express console experience differences. Step 1: Create and test the required Lambda functions 1. Open the Lambda console and then perform steps 1 through 4 in the Step 1: Create a Lambda function section. Make sure to name the Lambda function GetListOfFruits. 2. After you create your Lambda function, copy the function's Amazon Resource Name (ARN) displayed in the upper-right corner of the page. To copy the ARN, click the copy icon to copy the Lambda function's Amazon Resource Name. The following is an example ARN, where function-name is the name of the Lambda function (in this case, GetListOfFruits): arn:aws:lambda:region:123456789012:function:function-name 3. Copy the following code for the Lambda function into the Code source area of the GetListOfFruits page. function getRandomSubarray(arr, size) { var shuffled = arr.slice(0), i = arr.length, temp, index; while (i--) { index = Math.floor((i + 1) * Math.random()); temp = shuffled[index]; shuffled[index] = shuffled[i]; shuffled[i] = temp; } Step 1: Create and test the required Lambda functions 150 AWS Step Functions Developer Guide return shuffled.slice(0, size); } exports.handler = async function(event, context) { const fruits = ['Abiu','Açaí','Acerola','Ackee','African cucumber','Apple','Apricot','Avocado','Banana','Bilberry','Blackberry','Blackcurrant','Jostaberry']; const errorChance = 45; const waitTime = Math.floor( 100 * Math.random() ); await new Promise( r => setTimeout(() => r(), waitTime)); const num = Math.floor( 100 * Math.random() ); // const num = 51; if (num <= errorChance) { throw(new Error('Error')); } return getRandomSubarray(fruits, 4); }; 4. Choose Deploy, and then choose Test, to deploy the changes and see the output of your Lambda function. 5. Create two additional Lambda functions, named GetFruitPrice and CalculateAverage respectively, with the following steps: a. Copy the following code into the Code source area of the GetFruitPrice Lambda function: exports.handler = async function(event, context) { const errorChance = 0; const waitTime = Math.floor( 100 * Math.random() ); await new Promise( r => setTimeout(() => r(), waitTime)); const num = Math.floor( 100 * Math.random() ); if (num <= errorChance) { throw(new Error('Error')); } Step 1: Create and test the required Lambda functions 151 AWS Step Functions Developer Guide return Math.floor(Math.random()*100)/10; }; b. Copy the following code into the Code source area of the CalculateAverage Lambda function: function getRandomSubarray(arr, size) { var shuffled = arr.slice(0), i = arr.length, temp, index; while (i--) { index = Math.floor((i + 1) * Math.random()); temp = shuffled[index]; shuffled[index] = shuffled[i]; shuffled[i] = temp; } return shuffled.slice(0, size); } const average = arr => arr.reduce( ( p, c ) => p + c, 0 ) / arr.length; exports.handler = async function(event, context) { const errors = [ "Error getting data from DynamoDB", "Error connecting to DynamoDB", "Network error", "MemoryError - Low memory" ] const errorChance = 0; const waitTime = Math.floor( 100 * Math.random() ); await new Promise( r => setTimeout(() => r(), waitTime)); const num = Math.floor( 100 * Math.random() ); if (num <= errorChance) { throw(new Error(getRandomSubarray(errors, 1)[0])); } return average(event); }; c. Make sure to copy the ARNs of these two Lambda functions, and then Deploy and Test them. Step 1: Create and test the required Lambda functions 152 AWS Step Functions Developer Guide Step 2: Create and execute the state machine Use the Step Functions console to create a state machine that invokes the Lambda functions you created in Step 1. In this state machine, three Map states are defined. Each of these Map states contains a Task state that invokes one of your Lambda functions. Additionally, a Retry field is defined in each Task state with a number of retry attempts defined for each state. If a Task state encounters a runtime error, it's executed again up to the number of retry attempts defined for that Task. 1. Open the Step Functions console and choose Write your workflow in code. Important Ensure that your state machine is under the same AWS account and Region as the Lambda function you created earlier. 2. For Type, keep the default selection of Standard. 3. Copy the following Amazon States Language definition and paste it under Definition. Make sure to replace the ARNs shown with those of the Lambda functions that you previously created. { "StartAt": "LoopOverStores", "States": { "LoopOverStores": { "Type": "Map", "Iterator": { "StartAt": "GetListOfFruits", "States": { "GetListOfFruits": { "Type": "Task", "Resource": "arn:aws:states:::lambda:invoke", "OutputPath": "$.Payload", "Parameters": { "FunctionName": "arn:aws:lambda:region:123456789012:function:GetListofFruits:$LATEST", "Payload": { "storeName.$": "$" } }, Step 2: Create and execute the state machine 153 AWS Step Functions Developer Guide "Retry": [ { "ErrorEquals": [ "States.ALL" ], "IntervalSeconds": 2, "MaxAttempts": 1, "BackoffRate": 1.3 } ], "Next": "LoopOverFruits" }, "LoopOverFruits": { "Type": "Map", "Iterator": { "StartAt": "GetFruitPrice", "States": { "GetFruitPrice": { "Type": "Task", "Resource": "arn:aws:states:::lambda:invoke", "OutputPath": "$.Payload", "Parameters": { "FunctionName": "arn:aws:lambda:region:123456789012:function:GetFruitPrice:$LATEST", "Payload": { "fruitName.$": "$" } }, "Retry": [ { "ErrorEquals": [ "States.ALL" ], "IntervalSeconds": 2, "MaxAttempts": 3, "BackoffRate": 1.3 } ], "End": true } } }, "ItemsPath": "$", "End": true Step 2: Create
step-functions-dg-051
step-functions-dg.pdf
51
"arn:aws:states:::lambda:invoke", "OutputPath": "$.Payload", "Parameters": { "FunctionName": "arn:aws:lambda:region:123456789012:function:GetListofFruits:$LATEST", "Payload": { "storeName.$": "$" } }, Step 2: Create and execute the state machine 153 AWS Step Functions Developer Guide "Retry": [ { "ErrorEquals": [ "States.ALL" ], "IntervalSeconds": 2, "MaxAttempts": 1, "BackoffRate": 1.3 } ], "Next": "LoopOverFruits" }, "LoopOverFruits": { "Type": "Map", "Iterator": { "StartAt": "GetFruitPrice", "States": { "GetFruitPrice": { "Type": "Task", "Resource": "arn:aws:states:::lambda:invoke", "OutputPath": "$.Payload", "Parameters": { "FunctionName": "arn:aws:lambda:region:123456789012:function:GetFruitPrice:$LATEST", "Payload": { "fruitName.$": "$" } }, "Retry": [ { "ErrorEquals": [ "States.ALL" ], "IntervalSeconds": 2, "MaxAttempts": 3, "BackoffRate": 1.3 } ], "End": true } } }, "ItemsPath": "$", "End": true Step 2: Create and execute the state machine 154 AWS Step Functions Developer Guide } } }, "ItemsPath": "$.stores", "Next": "LoopOverStoreFruitsPrice", "ResultPath": "$.storesFruitsPrice" }, "LoopOverStoreFruitsPrice": { "Type": "Map", "End": true, "Iterator": { "StartAt": "CalculateAverage", "States": { "CalculateAverage": { "Type": "Task", "Resource": "arn:aws:states:::lambda:invoke", "OutputPath": "$.Payload", "Parameters": { "FunctionName": "arn:aws:lambda:region:123456789012:function:Calculate-average:$LATEST", "Payload.$": "$" }, "Retry": [ { "ErrorEquals": [ "States.ALL" ], "IntervalSeconds": 2, "MaxAttempts": 2, "BackoffRate": 1.3 } ], "End": true } } }, "ItemsPath": "$.storesFruitsPrice", "ResultPath": "$.storesPriceAverage", "MaxConcurrency": 1 } } } Step 2: Create and execute the state machine 155 AWS Step Functions Developer Guide 4. Enter a name for your state machine. Keep the default selections for the other options on this page and choose Create state machine. 5. Open the page titled with your state machine name. Perform steps 1 through 4 in the Step 4: Run the state machine section, but use the following data as the execution input: { "stores": [ "Store A", "Store B", "Store C", "Store D" ] } Step 3: View the state machine execution details On the page titled with your execution ID, you can review the results of your execution and debug any errors. 1. (Optional) Choose from the tabs displayed on the Execution Details page to see the information present in each of them. For example, to view the state machine input and its execution output, choose Execution input & output on the Execution summary section. 2. If your state machine execution failed, choose Cause or Show step detail on the error message. Details about the error are displayed in the Step details section. Notice that the step that caused the error, which is a Task state named GetListofFruits, is highlighted in the Graph view and Table view. Note Because the GetListofFruits step is defined inside a Map state, and the step failed to execute successfully, the Status of Map state step is displayed as Failed. Step 4: Explore the different View modes You can choose a preferred mode to view either the state machine workflow or the execution event history. Some of the tasks that you can perform in these View modes are as follows: Step 3: View the state machine execution details 156 AWS Step Functions Developer Guide Graph view – Switch between different Map state iterations If your Map state has five iterations and you want to view the execution details for the third and fourth iterations, do the following: 1. Choose the Map state that you want to view the iteration data for. 2. From Map iteration viewer, choose the iteration that you want to view. Iterations are counted from zero. To choose the third iteration out of five, choose #2 from the dropdown list next to the Map state's name. Note If your state machine contains nested Map states, Step Functions displays the parent and child Map state iterations as two separate dropdown lists representing the iteration data for the nested states. 3. (Optional) If one or more of your Map state iterations failed to execute or was stopped in an aborted state, you can view details about the failed iteration. To see these details, choose the affected iteration numbers under Failed or Aborted in the dropdown list. Table view – Switch between different Map state iterations If your Map state has five iterations and you want to view the execution details for the iteration number three and four, do the following: 1. Choose the Map state for which you want to view the different iteration data. 2. In the tree view display of the Map state iterations, choose the row for iteration named #2 for iteration number three. Similarly, choose the row named #3 for iteration number four. Table view – Configure the columns to display Choose the settings icon. Then, in the Preferences dialog box, choose the columns you want to display under Select visible columns. By default, this mode displays the Name, Type, Status, Resource, and Started After columns. Step 4: Explore the different View modes 157 AWS Step Functions Table view – Filter the results Developer Guide Limit the amount of information displayed by applying one or more filters based on a property, such as Status, or a date and time range. For example, to
step-functions-dg-052
step-functions-dg.pdf
52
Similarly, choose the row named #3 for iteration number four. Table view – Configure the columns to display Choose the settings icon. Then, in the Preferences dialog box, choose the columns you want to display under Select visible columns. By default, this mode displays the Name, Type, Status, Resource, and Started After columns. Step 4: Explore the different View modes 157 AWS Step Functions Table view – Filter the results Developer Guide Limit the amount of information displayed by applying one or more filters based on a property, such as Status, or a date and time range. For example, to view the steps that failed execution, apply the following filter: 1. Choose Filter by properties or search by keyword, and then choose Status under Properties. 2. Under Operators, choose Status =. 3. Choose Status = Failed. 4. (Optional) Choose Clear filters to remove the applied filters. Event view – Filter the results Limit the amount of information displayed by applying one or more filters based on a property, such as Type, or a date and time range. For example, to view the Task state steps that failed execution, apply the following filter: 1. Choose Filter by properties or search by keyword, and then choose Type under Properties. 2. Under Operators, choose Type =. 3. Choose Type = TaskFailed. 4. (Optional) Choose Clear filters to remove the applied filters. Event view – Inspect a TaskFailed event detail Choose the arrow icon next to the ID of a TaskFailed event to inspect its details, including input, output, and resource invocation that appear in a dropdown box. Creating a Step Functions state machine that uses Lambda In this tutorial, you will create a single-step workflow using AWS Step Functions to invoke an AWS Lambda function. Note Step Functions is based on state machines and tasks. In Step Functions, state machines are called workflows, which are a series of event-driven steps. Each step in a workflow is called a state. For example, a Task state represents a unit of work that another AWS service Create a state machine that uses Lambda 158 AWS Step Functions Developer Guide performs, such as calling another AWS service or API. Instances of running workflows performing tasks are called executions in Step Functions. For more information, see: • What is Step Functions? • Call other AWS services Lambda is well-suited for Task states, because Lambda functions are serverless and easy to write. You can write code in the AWS Management Console or your favorite editor. AWS handles the details of providing a computing environment for your function and running it. Step 1: Create a Lambda function Your Lambda function receives event data and returns a greeting message. Important Ensure that your Lambda function is under the same AWS account and AWS Region as your state machine. 1. Open the Lambda console and choose Create function. 2. On the Create function page, choose Author from scratch. 3. For Function name, enter HelloFunction. 4. Keep the default selections for all other options, and then choose Create function. 5. After your Lambda function is created, copy the function's Amazon Resource Name (ARN) displayed in the upper-right corner of the page. The following is an example ARN: arn:aws:lambda:region:123456789012:function:HelloFunction 6. Copy the following code for the Lambda function into the Code source section of the HelloFunction page. export const handler = async(event, context, callback) => { callback(null, "Hello from " + event.who + "!"); }; Step 1: Create a Lambda function 159 AWS Step Functions Developer Guide This code assembles a greeting using the who field of the input data, which is provided by the event object passed into your function. You add input data for this function later, when you start a new execution. The callback method returns the assembled greeting from your function. 7. Choose Deploy. Step 2: Test the Lambda function Test your Lambda function to see it in operation. 1. Choose Test. 2. For Event name, enter HelloEvent. 3. Replace the Event JSON data with the following. { "who": "AWS Step Functions" } The "who" entry corresponds to the event.who field in your Lambda function, completing the greeting. You will input the same input data when you run your state machine. 4. Choose Save and then choose Test. 5. To review the test results, under Execution result, expand Details. Step 3: Create a state machine Use the Step Functions console to create a state machine that invokes the Lambda function that you created in Step 1. 1. Open the Step Functions console and choose Create state machine. Important Make sure that your state machine is under the same AWS account and Region as the Lambda function you created earlier. 2. In the Choose a template dialog box, select Blank. Step 2: Test the Lambda function 160 AWS Step Functions Developer
step-functions-dg-053
step-functions-dg.pdf
53
machine. 4. Choose Save and then choose Test. 5. To review the test results, under Execution result, expand Details. Step 3: Create a state machine Use the Step Functions console to create a state machine that invokes the Lambda function that you created in Step 1. 1. Open the Step Functions console and choose Create state machine. Important Make sure that your state machine is under the same AWS account and Region as the Lambda function you created earlier. 2. In the Choose a template dialog box, select Blank. Step 2: Test the Lambda function 160 AWS Step Functions Developer Guide 3. Choose Select to open Workflow Studio in Design mode. 4. In the States browser on the left, make sure you've chosen the Actions tab. Then, drag and drop the AWS Lambda Invoke API into the empty state labelled Drag first state here. 5. In the Inspector panel on the right, configure the Lambda function: a. In the API Parameters section, choose the Lambda function that you created earlier in the Function name dropdown list. b. Keep the default selection in the Payload dropdown list. 6. 7. (Optional) Choose Definition to view the state machine's Amazon States Language (ASL) definition, which is automatically generated based on your selections in the Actions tab and Inspector panel. Specify a name for your state machine. To do this, choose the edit icon next to the default state machine name of MyStateMachine. Then, in State machine configuration, specify a name in the State machine name box. For example, enter the name LambdaStateMachine. Note Names of state machines, executions, and activity tasks must not exceed 80 characters in length. These names must be unique for your account and AWS Region, and must not contain any of the following: • Whitespace • Wildcard characters (? *) • Bracket characters (< > { } [ ]) • Special characters (" # % \ ^ | ~ ` $ & , ; : /) • Control characters (\\u0000 - \\u001f or \\u007f - \\u009f). Step Functions accepts names for state machines, executions, activities, and labels that contain non-ASCII characters. Because such characters will not work with Amazon CloudWatch, we recommend using only ASCII characters so you can track metrics in CloudWatch. 8. (Optional) In State machine configuration, specify other workflow settings, such as state machine type and its execution role. Step 3: Create a state machine 161 AWS Step Functions Developer Guide For this tutorial, keep all the default selections in State machine settings. 9. Choose Create. 10. In the Confirm role creation dialog box, choose Confirm to continue. You can also choose View role settings to go back to State machine configuration. Note If you delete the IAM role that Step Functions creates, Step Functions can't recreate it later. Similarly, if you modify the role (for example, by removing Step Functions from the principals in the IAM policy), Step Functions can't restore its original settings later. Step 4: Run the state machine After you create your state machine, you can run it. 1. On the State machines page, choose LambdaStateMachine. 2. Choose Start execution. The Start execution dialog box is displayed. 3. (Optional) Enter a custom execution name to override the generated default. Non-ASCII names and logging Step Functions accepts names for state machines, executions, activities, and labels that contain non-ASCII characters. Because such characters will not work with Amazon CloudWatch, we recommend using only ASCII characters so you can track metrics in CloudWatch. 4. In the Input area, replace the example execution data with the following. { "who" : "AWS Step Functions" } "who" is the key name that your Lambda function uses to get the name of the person to greet. Step 4: Run the state machine 162 AWS Step Functions 5. Choose Start Execution. Developer Guide Your state machine's execution starts, and a new page showing your running execution is displayed. 6. The Step Functions console directs you to a page that's titled with your execution ID. This page is known as the Execution Details page. On this page, you can review the execution results as the execution progresses or after it's complete. To review the execution results, choose individual states on the Graph view, and then choose the individual tabs on the Step details pane to view each state's details including input, output, and definition respectively. For details about the execution information you can view on the Execution Details page, see Execution details overview. Note You can also pass payloads while invoking Lambda from a state machine. For more information and examples about invoking Lambda by passing payload in the Parameters field, see Invoke an AWS Lambda function with Step Functions. Deploying a workflow that waits for human approval in Step Functions This tutorial shows you how to deploy a human approval
step-functions-dg-054
step-functions-dg.pdf
54
Graph view, and then choose the individual tabs on the Step details pane to view each state's details including input, output, and definition respectively. For details about the execution information you can view on the Execution Details page, see Execution details overview. Note You can also pass payloads while invoking Lambda from a state machine. For more information and examples about invoking Lambda by passing payload in the Parameters field, see Invoke an AWS Lambda function with Step Functions. Deploying a workflow that waits for human approval in Step Functions This tutorial shows you how to deploy a human approval project that allows an AWS Step Functions execution to pause during a task, and wait for a user to respond to an email. The workflow progresses to the next state once the user has approved the task to proceed. Deploying the AWS CloudFormation stack included in this tutorial will create all necessary resources, including: • Amazon API Gateway resources • An AWS Lambda functions • An AWS Step Functions state machine • An Amazon Simple Notification Service email topic • Related AWS Identity and Access Management roles and permissions Wait for human approval 163 AWS Step Functions Note Developer Guide You will need to provide a valid email address that you have access to when you create the AWS CloudFormation stack. For more information, see Working with CloudFormation Templates and the AWS::StepFunctions::StateMachine resource in the AWS CloudFormation User Guide. Step 1: Create an AWS CloudFormation template 1. Copy the example code from the AWS CloudFormation Template Source Code section. 2. Paste the source of the AWS CloudFormation template into a file on your local machine. For this example the file is called human-approval.yaml. Step 2: Create a stack 1. Log into the AWS CloudFormation console. 2. Choose Create Stack, and then choose With new resources (standard). 3. On the Create stack page, do the following: a. b. In the Prerequisite - Prepare template section, make sure Template is ready is selected. In the Specify template section, choose Upload a template file and then choose Choose file to upload the human-approval.yaml file you created earlier that includes the template source code. 4. Choose Next. 5. On the Specify stack details page, do the following: a. For Stack name, enter a name for your stack. b. Under Parameters, enter a valid email address. You'll use this email address to subscribe to the Amazon SNS topic. 6. Choose Next, and then choose Next again. 7. On the Review page, choose I acknowledge that AWS CloudFormation might create IAM resources and then choose Create. Step 1: Create a Template 164 AWS Step Functions Developer Guide AWS CloudFormation begins to create your stack and displays the CREATE_IN_PROGRESS status. When the process is complete, AWS CloudFormation displays the CREATE_COMPLETE status. 8. (Optional) To display the resources in your stack, select the stack and choose the Resources tab. Step 3: Approve the Amazon SNS subscription Once the Amazon SNS topic is created, you will receive an email requesting that you confirm subscription. 1. Open the email account you provided when you created the AWS CloudFormation stack. 2. Open the message AWS Notification - Subscription Confirmation from no- [email protected] The email will list the Amazon Resource Name for the Amazon SNS topic, and a confirmation link. 3. Choose the confirm subscription link. Step 4: Run the state machine 1. On the HumanApprovalLambdaStateMachine page, choose Start execution. Step 3: Approve the SNS subscription 165 AWS Step Functions Developer Guide The Start execution dialog box is displayed. 2. In the Start execution dialog box, do the following: a. (Optional) Enter a custom execution name to override the generated default. Non-ASCII names and logging Step Functions accepts names for state machines, executions, activities, and labels that contain non-ASCII characters. Because such characters will not work with Amazon CloudWatch, we recommend using only ASCII characters so you can track metrics in CloudWatch. b. In the Input box, enter the following JSON input to run your workflow. { "Comment": "Testing the human approval tutorial." } c. Choose Start execution. The ApprovalTest state machine execution starts, and pauses at the Lambda Callback task. d. The Step Functions console directs you to a page that's titled with your execution ID. This page is known as the Execution Details page. On this page, you can review the execution results as the execution progresses or after it's complete. To review the execution results, choose individual states on the Graph view, and then choose the individual tabs on the Step details pane to view each state's details including input, output, and definition respectively. For details about the execution information you can view on the Execution Details page, see Execution details overview. Step 4: Run the state machine 166 AWS Step Functions Developer Guide 3. In the email account
step-functions-dg-055
step-functions-dg.pdf
55
titled with your execution ID. This page is known as the Execution Details page. On this page, you can review the execution results as the execution progresses or after it's complete. To review the execution results, choose individual states on the Graph view, and then choose the individual tabs on the Step details pane to view each state's details including input, output, and definition respectively. For details about the execution information you can view on the Execution Details page, see Execution details overview. Step 4: Run the state machine 166 AWS Step Functions Developer Guide 3. In the email account you used for the Amazon SNS topic earlier, open the message with the subject Required approval from AWS Step Functions. The message includes separate URLs for Approve and Reject. 4. Choose the Approve URL. The workflow continues based on your choice. Step 4: Run the state machine 167 AWS Step Functions Developer Guide AWS CloudFormation Template Source Code Use this AWS CloudFormation template to deploy an example of a human approval process workflow. AWSTemplateFormatVersion: "2010-09-09" Description: "AWS Step Functions Human based task example. It sends an email with an HTTP URL for approval." Parameters: Email: Type: String AllowedPattern: "^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$" ConstraintDescription: Must be a valid email address. Resources: # Begin API Gateway Resources ExecutionApi: Type: "AWS::ApiGateway::RestApi" Properties: Name: "Human approval endpoint" Description: "HTTP Endpoint backed by API Gateway and Lambda" FailOnWarnings: true ExecutionResource: Template Source Code 168 AWS Step Functions Developer Guide Type: 'AWS::ApiGateway::Resource' Properties: RestApiId: !Ref ExecutionApi ParentId: !GetAtt "ExecutionApi.RootResourceId" PathPart: execution ExecutionMethod: Type: "AWS::ApiGateway::Method" Properties: AuthorizationType: NONE HttpMethod: GET Integration: Type: AWS IntegrationHttpMethod: POST Uri: !Sub "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/ ${LambdaApprovalFunction.Arn}/invocations" IntegrationResponses: - StatusCode: 302 ResponseParameters: method.response.header.Location: "integration.response.body.headers.Location" RequestTemplates: application/json: | { "body" : $input.json('$'), "headers": { #foreach($header in $input.params().header.keySet()) "$header": "$util.escapeJavaScript($input.params().header.get($header))" #if($foreach.hasNext),#end #end }, "method": "$context.httpMethod", "params": { #foreach($param in $input.params().path.keySet()) "$param": "$util.escapeJavaScript($input.params().path.get($param))" #if($foreach.hasNext),#end #end }, "query": { #foreach($queryParam in $input.params().querystring.keySet()) Template Source Code 169 AWS Step Functions Developer Guide "$queryParam": "$util.escapeJavaScript($input.params().querystring.get($queryParam))" #if($foreach.hasNext),#end #end } } ResourceId: !Ref ExecutionResource RestApiId: !Ref ExecutionApi MethodResponses: - StatusCode: 302 ResponseParameters: method.response.header.Location: true ApiGatewayAccount: Type: 'AWS::ApiGateway::Account' Properties: CloudWatchRoleArn: !GetAtt "ApiGatewayCloudWatchLogsRole.Arn" ApiGatewayCloudWatchLogsRole: Type: 'AWS::IAM::Role' Properties: AssumeRolePolicyDocument: Version: "2012-10-17" Statement: - Effect: Allow Principal: Service: - apigateway.amazonaws.com Action: - 'sts:AssumeRole' Policies: - PolicyName: ApiGatewayLogsPolicy PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - "logs:*" Resource: !Sub "arn:${AWS::Partition}:logs:*:*:*" ExecutionApiStage: DependsOn: - ApiGatewayAccount Template Source Code 170 AWS Step Functions Developer Guide Type: 'AWS::ApiGateway::Stage' Properties: DeploymentId: !Ref ApiDeployment MethodSettings: - DataTraceEnabled: true HttpMethod: '*' LoggingLevel: INFO ResourcePath: /* RestApiId: !Ref ExecutionApi StageName: states ApiDeployment: Type: "AWS::ApiGateway::Deployment" DependsOn: - ExecutionMethod Properties: RestApiId: !Ref ExecutionApi StageName: DummyStage # End API Gateway Resources # Begin # Lambda that will be invoked by API Gateway LambdaApprovalFunction: Type: 'AWS::Lambda::Function' Properties: Code: ZipFile: Fn::Sub: | const { SFN: StepFunctions } = require("@aws-sdk/client-sfn"); var redirectToStepFunctions = function(lambdaArn, statemachineName, executionName, callback) { const lambdaArnTokens = lambdaArn.split(":"); const partition = lambdaArnTokens[1]; const region = lambdaArnTokens[3]; const accountId = lambdaArnTokens[4]; console.log("partition=" + partition); console.log("region=" + region); console.log("accountId=" + accountId); const executionArn = "arn:" + partition + ":states:" + region + ":" + accountId + ":execution:" + statemachineName + ":" + executionName; console.log("executionArn=" + executionArn); Template Source Code 171 AWS Step Functions Developer Guide const url = "https://console.aws.amazon.com/states/home?region=" + region + "#/executions/details/" + executionArn; callback(null, { statusCode: 302, headers: { Location: url } }); }; exports.handler = (event, context, callback) => { console.log('Event= ' + JSON.stringify(event)); const action = event.query.action; const taskToken = event.query.taskToken; const statemachineName = event.query.sm; const executionName = event.query.ex; const stepfunctions = new StepFunctions(); var message = ""; if (action === "approve") { message = { "Status": "Approved! Task approved by ${Email}" }; } else if (action === "reject") { message = { "Status": "Rejected! Task rejected by ${Email}" }; } else { console.error("Unrecognized action. Expected: approve, reject."); callback({"Status": "Failed to process the request. Unrecognized Action."}); } stepfunctions.sendTaskSuccess({ output: JSON.stringify(message), taskToken: event.query.taskToken }) .then(function(data) { redirectToStepFunctions(context.invokedFunctionArn, statemachineName, executionName, callback); }).catch(function(err) { console.error(err, err.stack); callback(err); }); } Description: Lambda function that callback to AWS Step Functions Template Source Code 172 AWS Step Functions Developer Guide FunctionName: LambdaApprovalFunction Handler: index.handler Role: !GetAtt "LambdaApiGatewayIAMRole.Arn" Runtime: nodejs18.x LambdaApiGatewayInvoke: Type: "AWS::Lambda::Permission" Properties: Action: "lambda:InvokeFunction" FunctionName: !GetAtt "LambdaApprovalFunction.Arn" Principal: "apigateway.amazonaws.com" SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}: ${ExecutionApi}/*" LambdaApiGatewayIAMRole: Type: "AWS::IAM::Role" Properties: AssumeRolePolicyDocument: Version: "2012-10-17" Statement: - Action: - "sts:AssumeRole" Effect: "Allow" Principal: Service: - "lambda.amazonaws.com" Policies: - PolicyName: CloudWatchLogsPolicy PolicyDocument: Statement: - Effect: Allow Action: - "logs:*" Resource: !Sub "arn:${AWS::Partition}:logs:*:*:*" - PolicyName: StepFunctionsPolicy PolicyDocument: Statement: - Effect: Allow Action: - "states:SendTaskFailure" - "states:SendTaskSuccess" Resource: "*" # End Lambda that will be invoked by API Gateway Template Source Code 173 AWS Step Functions Developer Guide # Begin state machine that publishes to Lambda and sends an email with the link for approval HumanApprovalLambdaStateMachine: Type: AWS::StepFunctions::StateMachine Properties: RoleArn: !GetAtt LambdaStateMachineExecutionRole.Arn DefinitionString: Fn::Sub: | { "StartAt": "Lambda Callback", "TimeoutSeconds": 3600, "States": { "Lambda Callback": { "Type": "Task", "Resource": "arn:
step-functions-dg-056
step-functions-dg.pdf
56
Action: - "sts:AssumeRole" Effect: "Allow" Principal: Service: - "lambda.amazonaws.com" Policies: - PolicyName: CloudWatchLogsPolicy PolicyDocument: Statement: - Effect: Allow Action: - "logs:*" Resource: !Sub "arn:${AWS::Partition}:logs:*:*:*" - PolicyName: StepFunctionsPolicy PolicyDocument: Statement: - Effect: Allow Action: - "states:SendTaskFailure" - "states:SendTaskSuccess" Resource: "*" # End Lambda that will be invoked by API Gateway Template Source Code 173 AWS Step Functions Developer Guide # Begin state machine that publishes to Lambda and sends an email with the link for approval HumanApprovalLambdaStateMachine: Type: AWS::StepFunctions::StateMachine Properties: RoleArn: !GetAtt LambdaStateMachineExecutionRole.Arn DefinitionString: Fn::Sub: | { "StartAt": "Lambda Callback", "TimeoutSeconds": 3600, "States": { "Lambda Callback": { "Type": "Task", "Resource": "arn: ${AWS::Partition}:states:::lambda:invoke.waitForTaskToken", "Parameters": { "FunctionName": "${LambdaHumanApprovalSendEmailFunction.Arn}", "Payload": { "ExecutionContext.$": "$$", "APIGatewayEndpoint": "https://${ExecutionApi}.execute-api. ${AWS::Region}.amazonaws.com/states" } }, "Next": "ManualApprovalChoiceState" }, "ManualApprovalChoiceState": { "Type": "Choice", "Choices": [ { "Variable": "$.Status", "StringEquals": "Approved! Task approved by ${Email}", "Next": "ApprovedPassState" }, { "Variable": "$.Status", "StringEquals": "Rejected! Task rejected by ${Email}", "Next": "RejectedPassState" } ] }, "ApprovedPassState": { "Type": "Pass", "End": true Template Source Code 174 Developer Guide AWS Step Functions }, "RejectedPassState": { "Type": "Pass", "End": true } } } SNSHumanApprovalEmailTopic: Type: AWS::SNS::Topic Properties: Subscription: - Endpoint: !Sub ${Email} Protocol: email LambdaHumanApprovalSendEmailFunction: Type: "AWS::Lambda::Function" Properties: Handler: "index.lambda_handler" Role: !GetAtt LambdaSendEmailExecutionRole.Arn Runtime: "nodejs18.x" Timeout: "25" Code: ZipFile: Fn::Sub: | console.log('Loading function'); const { SNS } = require("@aws-sdk/client-sns"); exports.lambda_handler = (event, context, callback) => { console.log('event= ' + JSON.stringify(event)); console.log('context= ' + JSON.stringify(context)); const executionContext = event.ExecutionContext; console.log('executionContext= ' + executionContext); const executionName = executionContext.Execution.Name; console.log('executionName= ' + executionName); const statemachineName = executionContext.StateMachine.Name; console.log('statemachineName= ' + statemachineName); const taskToken = executionContext.Task.Token; console.log('taskToken= ' + taskToken); Template Source Code 175 AWS Step Functions Developer Guide const apigwEndpint = event.APIGatewayEndpoint; console.log('apigwEndpint = ' + apigwEndpint) const approveEndpoint = apigwEndpint + "/execution? action=approve&ex=" + executionName + "&sm=" + statemachineName + "&taskToken=" + encodeURIComponent(taskToken); console.log('approveEndpoint= ' + approveEndpoint); const rejectEndpoint = apigwEndpint + "/execution? action=reject&ex=" + executionName + "&sm=" + statemachineName + "&taskToken=" + encodeURIComponent(taskToken); console.log('rejectEndpoint= ' + rejectEndpoint); const emailSnsTopic = "${SNSHumanApprovalEmailTopic}"; console.log('emailSnsTopic= ' + emailSnsTopic); var emailMessage = 'Welcome! \n\n'; emailMessage += 'This is an email requiring an approval for a step functions execution. \n\n' emailMessage += 'Check the following information and click "Approve" link if you want to approve. \n\n' emailMessage += 'Execution Name -> ' + executionName + '\n\n' emailMessage += 'Approve ' + approveEndpoint + '\n\n' emailMessage += 'Reject ' + rejectEndpoint + '\n\n' emailMessage += 'Thanks for using Step functions!' const sns = new SNS(); var params = { Message: emailMessage, Subject: "Required approval from AWS Step Functions", TopicArn: emailSnsTopic }; sns.publish(params) .then(function(data) { console.log("MessageID is " + data.MessageId); callback(null); }).catch( function(err) { console.error(err, err.stack); callback(err); }); } Template Source Code 176 AWS Step Functions Developer Guide LambdaStateMachineExecutionRole: Type: "AWS::IAM::Role" Properties: AssumeRolePolicyDocument: Version: "2012-10-17" Statement: - Effect: Allow Principal: Service: states.amazonaws.com Action: "sts:AssumeRole" Policies: - PolicyName: InvokeCallbackLambda PolicyDocument: Statement: - Effect: Allow Action: - "lambda:InvokeFunction" Resource: - !Sub "${LambdaHumanApprovalSendEmailFunction.Arn}" LambdaSendEmailExecutionRole: Type: "AWS::IAM::Role" Properties: AssumeRolePolicyDocument: Version: "2012-10-17" Statement: - Effect: Allow Principal: Service: lambda.amazonaws.com Action: "sts:AssumeRole" Policies: - PolicyName: CloudWatchLogsPolicy PolicyDocument: Statement: - Effect: Allow Action: - "logs:CreateLogGroup" - "logs:CreateLogStream" - "logs:PutLogEvents" Resource: !Sub "arn:${AWS::Partition}:logs:*:*:*" - PolicyName: SNSSendEmailPolicy PolicyDocument: Statement: - Effect: Allow Template Source Code 177 AWS Step Functions Developer Guide Action: - "SNS:Publish" Resource: - !Sub "${SNSHumanApprovalEmailTopic}" # End state machine that publishes to Lambda and sends an email with the link for approval Outputs: ApiGatewayInvokeURL: Value: !Sub "https://${ExecutionApi}.execute-api.${AWS::Region}.amazonaws.com/ states" StateMachineHumanApprovalArn: Value: !Ref HumanApprovalLambdaStateMachine Using Inline Map state to repeat an action in Step Functions This tutorial helps you get started with using the Map state in Inline mode. You use the Inline Map state in your workflows to repeatedly perform an action. For more information about Inline mode, see Map state in Inline mode. In this tutorial, you use the Inline Map state to repeatedly generate version 4 universally unique identifiers (v4 UUID). You start by creating a workflow that contains two Pass workflow state states and an Inline Map state in the Workflow Studio. Then, you configure the input and output, including the input JSON array for the Map state. The Map state returns an output array that contains the v4 UUIDs generated for each item in the input array. Step 1: Create the workflow prototype In this step, you create the prototype for your workflow using Workflow Studio. Workflow Studio is a visual workflow designer available in the Step Functions console. You’ll choose the required states from the Flow tab and use the drag and drop feature of Workflow Studio to create the workflow prototype. 1. Open the Step Functions console and choose Create state machine. 2. In the Choose a template dialog box, select Blank. 3. Choose Select to open Workflow Studio in Design mode. 4. From the Flow tab, drag a Pass state and drop it to the empty state labelled Drag first state here. Repeat actions with Inline Map
step-functions-dg-057
step-functions-dg.pdf
57
for your workflow using Workflow Studio. Workflow Studio is a visual workflow designer available in the Step Functions console. You’ll choose the required states from the Flow tab and use the drag and drop feature of Workflow Studio to create the workflow prototype. 1. Open the Step Functions console and choose Create state machine. 2. In the Choose a template dialog box, select Blank. 3. Choose Select to open Workflow Studio in Design mode. 4. From the Flow tab, drag a Pass state and drop it to the empty state labelled Drag first state here. Repeat actions with Inline Map 178 AWS Step Functions Developer Guide 5. Drag a Map state and drop it below the Pass state. Rename the Map state to Map demo. 6. Drag a second Pass state and drop it inside of the Map demo state. 7. Rename the second Pass state to Generate UUID. Step 2: Configure input and output In this step, you configure input and output for all the states in your workflow prototype. First, you inject some fixed data into the workflow using the first Pass state. This Pass state passes on this data as input to the Map demo state. Within this input, you specify the node that contains the input array the Map demo state should iterate over. Then you define the step that the Map demo state should repeat to generate the v4 UUIDs. Finally, you configure the output to return for each repetition. 1. Choose the first Pass state in your workflow prototype. In the Output tab, enter the following under Result: { "foo": "bar", "colors": [ "red", "green", "blue", "yellow", "white" ] } 2. Choose the Map demo state and in the Configuration tab, do the following: a. b. Choose Provide a path to items array. Specify the following reference path to select the node that contains the input array: $.colors 3. Choose the Generate UUID state and in the Input tab, do the following: a. b. Choose Transform input with Parameters. Enter the following JSON input to generate the v4 UUIDs for each of the input array items. You use the States.UUID intrinsic function to generate the UUIDs. Step 2: Configure input and output 179 AWS Step Functions Developer Guide { "uuid.$": "States.UUID()" } 4. For the Generate UUID state, choose the Output tab and do the following: a. b. Choose Filter output with OutputPath. Enter the following reference path to select the JSON node that contains the output array items: $.uuid Step 3: Review and save auto-generated definition As you drag and drop states from the Flow panel onto the canvas, Workflow Studio automatically composes the Amazon States Language (ASL) definition of your workflow in real-time. You can edit this definition as required. 1. (Optional) Choose Definition on the Inspector panel panel to view the automatically- generated Amazon States Language definition of your workflow. Tip You can also view the ASL definition in the Code editor of Workflow Studio. In the code editor, you can also edit the ASL definition of your workflow. The following example shows the automatically generated Amazon States Language definition for your workflow. { "Comment": "Using Map state in Inline mode", "StartAt": "Pass", "States": { "Pass": { "Type": "Pass", "Next": "Map demo", "Result": { Step 3: Review and save auto-generated definition 180 AWS Step Functions Developer Guide "foo": "bar", "colors": [ "red", "green", "blue", "yellow", "white" ] } }, "Map demo": { "Type": "Map", "ItemsPath": "$.colors", "ItemProcessor": { "ProcessorConfig": { "Mode": "INLINE" }, "StartAt": "Generate UUID", "States": { "Generate UUID": { "Type": "Pass", "End": true, "Parameters": { "uuid.$": "States.UUID()" }, "OutputPath": "$.uuid" } } }, "End": true } } } 2. Specify a name for your state machine. To do this, choose the edit icon next to the default state machine name of MyStateMachine. Then, in State machine configuration, specify a name in the State machine name box. For this tutorial, enter the name InlineMapDemo. 3. (Optional) In State machine configuration, specify other workflow settings, such as state machine type and its execution role. For this tutorial, keep all the default selections in State machine configuration. Step 3: Review and save auto-generated definition 181 AWS Step Functions Developer Guide 4. In the Confirm role creation dialog box, choose Confirm to continue. You can also choose View role settings to go back to State machine configuration. Note If you delete the IAM role that Step Functions creates, Step Functions can't recreate it later. Similarly, if you modify the role (for example, by removing Step Functions from the principals in the IAM policy), Step Functions can't restore its original settings later. Step 4: Run the state machine State machine executions are instances where you run your workflow to perform tasks. 1. On the InlineMapDemo page, choose Start execution. 2. In the Start execution
step-functions-dg-058
step-functions-dg.pdf
58
the Confirm role creation dialog box, choose Confirm to continue. You can also choose View role settings to go back to State machine configuration. Note If you delete the IAM role that Step Functions creates, Step Functions can't recreate it later. Similarly, if you modify the role (for example, by removing Step Functions from the principals in the IAM policy), Step Functions can't restore its original settings later. Step 4: Run the state machine State machine executions are instances where you run your workflow to perform tasks. 1. On the InlineMapDemo page, choose Start execution. 2. In the Start execution dialog box, do the following: 1. (Optional) Enter a custom execution name to override the generated default. Non-ASCII names and logging Step Functions accepts names for state machines, executions, activities, and labels that contain non-ASCII characters. Because such characters will not work with Amazon CloudWatch, we recommend using only ASCII characters so you can track metrics in CloudWatch. 2. (Optional) In the Input box, enter input values in JSON format to run your workflow. 3. Choose Start execution. 4. The Step Functions console directs you to a page that's titled with your execution ID. This page is known as the Execution Details page. On this page, you can review the execution results as the execution progresses or after it's complete. To review the execution results, choose individual states on the Graph view, and then choose the individual tabs on the Step details pane to view each state's details including input, output, and definition respectively. For details about the execution information you can view on the Execution Details page, see Execution details overview. Step 4: Run the state machine 182 AWS Step Functions Developer Guide To view the execution input and output side-by-side, choose Execution input and output. Under Output, view the output array returned by the Map state. The following is an example of the output array: [ "a85cbc7b-4e65-4ac2-97af-80ed504adc1d", "b05bca11-d481-414e-aa9a-88285ec6590d", "f42d59f7-bd32-480f-b270-caddb518ce2a", "15f18616-517d-4b69-b7c3-bf22222d2efd", "690bcfee-6d58-408c-a6b4-1995ccafdbd2" ] Copying large-scale CSV data using Distributed Map in Step Functions This tutorial helps you start using the Map state in Distributed mode. A Map state set to Distributed is known as a Distributed Map state. You use the Distributed Map state in your workflows to iterate over large-scale Amazon S3 data sources. The Map state runs each iteration as a child workflow execution, which enables high concurrency. For more information about Distributed mode, see Map state in Distributed mode. In this tutorial, you use the Distributed Map state to iterate over a CSV file in an Amazon S3 bucket. You then return its contents, along with the ARN of a child workflow execution, in another Amazon S3 bucket. You start by creating a workflow prototype in the Workflow Studio. Next, you set the Map state's processing mode to Distributed, specify the CSV file as the dataset, and provide its location to the Map state. You also specify the workflow type for the child workflow executions that the Distributed Map state starts as Express. In addition to these settings, you also specify other configurations, such as the maximum number of concurrent child workflow executions and the location to export the Map result, for the example workflow used in this tutorial. Copy large-scale CSV using Distributed Map 183 AWS Step Functions Prerequisites Developer Guide • Upload a CSV file to an Amazon S3 bucket. You must define a header row within your CSV file. For information about size limits imposed on the CSV file and how to specify the header row, see CSV file in an Amazon S3 bucket. • Create another Amazon S3 bucket and a folder within that bucket to export the Map state result to. Important Make sure that your Amazon S3 buckets are in the same AWS account and AWS Region as your state machine. Note that even though your state machine may be able to access files in buckets across different AWS accounts that are in the same AWS Region, Step Functions only supports state machines to list objects in S3 buckets that are in both the same AWS account and the same AWS Region as the state machine. Step 1: Create the workflow prototype In this step, you create the prototype for your workflow using Workflow Studio. Workflow Studio is a visual workflow designer available in the Step Functions console. You choose the required state and API action from the Flow and Actions tabs respectively. You'll use the drag and drop feature of Workflow Studio to create the workflow prototype. 1. Open the Step Functions console and choose Create state machine. 2. In the Choose a template dialog box, select Blank. 3. Choose Select to open Workflow Studio in Design mode. 4. 5. 6. From the Flow tab, drag a Map state and drop it to the empty state labelled Drag first
step-functions-dg-059
step-functions-dg.pdf
59
your workflow using Workflow Studio. Workflow Studio is a visual workflow designer available in the Step Functions console. You choose the required state and API action from the Flow and Actions tabs respectively. You'll use the drag and drop feature of Workflow Studio to create the workflow prototype. 1. Open the Step Functions console and choose Create state machine. 2. In the Choose a template dialog box, select Blank. 3. Choose Select to open Workflow Studio in Design mode. 4. 5. 6. From the Flow tab, drag a Map state and drop it to the empty state labelled Drag first state here. In the Configuration tab, for State name, enter Process data. From the Actions tab, drag an AWS Lambda Invoke API action and drop it inside the Process data state. 7. Rename the AWS Lambda Invoke state to Process CSV data. Prerequisites 184 AWS Step Functions Developer Guide Step 2: Configure the required fields for Map state In this step, you configure the following required fields of the Distributed Map state: • ItemReader – Specifies the dataset and its location from which the Map state can read input. • ItemProcessor – Specifies the following values: • ProcessorConfig – Set the Mode and ExecutionType to DISTRIBUTED and EXPRESS respectively. This sets the Map state's processing mode and the workflow type for child workflow executions that the Distributed Map state starts. • StartAt – The first state in the Map workflow. • States – Defines the Map workflow, which is a set of steps to repeat in each child workflow execution. • ResultWriter – Specifies the Amazon S3 location where Step Functions writes the Distributed Map state results. Important Make sure that the Amazon S3 bucket you use to export the results of a Map Run is under the same AWS account and AWS Region as your state machine. Otherwise, your state machine execution will fail with the States.ResultWriterFailed error. To configure the required fields: 1. Choose the Process data state and, in the Configuration tab, do the following: a. b. For Processing mode, choose Distributed. For Item source, choose Amazon S3, and then choose CSV file in S3 from the S3 item source dropdown list. c. Do the following to specify the Amazon S3 location of your CSV file: i. ii. For S3 object, select Enter bucket and key from the dropdown list. For Bucket, enter the name of the Amazon S3 bucket, which contains the CSV file. For example, amzn-s3-demo-source-bucket. Step 2: Configure the required fields for Map state 185 AWS Step Functions Developer Guide iii. For Key, enter the name of the Amazon S3 object in which you saved the CSV file. You must also specify the name of the CSV file in this field. For example, csvDataset/ ratings.csv. d. For CSV files, you must also specify the location of the column header. To do this, choose Additional configuration, and then for CSV header location keep the default selection of First row if the first row of your CSV file is the header. Otherwise, choose Given to specify the header within the state machine definition. For more information, see ReaderConfig. e. For Child execution type, choose Express. 2. In Export location, to export the Map Run results to a specific Amazon S3 location, choose Export Map state's output to Amazon S3. 3. Do the following: a. b. c. For S3 bucket, choose Enter bucket name and prefix from the dropdown list. For Bucket, enter the name of the Amazon S3 bucket where you want to export the results to. For example, mapOutputs. For Prefix, enter the folder name where you want to save the results to. For example, resultData. Step 3: Configure additional options In addition to the required settings for a Distributed Map state, you can also specify other options. These can include the maximum number of concurrent child workflow executions and the location to export the Map state result to. 1. Choose the Process data state. Then, in Item source, choose Additional configuration. 2. Do the following: a. Choose Modify items with ItemSelector to specify a custom JSON input for each child workflow execution. b. Enter the following JSON input: { "index.$": "$$.Map.Item.Index", "value.$": "$$.Map.Item.Value" } Step 3: Configure additional options 186 AWS Step Functions Developer Guide For information about how to create a custom input, see ItemSelector (Map). 3. In Runtime settings, for Concurrency limit, specify the number of concurrent child workflow executions that the Distributed Map state can start. For example, enter 100. 4. Open a new window or tab on your browser and complete the configuration of the Lambda function you'll use in this workflow, as explained in Step 4: Configure the Lambda function. Step 4: Configure the Lambda function Important Ensure that your Lambda function is under the same AWS Region as
step-functions-dg-060
step-functions-dg.pdf
60
Step 3: Configure additional options 186 AWS Step Functions Developer Guide For information about how to create a custom input, see ItemSelector (Map). 3. In Runtime settings, for Concurrency limit, specify the number of concurrent child workflow executions that the Distributed Map state can start. For example, enter 100. 4. Open a new window or tab on your browser and complete the configuration of the Lambda function you'll use in this workflow, as explained in Step 4: Configure the Lambda function. Step 4: Configure the Lambda function Important Ensure that your Lambda function is under the same AWS Region as your state machine. 1. Open the Lambda console and choose Create function. 2. On the Create function page, choose Author from scratch. 3. In the Basic information section, configure your Lambda function: a. b. c. For Function name, enter distributedMapLambda. For Runtime, choose Node.js. Keep all of the default selections and choose Create function. d. After you create your Lambda function, copy the function's Amazon Resource Name (ARN) displayed in the upper-right corner of the page. You'll need to provide this in your workflow prototype. The following is an example ARN: arn:aws:lambda:us-east-2:123456789012:function:distributedMapLambda 4. Copy the following code for the Lambda function and paste it into the Code source section of the distributedMapLambda page. exports.handler = async function(event, context) { console.log("Received Input:\n", event); return { 'statusCode' : 200, 'inputReceived' : event //returns the input that it received } Step 4: Configure the Lambda function 187 AWS Step Functions }; Developer Guide 5. Choose Deploy. Once your function deploys, choose Test to see the output of your Lambda function. Step 5: Update the workflow prototype In the Step Functions console, you'll update your workflow to add the Lambda function's ARN. 1. Return to the tab or window where you created the workflow prototype. 2. Choose the Process CSV data step, and in the Configuration tab, do the following: a. b. For Integration type, choose Optimized. For Function name, start to enter the name of your Lambda function. Choose the function from the dropdown list that appears, or choose Enter function name and provide the Lambda function ARN. Step 6: Review the auto-generated Amazon States Language definition and save the workflow As you drag and drop states from the Action and Flow tabs onto the canvas, Workflow Studio automatically composes the Amazon States Language definition of your workflow in real-time. You can edit this definition as required. 1. (Optional) Choose Definition on the Inspector panel panel and view the state machine definition. Tip You can also view the ASL definition in the Code editor of Workflow Studio. In the code editor, you can also edit the ASL definition of your workflow. The following example code shows the automatically generated Amazon States Language definition for your workflow. { Step 5: Update the workflow prototype 188 AWS Step Functions Developer Guide "Comment": "Using Map state in Distributed mode", "StartAt": "Process data", "States": { "Process data": { "Type": "Map", "MaxConcurrency": 100, "ItemReader": { "ReaderConfig": { "InputType": "CSV", "CSVHeaderLocation": "FIRST_ROW" }, "Resource": "arn:aws:states:::s3:getObject", "Parameters": { "Bucket": "amzn-s3-demo-source-bucket", "Key": "csvDataset/ratings.csv" } }, "ItemProcessor": { "ProcessorConfig": { "Mode": "DISTRIBUTED", "ExecutionType": "EXPRESS" }, "StartAt": "Process CSV data", "States": { "Process CSV data": { "Type": "Task", "Resource": "arn:aws:states:::lambda:invoke", "OutputPath": "$.Payload", "Parameters": { "Payload.$": "$", "FunctionName": "arn:aws:lambda:us-east-2:account- id:function:distributedMapLambda" }, "End": true } } }, "Label": "Processdata", "End": true, "ResultWriter": { "Resource": "arn:aws:states:::s3:putObject", "Parameters": { "Bucket": "mapOutputs", "Prefix": "resultData" Step 6: Review the auto-generated Amazon States Language definition and save the workflow 189 AWS Step Functions Developer Guide } }, "ItemSelector": { "index.$": "$$.Map.Item.Index", "value.$": "$$.Map.Item.Value" } } } } 2. Specify a name for your state machine. To do this, choose the edit icon next to the default state machine name of MyStateMachine. Then, in State machine configuration, specify a name in the State machine name box. For this tutorial, enter the name DistributedMapDemo. 3. (Optional) In State machine configuration, specify other workflow settings, such as state machine type and its execution role. For this tutorial, keep all the default selections in State machine configuration. 4. In the Confirm role creation dialog box, choose Confirm to continue. You can also choose View role settings to go back to State machine configuration. Note If you delete the IAM role that Step Functions creates, Step Functions can't recreate it later. Similarly, if you modify the role (for example, by removing Step Functions from the principals in the IAM policy), Step Functions can't restore its original settings later. Step 7: Run the state machine An execution is an instance of your state machine where you run your workflow to perform tasks. 1. On the DistributedMapDemo page, choose Start execution. 2. In the Start execution dialog box, do the following: 1. (Optional) Enter a custom execution name to override the generated default. Step 7: Run the
step-functions-dg-061
step-functions-dg.pdf
61
If you delete the IAM role that Step Functions creates, Step Functions can't recreate it later. Similarly, if you modify the role (for example, by removing Step Functions from the principals in the IAM policy), Step Functions can't restore its original settings later. Step 7: Run the state machine An execution is an instance of your state machine where you run your workflow to perform tasks. 1. On the DistributedMapDemo page, choose Start execution. 2. In the Start execution dialog box, do the following: 1. (Optional) Enter a custom execution name to override the generated default. Step 7: Run the state machine 190 AWS Step Functions Developer Guide Non-ASCII names and logging Step Functions accepts names for state machines, executions, activities, and labels that contain non-ASCII characters. Because such characters will not work with Amazon CloudWatch, we recommend using only ASCII characters so you can track metrics in CloudWatch. 2. (Optional) In the Input box, enter input values in JSON format to run your workflow. 3. Choose Start execution. 4. The Step Functions console directs you to a page that's titled with your execution ID. This page is known as the Execution Details page. On this page, you can review the execution results as the execution progresses or after it's complete. To review the execution results, choose individual states on the Graph view, and then choose the individual tabs on the Step details pane to view each state's details including input, output, and definition respectively. For details about the execution information you can view on the Execution Details page, see Execution details overview. For example, choose the Map state, and then choose Map Run to open the Map Run Details page. On this page, you can view all the execution details of the Distributed Map state and the child workflow executions that it started. For information about this page, see Viewing Map Runs. Iterate a loop with a Lambda function in Step Functions In this tutorial, you implement a design pattern that uses a state machine and an AWS Lambda function to iterate a loop a specific number of times. Use this design pattern any time you need to keep track of the number of loops in a state machine. This implementation can help you break up large tasks or long-running executions into smaller chunks, or to end an execution after a specific number of events. You can use a similar implementation to periodically end and restart a long-running execution to avoid exceeding service quotas for AWS Step Functions, AWS Lambda, or other AWS services. Before you begin, go through the Creating a Step Functions state machine that uses Lambda tutorial to ensure you are familiar with using Lambda and Step Functions together. Iterate a loop with Lambda 191 AWS Step Functions Developer Guide Step 1: Create a Lambda function to iterate a count By using a Lambda function you can track the number of iterations of a loop in your state machine. The following Lambda function receives input values for count, index, and step. It returns these values with an updated index and a Boolean value named continue. The Lambda function sets continue to true if the index is less than count. Your state machine then implements a Choice state that executes some application logic if continue is true, or exits if it is false. To create the Lambda function 1. Sign in to the Lambda console, and then choose Create function. 2. On the Create function page, choose Author from scratch. 3. In the Basic information section, configure your Lambda function, as follows: a. b. c. For Function name, enter Iterator. For Runtime, choose Node.js. In Change default execution role, choose Create a new role with basic Lambda permissions. d. Choose Create function. 4. Copy the following code for the Lambda function into the Code source. export const handler = function (event, context, callback) { let index = event.iterator.index let step = event.iterator.step let count = event.iterator.count index = index + step callback(null, { index, step, count, continue: index < count }) } Step 1: Create a Lambda function to iterate a count 192 AWS Step Functions Developer Guide This code accepts input values for count, index, and step. It increments the index by the value of step and returns these values, and the Boolean continue. The value of continue is true if index is less than count. 5. Choose Deploy. Step 2: Test the Lambda Function Run your Lambda function with numeric values to see it in operation. You can provide input values for your Lambda function that mimic an iteration. To test your Lambda function 1. Choose Test. 2. In the Configure test event dialog box, enter TestIterator in the Event name box. 3. Replace the example data with the following. { "Comment": "Test my Iterator
step-functions-dg-062
step-functions-dg.pdf
62
step. It increments the index by the value of step and returns these values, and the Boolean continue. The value of continue is true if index is less than count. 5. Choose Deploy. Step 2: Test the Lambda Function Run your Lambda function with numeric values to see it in operation. You can provide input values for your Lambda function that mimic an iteration. To test your Lambda function 1. Choose Test. 2. In the Configure test event dialog box, enter TestIterator in the Event name box. 3. Replace the example data with the following. { "Comment": "Test my Iterator function", "iterator": { "count": 10, "index": 5, "step": 1 } } These values mimic what would come from your state machine during an iteration. The Lambda function will increment the index and return true for continue when the index is less than count. For this test, the index has already incremented to 5. The test will increment index to 6 and set continue to true. 4. Choose Create. 5. Choose Test to test your Lambda function. The results of the test are displayed in the Execution results tab. 6. Choose the Execution results tab to see the output. { "index": 6, Step 2: Test the Lambda Function 193 AWS Step Functions Developer Guide "step": 1, "count": 10, "continue": true } Note If you set index to 9 and test again, the index increments to 10, and continue will be false. Step 3: Create a State Machine Before you leave the Lambda console… Copy the Lambda function ARN. Paste it into a note. You'll need it in the next step. Next, you will create a state machine with the following states: • ConfigureCount – Sets default values for count, index, and step. • Iterator – Refers to the Lambda function you created earlier, passing in the values configured in ConfigureCount. • IsCountReached – A choice state that continues the loop or proceeds to Done state, based on the value returned from your Iterator function. • ExampleWork – A stub for work that needs to be done. In this example, the workflow has a Pass state, but in a real solution, you would likely use a Task. • Done – End state of your workflow. To create the state machine in the console: 1. Open the Step Functions console, and then choose Create a state machine. Step 3: Create a State Machine 194 AWS Step Functions Developer Guide Important Your state machine must be in the same AWS account and Region as your Lambda 2. 3. function. Select the Blank template. In the Code pane, paste the following JSON which defines the state machine. For more information about the Amazon States Language, see State Machine Structure. { "Comment": "Iterator State Machine Example", "StartAt": "ConfigureCount", "States": { "ConfigureCount": { "Type": "Pass", "Result": { "count": 10, "index": 0, "step": 1 }, "ResultPath": "$.iterator", "Next": "Iterator" }, "Iterator": { "Type": "Task", "Resource": "arn:aws:lambda:region:123456789012:function:Iterate", "ResultPath": "$.iterator", "Next": "IsCountReached" }, "IsCountReached": { "Type": "Choice", "Choices": [ { "Variable": "$.iterator.continue", "BooleanEquals": true, "Next": "ExampleWork" } ], "Default": "Done" Step 3: Create a State Machine 195 AWS Step Functions }, Developer Guide "ExampleWork": { "Comment": "Your application logic, to run a specific number of times", "Type": "Pass", "Result": { "success": true }, "ResultPath": "$.result", "Next": "Iterator" }, "Done": { "Type": "Pass", "End": true } } } 4. Replace the Iterator Resource field with the ARN for your Iterator Lambda function that you created earlier. 5. Select Config, and enter a Name for your state machine, such as IterateCount. Note Names of state machines, executions, and activity tasks must not exceed 80 characters in length. These names must be unique for your account and AWS Region, and must not contain any of the following: • Whitespace • Wildcard characters (? *) • Bracket characters (< > { } [ ]) • Special characters (" # % \ ^ | ~ ` $ & , ; : /) • Control characters (\\u0000 - \\u001f or \\u007f - \\u009f). Step Functions accepts names for state machines, executions, activities, and labels that contain non-ASCII characters. Because such characters will not work with Amazon CloudWatch, we recommend using only ASCII characters so you can track metrics in CloudWatch. Step 3: Create a State Machine 196 AWS Step Functions Developer Guide 6. For Type, accept default value of Standard. For Permissions, choose Create new role. 7. Choose Create, and then Confirm the role creations. Step 4: Start a New Execution After you create your state machine, you can start an execution. 1. On the IterateCount page, choose Start execution. 2. (Optional) Enter a custom execution name to override the generated default. Non-ASCII names and logging Step Functions accepts names for state machines, executions, activities, and labels that contain non-ASCII characters. Because such characters will not
step-functions-dg-063
step-functions-dg.pdf
63
track metrics in CloudWatch. Step 3: Create a State Machine 196 AWS Step Functions Developer Guide 6. For Type, accept default value of Standard. For Permissions, choose Create new role. 7. Choose Create, and then Confirm the role creations. Step 4: Start a New Execution After you create your state machine, you can start an execution. 1. On the IterateCount page, choose Start execution. 2. (Optional) Enter a custom execution name to override the generated default. Non-ASCII names and logging Step Functions accepts names for state machines, executions, activities, and labels that contain non-ASCII characters. Because such characters will not work with Amazon CloudWatch, we recommend using only ASCII characters so you can track metrics in CloudWatch. 3. Choose Start Execution. A new execution of your state machine starts, showing your running execution. The execution increments in steps, tracking the count using your Lambda function. On each iteration, it performs the example work referenced in the ExampleWork state in your state machine. When the count reaches the number specified in the ConfigureCount state in your state machine, the execution quits iterating and ends. Step 4: Start a New Execution 197 AWS Step Functions Developer Guide Processing batch data with a Lambda function in Step Functions In this tutorial, you use the Distributed Map state's ItemBatcher (Map) field to process an entire batch of items inside a Lambda function. Each batch contains a maximum of three items. The Distributed Map state starts four child workflow executions, where each execution processes three items, while one execution processes a single item. Each child workflow execution invokes a Lambda function that iterates over the individual items present in the batch. You'll create a state machine that performs multiplication on an array of integers. Say that the integer array you provide as input is [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and the multiplication factor is 7. Then, the resulting array formed after multiplying these integers with a factor of 7, will be [7, 14, 21, 28, 35, 42, 49, 56, 63, 70]. Step 1: Create the state machine In this step, you create the workflow prototype of the state machine that passes an entire batch of data to the Lambda function you'll create in Step 2. • Use the following definition to create a state machine using the Step Functions console. For information about creating a state machine, see Step 1: Create the workflow prototype in the Getting started with using Distributed Map state tutorial. In this state machine, you define a Distributed Map state that accepts an array of 10 integers as input and passes this array to a Lambda function in batches of 3. The Lambda function iterates over the individual items present in the batch and returns an output array named multiplied. The output array contains the result of the multiplication performed on the items passed in the input array. Process batch data with Lambda 198 AWS Step Functions Developer Guide Important Make sure to replace the Amazon Resource Name (ARN) of the Lambda function in the following code with the ARN of the function you'll create in Step 2. { "StartAt": "Pass", "States": { "Pass": { "Type": "Pass", "Next": "Map", "Result": { "MyMultiplicationFactor": 7, "MyItems": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] } }, "Map": { "Type": "Map", "ItemProcessor": { "ProcessorConfig": { "Mode": "DISTRIBUTED", "ExecutionType": "STANDARD" }, "StartAt": "Lambda Invoke", "States": { "Lambda Invoke": { "Type": "Task", "Resource": "arn:aws:states:::lambda:invoke", "OutputPath": "$.Payload", "Parameters": { "Payload.$": "$", "FunctionName": "arn:aws:lambda:region:account- id:function:functionName" }, "Retry": [ { "ErrorEquals": [ "Lambda.ServiceException", "Lambda.AWSLambdaException", "Lambda.SdkClientException", Step 1: Create the state machine 199 AWS Step Functions Developer Guide "Lambda.TooManyRequestsException" ], "IntervalSeconds": 2, "MaxAttempts": 6, "BackoffRate": 2 } ], "End": true } } }, "End": true, "Label": "Map", "MaxConcurrency": 1000, "ItemBatcher": { "MaxItemsPerBatch": 3, "BatchInput": { "MyMultiplicationFactor.$": "$.MyMultiplicationFactor" } }, "ItemsPath": "$.MyItems" } } } Step 2: Create the Lambda function In this step, you create the Lambda function that processes all the items passed in the batch. Important Ensure that your Lambda function is under the same AWS Region as your state machine. To create the Lambda function 1. Use the Lambda console to create a Python Lambda function named ProcessEntireBatch. For information about creating a Lambda function, see Step 4: Configure the Lambda function in the Getting started with using Distributed Map state tutorial. 2. Copy the following code for the Lambda function and paste it into the Code source section of your Lambda function. Step 2: Create the Lambda function 200 AWS Step Functions import json Developer Guide def lambda_handler(event, context): multiplication_factor = event['BatchInput']['MyMultiplicationFactor'] items = event['Items'] results = [multiplication_factor * item for item in items] return { 'statusCode': 200, 'multiplied': results } 3. After you create your Lambda function, copy the function's ARN displayed in the upper-right corner of the