我正在尝试在 AWS 中安排我的 python 脚本,但我不希望实例一直运行。因此,尝试使以下过程自动化:
- 在特定时间启动 EC2 实例
- 运行里面的python脚本
- 作业完成后停止 EC2 实例。
我不能直接将此脚本作为 Lambda 函数运行,因为该脚本执行一些需要更多 RAM 的并行处理,因此选择更大的 AWS 实例而不是将其编写为 Lambda 函数。此外,不希望此实例一直运行,因为它很昂贵。
到目前为止,我关注了Automatic starting and stopping of AWS EC2 instances with Lambda and CloudWatch · matoski.com并创建了一个 Lambda 函数来在特定时间启动和停止实例,但是我找不到在实例启动后运行 python 脚本的方法。
谁能指出我正确的方向?
最佳答案
我的应用程序每天在美国标准时间 13:39 运行一个实例,并在处理完成后自行关闭。它在下面使用
- 使用云监视事件规则的计划 lambda 函数
Cloud watch Event/rules config
- lambda 触发器将启动一个实例(带有硬编码 ID)
import boto3
def lambda_handler(event, context):
ec2 = boto3.client('ec2', region_name='ap-south-1')
ec2.start_instances(InstanceIds=['i-xxxxxxx'])
print('started your instances: ' + str('i-xxxxxx'))
return
这会触发一个实例,该实例有一个 cron 正在运行以执行 Python 脚本
@reboot python/home/Init.py
脚本完成后,python 作业会使用以下代码段自行关闭
import boto.ec2
import boto.utils
import logging
logger=logging.getLogger()
def stop_ec2():
conn = boto.ec2.connect_to_region("ap-south-1") # or your region
# Get the current instance's id
my_id = boto.utils.get_instance_metadata()['instance-id']
logger.info(' stopping EC2 :'+str(my_id))
conn.stop_instances(instance_ids=[my_id])
关于python - 安排启动 EC2 实例并在其中运行 python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49622575/