如何在AWS Lambda(Python)中调用SSM send_command?无响应排查
Hey there! Let's dig into why your Lambda isn't triggering the SSM document successfully—your hunch about the Targets parameter being null is spot-on. SSM needs explicit instructions on which instances to target, so leaving that as null will result in no action at all. Here's how to fix this and rule out other common issues:
1. Fix the Targets Parameter for Your Tagged Instance
Since you have an EC2 instance tagged Backup=db, use that tag to target it directly in your send_command call. Here's a complete Python 2.7 Lambda example using boto3:
import boto3 def lambda_handler(event, context): # Initialize SSM client ssm = boto3.client('ssm') try: # Send command to instances tagged Backup=db command_response = ssm.send_command( DocumentName='YOUR_SSM_DOCUMENT_NAME', # Replace with your actual document name Targets=[ { 'Key': 'tag:Backup', 'Values': ['db'] } ], # Uncomment and update below if your document requires input parameters # Parameters={ # 'YourParameterKey': ['YourParameterValue'] # }, TimeoutSeconds=3600 ) print(f"Command sent successfully! Command ID: {command_response['Command']['CommandId']}") return { 'statusCode': 200, 'body': f"Success! Command ID: {command_response['Command']['CommandId']}" } except Exception as e: print(f"Failed to send command: {str(e)}") return { 'statusCode': 500, 'body': f"Error: {str(e)}" }
2. Verify Lambda IAM Permissions
Your Lambda execution role needs permissions to interact with SSM and EC2. At minimum, attach this policy to the role (you can narrow down resources later for tighter security):
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "ssm:SendCommand", "ssm:GetCommandInvocation" ], "Resource": "*" }, { "Effect": "Allow", "Action": "ec2:DescribeInstances", "Resource": "*" } ] }
3. Check Target Instance Health
Even with correct code and permissions, the instance might not be reachable by SSM:
- SSM Agent Status: On the EC2 instance, run
sudo status amazon-ssm-agentto confirm it's running. If not, start it withsudo start amazon-ssm-agent. - IAM Role for EC2: The instance must have the
AmazonEC2RoleforSSMmanaged role attached—this allows it to communicate with the SSM service. - Network Access: Ensure the instance has outbound HTTPS access to
ssm.<your-region>.amazonaws.com(check security groups and network access control lists).
4. Debug with CloudWatch Logs
If you still get no response, check your Lambda's CloudWatch Logs. Look for errors like:
AccessDeniedException: Missing permissions in the Lambda role.InvalidInstanceId: The target instance isn't registered with SSM.NoInstancesFound: The tag filter didn't match any active instances.
内容的提问来源于stack exchange,提问作者Mark J. Bobak

