You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWS Lambda运行Python脚本报Runtime.HandlerNotFound错误求助

Lambda Runtime.HandlerNotFound 错误排查与修复

核心错误原因

Runtime.HandlerNotFound错误的本质是Lambda运行时找不到你配置的入口执行函数:

  • 本地/EC2运行Python脚本时,会执行if __name__ == '__main__'块下的代码触发逻辑,但Lambda不会识别这个触发规则,它要求你显式指定一个入口函数,格式为[代码文件名].[函数名]。
  • 你当前的代码中没有符合Lambda要求的入口函数定义,所以触发报错。

额外需要修复的兼容问题

除了入口函数的问题,你的代码还有几个和Lambda运行环境不兼容的点:

  • 硬编码AWS访问密钥:Lambda不需要在代码里写AK/SK,直接给Lambda执行角色配置对应权限即可,硬编码密钥有安全风险。
  • 缺少依赖:requests不是Lambda Python运行时的内置库,需要额外打包上传。
  • 缺少异常导入:代码中用到了ClientError但没有导入对应的模块。
  • 调用exit():Lambda运行环境中不要调用exit(),会导致函数异常终止。

具体修复步骤

1. 调整代码,添加入口函数

修改后的代码如下:

import boto3
import requests
import time
from botocore.exceptions import ClientError

DELAY_TIME=10 # 10 Seconds
region = 'us-east-2'
instances = {
  '替换为你的实例ID1': 'http://替换为你的链接1',
  '替换为你的实例ID2': 'http://替换为你的链接2'
}

# 自动使用Lambda执行角色的权限,无需硬编码密钥
ec2 = boto3.client('ec2', region_name=region)

def startInstances(instancesIds):
  if type(instancesIds) != list:  
    instancesIds = [instancesIds]
  try:
    response = ec2.start_instances(InstanceIds=instancesIds, DryRun=False)
    print(response)
    print("Instances Started")
  except ClientError as e:
    print(e)
    print("Instances Failed to Start")

def stopInstances(instancesIds):
  if type(instancesIds) != list:  
    instancesIds = [instancesIds]
  try:
    response = ec2.stop_instances(InstanceIds=instancesIds, DryRun=False)
    print(response)
    print("Instances Stopped")
  except ClientError as e:
    print(e)
    print("Instances Failed to Stop")

def check():
  for x in instances:
    retry = 0
    live = False
    print("Checking Webiste " + instances[x])
    while(retry < 5):
      try:
        r = requests.get(instances[x] ,verify=True)
        if r.status_code == 200:
          live = True
        break
      except: 
        print(f"Not Live, retry time {retry + 1}")
        print(f"Delaying request for {DELAY_TIME} seconds...")
        retry += 1
        time.sleep(DELAY_TIME)
    if live:
      print("Website is live")
      startInstances(x)
    else:
      print('Website is dead') 
      stopInstances(x)   
    print("")

# Lambda标准入口函数,必须保留event、context两个参数
def lambda_handler(event, context):
  check()

2. 匹配Lambda的handler配置

  • 把修改后的代码保存为lambda_function.py
  • 打开Lambda控制台的函数配置页,找到运行时设置,把handler参数配置为lambda_function.lambda_handler,和你代码的文件名、入口函数名保持一致。

3. 解决依赖问题

requests库不是Lambda默认内置的库,你可以选择两种方式解决:

  • 把requests库和代码一起打包成zip压缩包上传到Lambda
  • 给Lambda绑定已经打包好requests的Lambda层

4. 配置执行权限

给Lambda对应的执行角色添加以下权限,无需在代码中写密钥:

  • ec2:StartInstances
  • ec2:StopInstances
    资源范围指定为你需要操作的EC2实例ARN即可。

5. 调整超时配置

你的代码中重试等待的最长时间为50秒,把Lambda函数的超时时间调整到1分钟以上,避免函数还未执行完成就被强制终止。

其他注意事项

如果你要检测的网站部署在VPC内部,需要把Lambda函数挂载到对应VPC下,才能正常访问内网地址。

内容的提问来源于stack exchange,提问作者Mohsin Ijaz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 23:54:01