Python Lambda调用Step Functions StartExecution传递提取变量时遇InvalidExecutionInput错误的问题咨询
Let's break down what's going wrong here and how to fix it quickly.
The Root Cause
When you use str() to convert a Python dictionary to a string, it uses single quotes for keys and string values—like this:
str({"filename": "test.txt"}) # Output: "{'filename': 'test.txt'}"
But Step Functions requires valid JSON for the input parameter, which strictly uses double quotes for all keys and string values. The single quotes in your generated string are causing the InvalidExecutionInput error you're seeing.
The Correct Approach
Instead of str(), use Python's built-in json module to serialize your dictionary into a properly formatted JSON string. Here's how to adjust your code:
- First, import the
jsonmodule at the top of your Lambda function:
import json import boto3 # Initialize your Step Functions client step_function = boto3.client('stepfunctions')
- Rewrite your
start_executioncall to usejson.dumps()instead ofstr():
# Build your input data as a regular Python dictionary input_data = { "filename": filename, "filetype": filetype, "unixtimestamp": unixtimestamp, "masterclient": masterclient, "source_bucket_name": source_bucket_name, "destination_bucket_name": destination_bucket_name, "filekey": filekey, "this is a test string": "teststring" } # Serialize to valid JSON string response = step_function.start_execution( stateMachineArn=state_machine_zip_files_arn, input=json.dumps(input_data) )
Key Notes
- You don't need to use f-strings like
f"{filename}"unless you're explicitly formatting a non-string value (e.g., converting an integer to a string). If your variables are already strings, just pass them directly into the dictionary. json.dumps()handles all the JSON formatting rules automatically: double quotes, escaping special characters, and serializing only JSON-compatible data types (strings, numbers, lists, dictionaries, booleans,None).- Make sure all your variables (like
filename,filetype, etc.) are JSON-serializable. If you have any Python-specific objects (like datetime objects), you'll need to convert them to strings or numbers first before passing tojson.dumps().
Bonus: Debugging Tip
If you want to verify the JSON output before sending it, you can print it in your Lambda logs:
print("Generated input JSON:", json.dumps(input_data))
This will let you confirm the string uses double quotes and is properly formatted.
内容的提问来源于stack exchange,提问作者user13067694

