【发布时间】:2021-02-20 05:42:24
【问题描述】:
首先,我对 AWS 还是很陌生,我经过大量试验和错误后才让我的 lambda 函数执行我的 python 脚本,该脚本位于 ec2 实例上。
如果我在我的 ec2 实例中通过命令行手动运行我的代码,代码可以完美运行,它会调用请求的 api 并保存数据。
如果我使用 ssh 通过 lambda 函数调用我的脚本,它会在 api 调用时停止执行,lamda 返回一切都运行了,但它没有,我没有返回输出消息说有异常,什么都没有在 cloudwatch 日志中。我知道它开始执行我的代码,因为如果我在 api 调用之前放置打印语句,我会看到它们在 cloudwatch 日志中返回。
任何帮助菜鸟的想法。
这是我的 lambda 代码:
import time
import boto3
import json
import paramiko
def lambda_handler(event, context):
ec2 = boto3.resource('ec2', region_name='eu-west-2')
instance_id = 'removed_id'
instance = ec2.Instance(instance_id)
# Start the instance
instance.start()
s3_client = boto3.client('s3')
# Download private key file from secure S3 bucket
# and save it inside /tmp/ folder of lambda event
s3_client.download_file('removed_bucket', 'SSEC2.pem',
'/tmp/SSEC2.pem')
# Allowing few seconds for the download to complete
time.sleep(2)
# Giving some time to start the instance completely
time.sleep(60)
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
privkey = paramiko.RSAKey.from_private_key_file('/tmp/SSEC2.pem')
# username is most likely 'ec2-user' or 'root' or 'ubuntu'
# depending upon your ec2 AMI
ssh.connect(
instance.public_dns_name, username='ec2-user', pkey=privkey
)
print('Executing')
stdin, stdout, stderr = ssh.exec_command(
'/home/ec2-user/miniconda3/bin/python /home/ec2-user/api-calls/main.py')
stdin.flush()
data = stdout.read().splitlines()
for line in data:
print(line)
ssh.close()
# Stop the instance
# instance.stop()
return {
'statusCode': 200,
'body': json.dumps('Execution successful ' )
}
编辑: 好的,轻微的更新,它不会在 api 调用上失败,它实际上是在尝试打开一个写入的配置文件时停止,该文件存储在“config/config.json”中。现在很明显,当我手动执行时,这在 ec2 环境中有效,所以如果作业是从其他地方触发的,这一定与 ec2 中的环境变量不一样有关?这是确切的代码:
@staticmethod
def get_config():
with open("config/config.json", "r") as read_file:
data = json.load(read_file)
return data
【问题讨论】:
-
这能回答你的问题吗:stackoverflow.com/questions/3215727/…
-
感谢 Hussain,一旦尝试在 python 中进行 api 调用,代码仍然会退出。有趣的是,通过使用您的建议,我确实得到了一个返回的错误代码 1,但这就是我得到的全部,没有实际的错误要筛选,很奇怪。
标签: python amazon-web-services aws-lambda