【发布时间】:2021-10-11 04:56:51
【问题描述】:
我是 python 和 AWS lambda 的新手。我正在尝试从 lambda 函数运行此脚本,但出现错误:
Runtime.HandlerNotFound
如果我从 ec2 实例运行此脚本,它可以正常工作,但是当我从 AWS lambda 运行相同的脚本时,它会引发错误。
如果有人指导我做错了什么,我将非常感激。
谢谢
import boto3
import requests
import time
AWS_Access_Key_ID =
AWS_Secret_Access_Key =
DELAY_TIME=10 # 10 Seconds
region = 'us-east-2'
# instances = ['']
instances = {
'instance id': 'http://link',
'instance id': 'http://link'
}
ec2 = None
try:
ec2 = boto3.client('ec2', aws_access_key_id=AWS_Access_Key_ID, aws_secret_access_key=AWS_Secret_Access_Key, region_name=region)
# ec2 = boto3.resource('ec2',aws_access_key_id=AWS_Access_Key_ID, aws_secret_access_key=AWS_Secret_Access_Key, region_name=region)
except Exception as e:
print(e)
print("AWS CREDS ERROR, Exiting...")
exit()
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("Not Live, retry time " + str(retry + 1))
print("Delaying request for " + str(DELAY_TIME) + " seconds...")
retry += 1
time.sleep(DELAY_TIME)
if(live):
print("Website is live")
# call function to start the ec2 instance
startInstances(x)
else:
# call function to stop the ec2 instance
print('Website is dead')
stopInstances(x)
print("")
def main():
check()
if __name__ == '__main__':
main()
【问题讨论】:
-
你能分享一下你的lambda的配置吗?没有它,就不可能知道为什么会出现此错误。
-
您的函数没有任何处理程序。您是否查看了有关如何在 python 中创建 lambda 函数的 aws 文档?顺便说一句,像这样硬编码凭证是一个非常糟糕的主意。
-
尝试在控制台中设置处理程序,下一个模式
file_name.function_name在您的情况下可能是file_name.main -
将 sleep 引入 lambda 函数是个坏主意。最好每秒运行一次函数,而不是让函数休眠一秒钟。
-
@ChristianDanielAvilaSanchez 感谢您的回复,现在我收到此错误,{“errorMessage”:“main() 接受 0 个位置参数,但给出了 2 个”,“errorType”:“TypeError”, "stackTrace": [" File \"/var/runtime/bootstrap.py\", line 127, in handle_event_request\n response = request_handler(event, lambda_context)\n" ] }
标签: python-3.x amazon-web-services amazon-ec2 aws-lambda