Terraform调用Lambda初始化RDS集群报错:name 'user'未定义
1. Fix Lambda Handler to Use Event Payload
The most common cause of this error is that your Lambda code tries to access user as a top-level variable instead of extracting it from the incoming event payload. When invoking Lambda via Terraform, all input data is passed through the event parameter of your handler function.
Before (Hardcoded):
def lambda_handler(event, context): user = "hardcoded_user" # Direct variable assignment password = "hardcoded_pass" # ... rest of your DB user creation code
After (Use Event Data):
import json def lambda_handler(event, context): # Extract values from the event payload user = event.get("user") password = event.get("password") # Validate required fields exist if not user or not password: raise ValueError("Missing 'user' or 'password' in event payload") # ... rest of your DB user creation code
2. Ensure Terraform Sends Valid JSON Payload
Terraform's aws_lambda_invocation resource requires the payload argument to be a valid JSON string. If you pass raw values without serialization, the Lambda will receive malformed data.
Correct Terraform Configuration:
# Retrieve secrets from Secrets Manager data "aws_secretsmanager_secret_version" "db_user_creds" { secret_id = "your-secret-name" # Replace with your secret ID } # Invoke Lambda to create DB user resource "aws_lambda_invocation" "create_db_user" { function_name = aws_lambda_function.your_lambda_name.function_name # Serialize payload to JSON using jsonencode payload = jsonencode({ user = jsondecode(data.aws_secretsmanager_secret_version.db_user_creds.secret_string)["username"] password = jsondecode(data.aws_secretsmanager_secret_version.db_user_creds.secret_string)["password"] }) # Wait for RDS cluster to be ready before invoking depends_on = [aws_rds_cluster.your_rds_cluster] }
Key notes:
- Use
jsonencode()to convert the payload map into a valid JSON string. - Use
jsondecode()on the Secrets Manager secret string (stored as JSON) to extract username and password fields.
3. Verify Payload Structure in CloudWatch Logs
If the above fixes don't work, check your Lambda's CloudWatch Logs to inspect the actual event payload. Add this line to your handler to log the incoming data:
print(f"Received event: {json.dumps(event)}")
Navigate to CloudWatch → Logs → Log Groups → Your Lambda's log group to view the payload. If user or password are missing, adjust your Terraform configuration to match the expected keys.
4. Check for Typos in Payload Keys
Double-check that the keys in your Terraform payload exactly match what your Lambda code expects. For example, if your Lambda looks for event.get("username") but Terraform sends "user", you'll get the same undefined variable error.
内容的提问来源于stack exchange,提问作者Dave

