【以下的问题经过翻译处理】 我在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))