Can you write a python script that re-executes failed step-functions workflows? This script will use argparse to read parameters, will then fetch all the failed workflows, retrieve their inputs and names and then re-execute them by using the same input as the original workflow and the same name but adding a "retry" suffix at the end.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Below is a Python script that uses argparse for parameter input, boto3 to interact with AWS Step Functions, and re-executes failed workflows as per your requirements. Please ensure you have argparse, boto3, and the necessary AWS credentials set up (e.g., via ~/.aws/credentials or IAM roles if running on an EC2 instance) before running this script.
python
import argparse
import boto3
from botocore.exceptions import ClientError
def parse_args():
"""Parse command line arguments."""
parser = argparse.ArgumentParser(description='Re-executes failed Step Functions workflows.')
parser.add_argument('--state-machine-arn', required=True, help='ARN of the State Machine')
parser.add_argument('--max-results', type=int, default=100, help='Maximum number of results to return per page (default: 100)')
parser.add_argument('--retry-suffix', default='-retry', help='Suffix to append to the original execution name for retries (default: "-retry")')
return parser.parse_args()
def get_failed_executions(sfn_client, state_machine_arn, max_results):
"""
Fetch failed executions for the given State Machine, handling pagination.
:param sfn_client: Step Functions client
:param state_machine_arn: ARN of the State Machine
:param max_results: Maximum results per page
:return: List of failed executions
"""
failed_executions = []
next_token = None
while True:
try:
if next_token:
response = sfn_client.list_executions(
stateMachineArn=state_machine_arn,
statusFilter='FAILED',
maxResults=max_results,
nextToken=next_token
)
else:
response = sfn_client.list_executions(
stateMachineArn=state_machine_arn,
statusFilter='FAILED',
maxResults=max_results
)
failed_executions.extend(response['executions'])
next_token = response.get('nextToken')
# Exit loop if no more pages
if not next_token:
break
except ClientError as e:
print(f"Failed to retrieve executions: {e}")
break
return failed_executions
def get_execution_input(sfn_client, execution_arn):
"""Retrieve the input of a given execution."""
try:
response = sfn_client.describe_execution(executionArn=execution_arn)
return response.get('input', "")
except ClientError as e:
print(f"Failed to retrieve input for {execution_arn}: {e}")
return ""
def can_re_execute(sfn_client, state_machine_arn):
"""Check if the State Machine is in a valid state for re-execution."""
try:
response = sfn_client.describe_state_machine(stateMachineArn=state_machine_arn)
status = response.get('status')
return status == 'ACTIVE'
except ClientError as e:
print(f"Failed to check State Machine status: {e}")
return False
def re_execute_workflow(sfn_client, state_machine_arn, original_execution_name, execution_input, retry_suffix):
"""Re-executes a workflow with the original input and a modified name."""
new_execution_name = f"{original_execution_name}{retry_suffix}"
try:
response = sfn_client.start_execution(
stateMachineArn=state_machine_arn,
input=execution_input,
name=new_execution_name
)
print(f"Successfully re-executed {original_execution_name} as {new_execution_name}: {response['executionArn']}")
except ClientError as e:
print(f"Failed to re-execute {original_execution_name} as {new_execution_name}: {e}")
def main():
args = parse_args()
sfn_client = boto3.client('stepfunctions')
# Check if the State Machine is valid for re-execution
if not can_re_execute(sfn_client, args.state_machine_arn):
print(f"State Machine {args.state_machine_arn} is not in an ACTIVE state. Exiting.")
return
failed_executions = get_failed_executions(sfn_client, args.state_machine_arn, args.max_results)
for execution in failed_executions:
execution_arn = execution['executionArn']
execution_name = execution['name']
execution_input = get_execution_input(sfn_client, execution_arn)
if execution_input:
re_execute_workflow(sfn_client, args.state_machine_arn, execution_name, execution_input, args.retry_suffix)
else:
print(f"Skipping {execution_name} due to missing input.")
if __name__ == "__main__":
main()
How to Use:
Install Requirements:
If not already installed, run pip install boto3 (ensure you have the latest boto3).