安排启动EC2实例并在其中运行python脚本 [英] Schedule to start an EC2 instance and run a python script within it

查看:123
本文介绍了安排启动EC2实例并在其中运行python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在AWS中安排python脚本,但是我不希望实例一直运行。因此,尝试自动化以下过程:

I am trying to schedule my python script in AWS, however I don't want the instances to be running all the time. So, trying to automate the process of:


  1. 在特定时间启动EC2实例

  2. 在其中运行python脚本

  3. 作业完成后,停止EC2实例。

我无法将此脚本直接作为Lambda函数运行,因为该脚本会执行一些并行处理,而这需要更多RAM,因此请选择更大的AWS实例,而不是将其编写为Lambda函数。另外,不要因为这个实例昂贵而一直不让它一直运行。

I cannot run this script directly as a Lambda function because the script does some parallel processing which requires more RAM, so choosing a bigger AWS instance rather than writing it as a lambda function. Also, don't want this instance to be running all the time as it is expensive.

到目前为止,我关注了使用Lambda和CloudWatch·matoski.com 自动启动和停止AWS EC2实例,并创建了Lambda函数来在特定时间启动和停止实例,但是我找不到运行方法。实例启动后,就使用python脚本。

So far, I followed Automatic starting and stopping of AWS EC2 instances with Lambda and CloudWatch · matoski.com and created a Lambda function to start and stop the instance at specific time, however I couldn't find a way to run the python script once the instance is started.

有人可以指出正确的方向吗?

Can anyone point me in the right direction?

推荐答案

MY应用程序每天(美国东部时间)13:39运行一个实例,并在处理完成后自行关闭。它在下面使用

MY application runs an instance @ 13:39 UST everyday and self shuts down after processing is complete. It uses below


  1. 使用云监视事件规则的预定lambda函数

云监视事件/规则配置


  1. 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


  1. 这会触发一个实例,该实例的cron运行到执行Python脚本

  1. This triggers an instance which has a cron running to execute Python script

@reboot python /home/Init.py

@reboot python /home/Init.py

一旦脚本完成,p ython作业会使用以下代码段自行关闭

Once script completes, python job shuts down itself using below snippet

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])

这篇关于安排启动EC2实例并在其中运行python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆