
Multi-Step Automation Workflows with AWS Step Functions
Build an incident-response workflow with AWS Step Functions: parallel actions, severity branching, and error handling. No Lambda required
Say you have an incident-response runbook. It gathers instance details, takes a forensic snapshot, tags the instance, and notifies the team. Four steps, wired together in a shell script or a single Lambda function.
An automation script like this is fine until one step fails. The snapshot call times out, the function crashes, and now you have a half-tagged instance, no backup, and no record of how far the script got before it died.
Re-running isn't simple either. You either repeat the steps that already succeeded, or you wrap every call in fragile "did this already happen?" checks.
Orchestration logic (retries, branching, parallelism, and knowing where you are when something fails) doesn't belong in a script. It belongs in a workflow engine. AWS Step Functions models your automation as a state machine: each step is a named state, the service tracks execution history, and failure handling is declarative rather than something you hand-roll.
This post builds a real incident-response workflow hands-on, gathering info, running two actions in parallel, branching on severity, and handling errors, then covers the one upfront decision that shapes everything: Standard vs Express.
The Script That Fails Halfway
A procedural script orchestrating cloud operations carries problems that have nothing to do with the operations themselves:
- No memory of progress: a crash at step 3 usually leaves no record of what finished, so re-running risks repeating completed work.
- Hand-rolled error handling: every call needs its own try/retry/timeout logic, and it's never consistent.
- No parallelism without effort: independent steps run one after another because concurrency in a script is extra code.
- No audit trail: "what ran, in what order, with what result?" has no built-in answer.
Step Functions makes all four someone else's job. To see how, you first need the vocabulary.
Workflows as State Machines
In Step Functions, workflows are called state machines, and each step is a state. You define them in the Amazon States Language (ASL) , a JSON-based structured language. States fall into two broad kinds:
- Task: does a unit of work by calling an AWS service API or running a Lambda function.
- Flow states: control execution. Choice adds conditional branching, Parallel runs branches concurrently, Map iterates over a dataset, Wait pauses, and Succeed/Fail terminate.
Error handling attaches to states declaratively: Retry re-attempts a failing task with backoff, and Catch routes a failure to a fallback state instead of crashing the whole execution.
The feature that removes most Lambda glue is AWS SDK service integrations . You can call any of over 200 AWS services, more than 9,000 API actions, directly from a Task state. For instance, you can call EC2's
CreateSnapshot action by just definied a Task's Resource as arn:aws:states:::aws-sdk:ec2:createSnapshot .Here's the workflow we'll build, an incident response that gathers context, acts in parallel, then branches on severity:
With the model and the target in hand, let's define it.
Building the Workflow
Step Functions needs an execution role it can assume to call the services in your Task states. Scope it to just what the workflow touches: describe/tag/snapshot EC2 and publish to SNS.
# Trust policy: let the Step Functions service assume this rolecat > sfn-trust.json << 'EOF'{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "states.amazonaws.com" }, "Action": "sts:AssumeRole" } ]}EOF
aws iam create-role --role-name IncidentResponseRole \ --assume-role-policy-document file://sfn-trust.json
# Least privilege: only the API actions the Task states callaws iam put-role-policy --role-name IncidentResponseRole \ --policy-name WorkflowActions \ --policy-document '{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": ["ec2:DescribeInstances", "ec2:CreateTags", "ec2:CreateSnapshot"], "Resource": "*" }, { "Effect": "Allow", "Action": "sns:Publish", "Resource": "*" } ] }'Now the state machine definition. Read it top-down:
GatherInstanceInfo describes the instance (and Catch sends any failure to HandleError ), ParallelActions tags and snapshots at the same time, DetermineSeverity branches, and the notify states publish to SNS. Each Task uses an aws-sdk resource, so there's no Lambda anywhere.{ "Comment": "Incident response: gather, act in parallel, branch, notify", "StartAt": "GatherInstanceInfo", "States": { "GatherInstanceInfo": { "Type": "Task", "Resource": "arn:aws:states:::aws-sdk:ec2:describeInstances", "Parameters": { "InstanceIds.$": "States.Array($.InstanceId)" }, "ResultPath": "$.InstanceInfo", "Next": "ParallelActions", "Catch": [{ "ErrorEquals": ["States.ALL"], "Next": "HandleError" }] },
"ParallelActions": { "Type": "Parallel", "ResultPath": "$.ParallelResults", "Next": "DetermineSeverity", "Branches": [ { "StartAt": "TagInstance", "States": { "TagInstance": { "Type": "Task", "Resource": "arn:aws:states:::aws-sdk:ec2:createTags", "Parameters": { "Resources.$": "States.Array($.InstanceId)", "Tags": [{ "Key": "IncidentStatus", "Value": "Investigating" }] }, "End": true } } }, { "StartAt": "GetVolumeId", "States": { "GetVolumeId": { "Type": "Pass", "Parameters": { "VolumeId.$": "$.InstanceInfo.Reservations[0].Instances[0].BlockDeviceMappings[0].Ebs.VolumeId" }, "Next": "CreateSnapshot" }, "CreateSnapshot": { "Type": "Task", "Resource": "arn:aws:states:::aws-sdk:ec2:createSnapshot", "Parameters": { "VolumeId.$": "$.VolumeId", "Description": "Forensic snapshot - incident response" }, "End": true } } } ] },
"DetermineSeverity": { "Type": "Choice", "Choices": [ { "Variable": "$.Severity", "StringEquals": "CRITICAL", "Next": "NotifyCritical" } ], "Default": "NotifyStandard" },
"NotifyCritical": { "Type": "Task", "Resource": "arn:aws:states:::aws-sdk:sns:publish", "Parameters": { "TopicArn.$": "$.TopicArn", "Message": "CRITICAL incident processed - team paged" }, "End": true },
"NotifyStandard": { "Type": "Task", "Resource": "arn:aws:states:::aws-sdk:sns:publish", "Parameters": { "TopicArn.$": "$.TopicArn", "Message": "Standard incident processed - logged for review" }, "End": true },
"HandleError": { "Type": "Fail", "Error": "IncidentResponseFailed", "Cause": "Could not gather instance information" } }}Two input-handling details worth noting:
ResultPath controls where a task's output is merged into the state data (so GatherInstanceInfo adds InstanceInfo without clobbering the original input), and .$ on a field means "pull this value from the execution's JSON data" rather than using a literal.Create the state machine from the definition:
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
STATE_MACHINE_ARN=$(aws stepfunctions create-state-machine \ --name incident-response \ --definition file://incident-response.json \ --role-arn arn:aws:iam::${ACCOUNT_ID}:role/IncidentResponseRole \ --query 'stateMachineArn' --output text)The workflow exists. Now run it.
Running It and Reading the Result
The workflow needs a running instance to describe, tag, and snapshot. If you don't have a spare one, launch a throwaway. The AMI comes from a public SSM parameter so you never hardcode an image ID, and EC2 attaches a root EBS volume by default, which is what the snapshot step acts on:
# Launch a minimal instance from the latest Amazon Linux 2023 AMIINSTANCE_ID=$(aws ec2 run-instances \ --image-id resolve:ssm:/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64 \ --instance-type t2.micro \ --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=sfn-throwaway}]' \ --query 'Instances[0].InstanceId' --output text)
# Wait until it's running and its EBS volume is attachedaws ec2 wait instance-running --instance-ids "$INSTANCE_ID"echo "Launched $INSTANCE_ID"The final step publishes to SNS, so the topic in the input has to exist or the workflow fails at the notify state with
Sns.NotFoundException . Create one and capture its ARN:# Create the topic the workflow notifies; capture the ARN it returnsTOPIC_ARN=$(aws sns create-topic --name incidents \ --query 'TopicArn' --output text)echo "Topic ready: $TOPIC_ARN"To actually see the notification land, subscribe your email to the topic:
# Replace with your own email addressaws sns subscribe \ --topic-arn "$TOPIC_ARN" \ --protocol email \ --notification-endpoint you@example.comSNS sends a confirmation email to that address. Open it and click the confirm link before you run the workflow, otherwise the subscription stays pending and the published message never reaches your inbox.
Start an execution with input JSON. The keys here (
InstanceId , Severity , TopicArn ) are exactly the fields the definition reads via .$ :# Uses $INSTANCE_ID and $TOPIC_ARN captured aboveEXECUTION_ARN=$(aws stepfunctions start-execution \ --state-machine-arn "$STATE_MACHINE_ARN" \ --input '{"InstanceId":"'"$INSTANCE_ID"'","Severity":"CRITICAL","TopicArn":"'"$TOPIC_ARN"'"}' \ --query 'executionArn' --output text)
# Poll until the execution leaves the RUNNING statewhile true; do STATUS=$(aws stepfunctions describe-execution \ --execution-arn "$EXECUTION_ARN" --query 'status' --output text) echo "$(date +%H:%M:%S) $STATUS" [ "$STATUS" != "RUNNING" ] && break sleep 3doneThe execution history is the audit trail a script never gave you. Every state entry and exit is recorded with timestamps, inputs, and outputs, including the full
DescribeInstances response captured as GatherInstanceInfo 's output:aws stepfunctions get-execution-history --execution-arn "$EXECUTION_ARN"Run it again with
"Severity":"STANDARD" and the Choice state takes the other branch: same workflow, different path, no code change. That's the payoff. Branching and parallelism are declared in the definition and visible in the console graph, not buried in script control flow. The remaining decision is what kind of state machine to run it as.Standard vs Express, and Other Production Choices
When you create a state machine you choose a Type , Standard (default) or Express, and it's the choice that most shapes cost and behavior. Pick based on what the workflow does:
- Standard: exactly-once execution, durable, runs up to one year, with full execution history. Suited to non-idempotent actions like processing payments or orchestrating infrastructure, which is why our incident-response workflow is a Standard case.
- Express: at-least-once execution, up to five minutes, built for high-volume, short-duration event processing (think per-request processing at thousands of events per second). Cheaper at volume, but you handle idempotency.
As a rule of thumb: if the workflow touches money or needs an audit trail, use Standard; if it's high-frequency event handling, use Express.
Here are a few more patterns keep workflows production-grade:
- Prefer SDK integrations over Lambda glue. Every Task above called a service directly. Reach for Lambda only when you need custom logic the SDK can't express, not just to make an API call.
- Use Retry before Catch. Add a
Retryblock for transient failures (throttling, timeouts) so a blip doesn't fail the run, and letCatchhandle the genuinely unrecoverable path, asGatherInstanceInfodoes.
Cleaning Up
Tear down everything the walkthrough created so nothing lingers on the bill. These commands reuse the variables captured earlier (
$STATE_MACHINE_ARN , $INSTANCE_ID , $TOPIC_ARN ):# Delete the state machineaws stepfunctions delete-state-machine --state-machine-arn "$STATE_MACHINE_ARN"
# Remove the inline policy, then the execution roleaws iam delete-role-policy --role-name IncidentResponseRole --policy-name WorkflowActionsaws iam delete-role --role-name IncidentResponseRole
# Terminate the throwaway instance (its EBS volume is deleted with it)aws ec2 terminate-instances --instance-ids "$INSTANCE_ID"
# Delete the SNS topic (this also drops its email subscription)aws sns delete-topic --topic-arn "$TOPIC_ARN"The forensic snapshot the workflow created isn't tracked in a variable. List any snapshots tagged by the run and delete them if you don't want to keep them:
aws ec2 describe-snapshots --owner-ids self \ --filters "Name=description,Values=Forensic snapshot - incident response" \ --query 'Snapshots[].SnapshotId' --output text# aws ec2 delete-snapshot --snapshot-id <snap-id>Wrapping Up
Step Functions moves orchestration logic out of brittle scripts and into a state machine that remembers where it is, retries and catches failures declaratively, runs independent steps in parallel, and records every step for audit. You built that incident-response workflow end to end through direct AWS SDK integrations, with no Lambda to maintain.
The next step is to stop starting executions by hand. Wire this workflow to an EventBridge rule so a real signal, a GuardDuty finding or a CloudWatch alarm, triggers it automatically. At that point your runbook isn't a document someone follows under pressure; it's a workflow that runs itself.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article