Generated banner for AWS Step Functions
Generated logo for AWS Step Functions

AWS Step Functions

AWSOfficialPublished by AWS

  • Skill
  • Tool integration
  • Cloud and DevOps
  • Apache-2.0
  • Medium risk

From the author

Authors and edits AWS Step Functions state machines: writes Amazon States Language (ASL) in JSONata, and chooses and structures state types (Task, Choice, Map, Parallel, Pass, Wait, Succeed, Fail). Covers ASL syntax, JSONata data transformation and variables, Retry/Catch error handling, service integrations (.sync, waitForTaskToken callbacks), Distributed Map for large-scale S3/CSV processing, saga/compensation patterns, Standard vs Express workflow choice, TestState API unit testing, and migrating state machines from JSONPath to JSONata. Use when the user is building, authoring, debugging, or migrating a Step Functions state machine or ASL definition, or orchestrating multi-step workflows with branching, retries, or human-approval callbacks, even if they don't say 'Step Functions.' Do NOT use for general Lambda function code, API Gateway, EventBridge wiring, or SAM/CDK application packaging.
— the description by AWS

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides comprehensive support for building and managing AWS Step Functions workflows. It covers the Amazon States Language (ASL) structure, state types, and the integration of JSONata for data transformation. Users receive guidance on error handling, service integrations, and architectural patterns such as saga, polling, and semaphore locks. The skill also includes instructions for migrating from JSONPath to JSONata, unit testing with the TestState API, and implementing security best practices for workflow definitions.

What it does

  • Provides syntax guidance for ASL state types including Task, Choice, Map, and Parallel.
  • Explains JSONata expressions for data transformation, filtering, and variable assignment.
  • Details error handling strategies using Retry and Catch blocks.
  • Offers patterns for complex orchestration like saga compensation, scatter-gather, and human-in-the-loop.
  • Guides users through migrating legacy JSONPath definitions to modern JSONata.
  • Supports unit testing of individual states using the TestState API and mock data.

When to use it

  • When authoring or editing AWS Step Functions state machine definitions.
  • When implementing complex branching, retries, or multi-step workflow logic.
  • When migrating existing state machines from JSONPath to JSONata.
  • When debugging data flow or state transitions within a workflow.
  • When testing state machine logic in isolation without deploying to AWS.

Advantages

  • Centralized reference for ASL syntax and JSONata transformation logic.
  • Clear distinction between Standard and Express workflow capabilities.
  • Structured patterns for common distributed system challenges.
  • Guidance on secure configuration and least-privilege IAM practices.
  • Practical advice for isolating and testing states to reduce development cycles.

Usage examples

“How do I implement a retry policy for a Lambda task in my state machine?”
The agent provides the Retry block syntax, explaining how to configure ErrorEquals, IntervalSeconds, MaxAttempts, and BackoffRate.
“Show me how to use JSONata to transform the output of a Task state.”
The agent demonstrates the Output field usage with JSONata expressions, showing how to reference $states.result.
“How can I test a single state in my workflow without running the whole machine?”
The agent explains the TestState API, providing the command structure and how to construct the required mock input.
“What is the difference between Standard and Express workflows?”
The agent provides a comparison table covering duration, execution semantics, history retention, and throughput limits.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/aws/aws-step-functions/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip aws-step-functions.zip -d .agents/skills

Documentation by AWS

AWS Step Functions

Overview

AWS Step Functions uses Amazon States Language (ASL) to define state machines as JSON. 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.

This skill provides comprehensive guidance for writing state machines in ASL, covering:

  • ASL structure and JSONata expression syntax

  • Details on the eight available workflow states

  • The $states reserved variable

  • Workflow variables with Assign

  • Error handling

  • AWS Service integration patterns

  • Example code for data transformation and architecture

  • Validation and testing of state machines

  • How to migrate from JSONPath to JSONata

The AWS MCP server is recommended for sandboxed execution and audit logging when following this skill, but all steps use AWS CLI syntax and work without it.

When to Load Reference Files

Load the appropriate reference file based on what the user is working on:

  • ASL structure, state types, Task, Pass, Choice, Wait, Succeed, Fail, Parallel, Map → see references/asl-state-types.md

  • Error handling, troubleshooting, Retry, Catch, fallback, error codes, States.Timeout, States.ALL → see references/error-handling.md

  • Service integrations, Lambda invoke, DynamoDB, SNS, SQS, SDK integrations, Resource ARN, sync, async → see references/service-integrations.md

  • Migrating from JSONPath to JSONata, migration, JSONPath to JSONata, InputPath, Parameters, ResultSelector, ResultPath, OutputPath, intrinsic functions, Iterator, payload template → see references/migrating-from-jsonpath-to-jsonata.md

  • Validation, linting, testing, TestState, test state, mock, mocking, unit test, inspection level, DEBUG, TRACE, validate state, test in isolation → see references/validation-and-testing.md

  • Architecture patterns, examples, polling, saga, compensation, scatter-gather, semaphore, lock, human-in-the-loop, escalation, Express to Standard → see references/architecture-patterns.md

  • Data transformation, JSONata expressions, filtering, aggregation, string operations, $reduce, $lookup, $toMillis, $partition, $parse, $hash, $uuid → see references/transforming-data.md

  • State input/output, $states, Assign, Output, Arguments, variable scope, variable limits, evaluation order, passing data between states → see references/processing-state-inputs-and-outputs.md

Quick Reference

Standard vs Express Workflows
StandardExpress
Max duration1 year5 minutes
Execution semanticsExactly-onceAt-least-once (async) / At-most-once (sync)
Execution historyRetained 90 days, queryable via APICloudWatch Logs only
Max throughput2,000 exec/sec100,000 exec/sec
Pricing modelPer state transitionPer execution count + duration
.sync / .waitForTaskTokenSupportedNot supported
Best forAuditable, non-idempotent operationsHigh-volume, idempotent event processing

Choose Standard for: payment processing, order fulfillment, compliance workflows, anything that must never execute twice.

Choose Express for: IoT data ingestion, streaming transformations, mobile backends, high-throughput short-lived processing.

When recommending Express, the single limitation you must always state — even for fire-and-forget / high-throughput pipelines — is that Express does NOT support .sync or .waitForTaskToken (no callbacks, no nested .sync waits, no human-approval or job-completion waits). Also note: 5-minute max duration, no queryable execution history (CloudWatch Logs only), and at-least-once (async) / at-most-once (sync) execution — so non-idempotent work can run twice. If any of these matter, choose Standard (exactly-once, up to 1 year, full history).

Setting the State Machine Query Language

JSONata is the preferred way to reference and transform data in ASL. It replaces the five JSONPath I/O fields (InputPath, Parameters, ResultSelector, ResultPath, OutputPath) with just two: Arguments (inputs) and Output.

Enable at the top level to apply to all states:

{ "QueryLanguage": "JSONata", "StartAt": "...", "States": {...} }

Or per-state to migrate from JSONPath incrementally:

{ "Type": "Task", "QueryLanguage": "JSONata", ... }

JSONPath is supported and is the default if QueryLanguage is omitted — existing state machines do not need to be migrated.

Field mapping (JSONPath → JSONata):

JSONPath fieldJSONata equivalent
Parameters (keys use key.$)Arguments — drop the .$ suffix and wrap each value in {% %}
ResultSelector and OutputPathOutput (reference the raw result via $states.result)
ResultPathAssign (preferred) or Output
InputPathnot needed — reference $states.input directly

A state uses one query language, not both. Never mix JSONPath fields (InputPath/Parameters/ResultSelector/ResultPath/OutputPath) with JSONata fields (Arguments/Output) in the same state — this is the most common migration error. See references/migrating-from-jsonpath-to-jsonata.md for full details.

How Assign and Output Are Evaluated (Parallel, Not Sequential)

Within a single state, Assign and Output are evaluated at the same time — in parallel — both reading the same data (the state input plus the task result). They are NOT evaluated one after the other. Because they run together, a variable you set in Assign is not visible in that same state's Output: there is no ordering in which Output could observe the just-assigned value. The assigned value becomes available only to subsequent states.

So if you set a variable in Assign and reference it in the same state's Output, you get the old/undefined value — not because Output runs "before" Assign, but because both evaluate concurrently from the same snapshot. To use the value immediately, reference it in the next state (variables persist across states); to shape the current state's output from the task result, use $states.result directly in Output.

Unit Testing a State with TestState

Test a single state without deploying the state machine or calling the real service using the TestState API (aws stepfunctions test-state) with --mock. A complete answer covers all four points:

  • Mock the service response exactly — the --mock result MUST match the target AWS service's API response schema exactly (field names are case-sensitive). For a Lambda invoke Task that is StatusCode and Payload: --mock '{"result":"{\"StatusCode\":200,\"Payload\":{...}}"}'.

  • All three inspection levels (--inspection-level): INFO (default — output, status, nextState), DEBUG (adds data flow: afterArguments, result, variables — use to debug JSONata/data flow), TRACE (adds raw HTTP request/response, for HTTP Task).

  • .sync and .waitForTaskToken integrations still require a mock — for .sync, mock the polling API (e.g. DescribeExecution, not the initial call); for .waitForTaskToken, also pass --context '{"Task":{"Token":"..."}}'.

  • No deployment or real invocation is needed — the state is tested in isolation.

See references/validation-and-testing.md for per-service mock structures and error/retry/Map/Parallel testing.

Best Practices

  • Set "QueryLanguage": "JSONata" at the top level for new state machines unless the user wants to use JSONPath

  • Keep Output minimal — only include what the state immediately after the current state needs

  • Use Assign to store variables needed in later states instead of threading it through Output

  • Use $states.input to reference original state input

  • Assign and Output are evaluated in parallel from the state's entry data, NOT sequentially — a variable set in Assign is therefore NOT visible in the same state's Output (which still sees the pre-Assign values); the new value takes effect only in the next state.

  • All JSONata expressions must produce a defined value — $data.nonExistentField throws States.QueryEvaluationError

  • Use $states.context.Execution.Input to access the original workflow input from any state

  • Save state machine definitions with .asl.json extension when working outside the console

  • Prefer the optimized Lambda integration (arn:aws:states:::lambda:invoke) over the SDK integration

Troubleshooting

Common Errors
  • States.QueryEvaluationError — JSONata expression failed. Check for type errors, undefined fields, or out-of-range values.

  • Mixing JSONPath fields with JSONata fields in the same state.

  • Using $ or $$ at the top level of a JSONata expression — use $states.input instead.

  • Forgetting {% %} delimiters around JSONata expressions — the string will be treated as a literal.

  • Assigning variables in Assign and expecting them in Output of the same state — new values only take effect in the next state.

  • Reference references/validation-and-testing.md and references/error-handling.md for detailed troubleshooting information.

Security Considerations

  • Least-privilege execution role. Scope the state machine's IAM role to the specific resources and actions it invokes (specific Lambda/DynamoDB/SQS/SNS ARNs). Avoid *FullAccess policies and service:* wildcards.

  • Encryption. Recommend encryption at rest and in transit for every data store a workflow touches: KMS-encrypted DynamoDB tables, server-side encryption (KmsMasterKeyId) on SQS queues and SNS topics, and TLS for HTTP Tasks.

  • Task tokens and message bodies are sensitive. A .waitForTaskToken token is a credential — treat it as a secret. Do not place PII, financial data, or secrets in SQS/SNS message bodies or notifications; pass a reference ID and have recipients look up details through an authorized channel.

  • Validate input and fail fast. Validate required fields at the start of the workflow with a Choice (or Pass) state using $exists() and $type(), and route invalid input to a Fail state so malformed data never reaches downstream states. Protect downstream services from bursts by setting MaxConcurrency on Map states and throttling upstream (StartExecution rate limits or EventBridge).

  • Cross-account access. When using the Credentials field to assume a role in another account, include condition keys such as aws:SourceArn or aws:SourceAccount in the target role's trust policy to prevent unintended assumption.

  • External secrets. For HTTP Tasks calling third-party APIs, store API keys and tokens in AWS Secrets Manager (referenced via an EventBridge connection), never embedded in the state machine definition.

  • Observability. Enable CloudWatch Logs for executions (log level ALL or ERROR; required for Express workflows, which have no queryable execution history), enable CloudTrail to audit Step Functions API calls, and set CloudWatch Alarms on execution failures. Always encrypt the execution log group with a customer-managed KMS key, since state input/output routinely flows through execution logs.

Resources

Files

references/validation-and-testing.md

Validation and Testing

Local ASL Validation

Files saved with the .asl.json extension get automatic validation from the AWS Toolkit Extension. If the extension is not installed, suggest the user install it (https://open-vsx.org/extension/amazonwebservices/aws-toolkit-vscode). Use your diagnostics tool on any .asl.json file to catch structural errors instantly. The State Machine definition must be saved as .asl.json to work with local validation.


Testing with TestState API

The TestState API enables unit and integration testing of Step Functions without deployment. Key capabilities:

  • Mock service integrations — Test without invoking real services

  • Advanced states — Map, Parallel, Activity, .sync, .waitForTaskToken (require mocks)

  • Control execution — Simulate retries, Map iterations, error scenarios

  • Chain tests — Use output→input to test execution paths

  • Optional IAM — When mocking, roleArn optional

Before Accessing AWS

Before calling the TestState API, follow this sequence:

  1. Ask the user to grant you permission to use the TestState API in their AWS account.

  2. Check for AWS credentials: run aws sts get-caller-identity and verify the response.

  3. If credentials are available, confirm the IAM role ARN to use for execution (or omit if using mocks).

  4. If credentials are unavailable, help the user construct the CLI/SDK call to run manually.

  5. Never assume AWS access — always ask before making any AWS API call.

Prefer short-lived credentials: Use credentials from an IAM role (EC2 instance profile, ECS task role, or AWS IAM Identity Center) rather than long-lived access keys stored in ~/.aws/credentials.

Required IAM Permissions

The calling identity needs states:TestState. If not using mocks, it also needs iam:PassRole for the execution role. For HTTP Task with revealSecrets, add states:RevealSecrets.

aws stepfunctions test-state \
  --definition '{"Type":"Task","Resource":"arn:aws:states:::lambda:invoke","Arguments":{...},"End":true}' \
  --input '{"data":"value"}' \
  --mock '{"result":"{\"StatusCode\":200,\"Payload\":{\"body\":\"success\"}}"}' \
  --inspection-level DEBUG

Inspection Levels

LevelReturnsUse Case
INFOoutput, status, nextStateQuick validation
DEBUG+ afterArguments, result, variablesData flow debugging
TRACE+ HTTP request/response (use --reveal-secrets for auth)HTTP Task debugging

Critical: Service-Specific Mock Structure

⚠️ Mocks MUST match AWS service API response schema exactly — field names (case-sensitive), types, required fields.

Finding Mock Structure
  1. Identify service from Resource ARN: arn:aws:states:::lambda:invoke → Lambda Invoke API

  2. Consult AWS SDK docs for that API's Response Syntax

  3. Structure mock to match

Common Service Mocks
ServiceAPIMock StructureExample
LambdaInvoke{StatusCode, Payload, FunctionError?}'{"result":"{\"StatusCode\":200,\"Payload\":{\"body\":\"ok\"}}"}'
DynamoDBPutItem{Attributes?}'{"result":"{\"Attributes\":{\"id\":{\"S\":\"123\"}}}"}'
DynamoDBGetItem{Item?}'{"result":"{\"Item\":{\"id\":{\"S\":\"123\"}}}"}'
SNSPublish{MessageId}'{"result":"{\"MessageId\":\"abc-123\"}"}'
SQSSendMessage{MessageId, MD5OfMessageBody}'{"result":"{\"MessageId\":\"xyz\",\"MD5OfMessageBody\":\"...\"}"}'
EventBridgePutEvents{FailedEntryCount, Entries[]}'{"result":"{\"FailedEntryCount\":0,\"Entries\":[{\"EventId\":\"123\"}]}"}'
S3PutObject{ETag, VersionId?}'{"result":"{\"ETag\":\"\\\"abc123\\\"\"}"}'
Step FunctionsStartExecution{ExecutionArn, StartDate}'{"result":"{\"ExecutionArn\":\"arn:...\",\"StartDate\":\"...\"}"}'
Secrets ManagerGetSecretValue{ARN, Name, SecretString?}'{"result":"{\"Name\":\"MySecret\",\"SecretString\":\"...\"}"}'

For .sync patterns: Mock the polling API (e.g., startExecution.sync:2 → mock DescribeExecution, NOT StartExecution)

Mock Syntax

Success: --mock '{"result":"<service API response JSON>"}'
Error: --mock '{"errorOutput":{"error":"ErrorCode","cause":"description"}}'
Validation: --mock '{"fieldValidationMode":"STRICT|PRESENT|NONE","result":"..."}'

Validation modes:

  • STRICT (default): All required fields, correct types — use in CI/CD

  • PRESENT: Only validate fields present — flexible testing

  • NONE: No validation — quick prototyping only

Testing Map States

Tests Map's input/output processing, not iterations inside. Mock = entire Map output.

aws stepfunctions test-state \
  --definition '{
    "Type":"Map",
    "Items":"{% $states.input.items %}",
    "ItemSelector":{"value":"{% $states.context.Map.Item.Value %}"},
    "ItemProcessor":{"ProcessorConfig":{"Mode":"INLINE"},...},
    "End":true
  }' \
  --input '{"items":[1,2,3]}' \
  --mock '{"result":"[10,20,30]"}' \
  --inspection-level DEBUG

DEBUG returns: afterItemSelector, afterItemBatcher, toleratedFailureCount, maxConcurrency

Distributed Map: Provide data in input (as if read from S3)
Failure threshold testing: Use --state-configuration '{"mapIterationFailureCount":N}'
Testing state within Map: --state-name auto-populates $states.context.Map.Item.Index, $states.context.Map.Item.Value

Testing Parallel States

Mock = JSON array, one element per branch (in definition order):

--mock '{"result":"[{\"branch1\":\"result1\"},{\"branch2\":\"result2\"}]"}'

Testing Error Handling

Retry Logic
--state-configuration '{"retrierRetryCount":1}' \
--mock '{"errorOutput":{"error":"Lambda.ServiceException","cause":"..."}}' \
--inspection-level DEBUG

Response includes: status:"RETRIABLE", retryBackoffIntervalSeconds, retryIndex

Catch Handlers
--mock '{"errorOutput":{"error":"Lambda.TooManyRequestsException","cause":"..."}}' \
--inspection-level DEBUG

Response includes: status:"CAUGHT_ERROR", nextState, catchIndex, error in output

Error Propagation in Map/Parallel
--state-name "ChildState" \
--state-configuration '{"errorCausedByState":"ChildState"}' \
--mock '{"errorOutput":{"error":"States.TaskFailed","cause":"..."}}'

Testing .sync and .waitForTaskToken

Required: Must provide mock (validation exception otherwise)

.sync Patterns

Mock the polling API, not initial call:

# startExecution.sync:2 → mock DescribeExecution
--mock '{"result":"{\"Status\":\"SUCCEEDED\",\"Output\":\"{...}\"}"}'

Common patterns: startExecution.sync:2→DescribeExecution, batch:submitJob.sync→DescribeJobs, glue:startJobRun.sync→GetJobRun

.waitForTaskToken
--context '{"Task":{"Token":"test-token-123"}}' \
--mock '{"result":"{\"StatusCode\":200,\"Payload\":{\"status\":\"approved\"}}"}'

Activity States

Require mock:

--definition '{"Type":"Task","Resource":"arn:aws:states:...:activity:MyActivity",...}' \
--mock '{"result":"{\"result\":\"completed\"}"}'

Chaining Tests (Integration Testing)

RESULT_1=$(aws stepfunctions test-state --state-name "State1" ... | jq -r '.output')
NEXT_1=$(... | jq -r '.nextState')
RESULT_2=$(aws stepfunctions test-state --state-name "$NEXT_1" --input "$RESULT_1" ...)

Validates: data transformations, state transitions, end-to-end paths

Context Fields

Test states referencing execution context:

--context '{
  "Execution":{"Id":"arn:...","Name":"test-123","StartTime":"2024-01-01T10:00:00.000Z"},
  "State":{"Name":"ProcessData","EnteredTime":"2024-01-01T10:00:05.000Z"},
  "Task":{"Token":"test-token-abc123"}
}'

HTTP Tasks (TRACE)

--resource "arn:aws:states:::http:invoke" \
--inspection-level TRACE \
--reveal-secrets  # Requires states:RevealSecrets permission

Returns: inspectionData.request (method, URL, headers, body), inspectionData.response (status, headers, body)

Troubleshooting

ErrorFix
Invalid field typeCheck AWS SDK docs for correct types
Required field missingAdd field OR use fieldValidationMode:PRESENT
.sync validation failedMock polling API, not initial call

Debug workflow:

  1. Start fieldValidationMode:NONE for logic testing

  2. Switch to PRESENT for partial validation

  3. Use STRICT in CI/CD

Test Automation Pattern

#!/bin/bash
test_state() {
  local state_name=$1
  local input=$2
  local mock=$3

  aws stepfunctions test-state \
    --definition "$(cat statemachine.asl.json)" \
    --state-name "$state_name" \
    --input "$input" \
    --mock "$mock" \
    --inspection-level DEBUG
}

# Test chain
RESULT=$(test_state "State1" '{"id":"123"}' '{"result":"..."}' | jq -r '.output')
test_state "State2" "$RESULT" '{"result":"..."}'

Best Practices

  1. Always verify mock structure against AWS SDK docs for the specific service

  2. For .sync, mock polling API (DescribeX/GetX), not initial call

  3. Use STRICT validation in CI/CD to catch mismatches early

  4. Test all error paths with appropriate error codes

  5. Chain tests to validate multi-state execution paths

  6. Start with NONE→PRESENT→STRICT when developing mocks

  7. Use DEBUG for data flow, TRACE for HTTP debugging

  8. Mock external dependencies to isolate state machine logic

  9. Test Map failure thresholds with mapIterationFailureCount

  10. Never expose --reveal-secrets output — keep it out of version control, shell history, CI/CD build logs, and CloudWatch Logs; redirect to a file with restricted permissions and avoid persisting DEBUG/TRACE output that may contain secrets

Quick Reference

# Basic test
aws stepfunctions test-state --definition '{...}' --input '{...}' --mock '{...}'

# Test specific state in state machine
aws stepfunctions test-state --definition "$(cat sm.json)" --state-name "MyState" --input '{...}' --mock '{...}'

# Test retry (2nd attempt)
--state-configuration '{"retrierRetryCount":1}' --mock '{"errorOutput":{...}}'

# Test Map failure threshold
--state-configuration '{"mapIterationFailureCount":5}' --mock '{"errorOutput":{...}}'

# Test with context
--context '{"Execution":{"Id":"..."}, "Task":{"Token":"..."}}'

# HTTP Task with secrets
--inspection-level TRACE --reveal-secrets

# Mock validation modes
--mock '{"fieldValidationMode":"STRICT|PRESENT|NONE","result":"..."}'

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs an MCP server, Needs an API key

Security

What our scanner noticed· Medium risk

  • References to credential files

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
AWS
Publisher
AWS (Official)
Source
aws/agent-toolkit-for-aws · skills/specialized-skills/serverless-skills/aws-step-functions · commit 0a218f8
Licence
Apache License 2.0 (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • NOTICE (added by AutoGineer from NOTICE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by AWS or AWS.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download aws-step-functions.zip