当我通过Lambda函数向EC2发送运行命令时,Python脚本应该运行超过一小时,但实际上只运行了一小时,为什么呢?

0

【以下的问题经过翻译处理】 我在EC2(t2.xlarge,Amazon Linux 2)中有一个简单的test.py Python脚本(见下文)。 我使用VSCode连接EC2进行测试/调试。

当我通过VSCode或通过linux终端(sudo python3 /home/ec2-user/tmp/test.py)运行此代码时,该代码一直运行到最后

但是,当我使用lambda发送相同的执行命令时,此代码会在1小时后停止运行(没有python3任务运行)! 我希望它能够持续运行超过1个小时!

我的目标是通过lambda向EC2发送命令行来运行我的python脚本,并确保脚本运行到最后。

test.py

import logging
from time import sleep

logging.basicConfig(filename="/home/ec2-user/tmp/test.log",
                    format='%(asctime)s %(message)s',
                    filemode='w')
logger = logging.getLogger()
logger.setLevel(logging.INFO)
var= True
count = 0
while var==True:
    logger.info('=)')
    sleep(1)
    count+=1
    if count>100000:
        var=False

lambda function

import json
import boto3

comand_shell    = 'sudo python3 /home/ec2-user/tmp/test.py' 
instance_id_ec2  = 'my_ec2_instance_id'

def lambda_handler(event, context):
    client = boto3.client("ec2")
    ssm = boto3.client("ssm")
    
    try:
        describeInstance = client.describe_instances()
        for r in describeInstance['Reservations']:
            for inst in r['Instances']:
                if inst['InstanceId'] == instance_id_ec2:
                    status = inst['State']['Name']
        if status == 'running': 
            response = ssm.send_command(
                InstanceIds=[instance_id_ec2],
                DocumentName="AWS-RunShellScript",
                Parameters={"commands": [comand_shell]},
                )
            print(f'{comand_shell } has sent to {instance_id_ec2} successfuly')
        else:
            print(f'Failed')
    except Exception as e:
        print("Unexpected Exception: %s" % str(e))
profile picture
专家
已提问 5 个月前32 查看次数
1 回答
0

【以下的回答经过翻译处理】 ssm运行命令有默认超时时间根据文档。您可以在提交请求时更改默认值。在re:Post上也有一些关于此的简短讨论

profile picture
专家
已回答 5 个月前

您未登录。 登录 发布回答。

一个好的回答可以清楚地解答问题和提供建设性反馈,并能促进提问者的职业发展。

回答问题的准则