当我通过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
EXPERTE
gefragt vor 5 Monaten35 Aufrufe
1 Antwort
0

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

profile picture
EXPERTE
beantwortet vor 5 Monaten

Du bist nicht angemeldet. Anmelden um eine Antwort zu veröffentlichen.

Eine gute Antwort beantwortet die Frage klar, gibt konstruktives Feedback und fördert die berufliche Weiterentwicklung des Fragenstellers.

Richtlinien für die Beantwortung von Fragen