TerraformPilot

Troubleshooting

Fix Terraform Step Functions - StateMachineAlreadyExists

Fix AWS Step Functions duplicate state machine errors in Terraform. Covers naming conflicts, import, definition updates, and versioning patterns.

LLuca Berton1 min read

Quick Answer

#

A Step Functions state machine with the same name already exists in the region. Import it into Terraform, use a unique name, or delete the orphaned state machine.

The Error

#
Error: creating Step Functions State Machine (order-processing):
  StateMachineAlreadyExists: State Machine Already Exists:
  'arn:aws:states:us-east-1:123456789012:stateMachine:order-processing'

What Causes This Error

#
  1. State machine created manually or by another Terraform workspace
  2. Previous failed apply — created in AWS but not recorded in state
  3. CloudFormation stack manages the same state machine

How to Fix It

#

Solution 1: Import the Existing State Machine

#
# Find the state machine ARN
aws stepfunctions list-state-machines \
  --query "stateMachines[?name=='order-processing'].stateMachineArn"
 
# Import using the ARN
terraform import aws_sfn_state_machine.order_processing \
  arn:aws:states:us-east-1:123456789012:stateMachine:order-processing

Solution 2: Use Unique Names

#
resource "aws_sfn_state_machine" "order_processing" {
  name     = "${var.project}-${var.environment}-order-processing"
  role_arn = aws_iam_role.step_functions.arn
 
  definition = jsonencode({
    StartAt = "ProcessOrder"
    States = {
      ProcessOrder = {
        Type     = "Task"
        Resource = aws_lambda_function.process_order.arn
        End      = true
      }
    }
  })
 
  tags = {
    Environment = var.environment
    ManagedBy   = "terraform"
  }
}

Solution 3: Delete the Orphaned State Machine

#
# Delete if no longer needed
aws stepfunctions delete-state-machine \
  --state-machine-arn arn:aws:states:us-east-1:123456789012:stateMachine:order-processing
 
# Then apply
terraform apply

Troubleshooting Checklist

#
  1. ✅ Does the state machine exist? (aws stepfunctions list-state-machines)
  2. ✅ Should you import or delete it?
  3. ✅ Are you using environment-prefixed names?
  4. ✅ Was a previous apply interrupted?

Prevention Tips

#
  • Use environment-prefixed namesmyapp-prod-order-processing
  • Import existing state machines before recreating
  • Tag with ManagedBy = "terraform" for easy identification
  • Use terraform state list to verify what's tracked
#

Conclusion

#

StateMachineAlreadyExists means the name is taken. Import the existing state machine or use environment-prefixed names to prevent collisions across workspaces.

#Terraform#AWS#Troubleshooting#Error Fix

Share this article