【问题标题】:How can i stop EC2 instance automatically after launching , based on specified hour?如何在启动后根据指定时间自动停止 EC2 实例?
【发布时间】:2018-12-06 20:29:05
【问题描述】:

我知道如何使用 Ruby sdk 启动和停止 ec2 实例。现在我需要在启动 ec2 实例后根据小时参数自动关闭? 我怎么解决这个问题?请提供一些有用的参考。

   #disconnecting EC2 Instance 
   def disconnect_group_instance
        if current_user.present?
          server_instance = GroupUserInstance.find_by_group_user_id(params[:id])
           ec2 = Aws::EC2::Client.new
           resp = ec2.stop_instances({
           dry_run: false,
           instance_ids: [server_instance.server_id],
           force: false
         })
       end
   end

有什么方法可以传递时间变量并基于此我可以执行适当的操作?

【问题讨论】:

  • 我不太明白你的要求,但这是否可以通过 lambda 解决?每小时关闭一次服务器?
  • 感谢@George Appleton 的回复。实际上我正在寻找 api 调用,因为我的时间段是用户定义的。(可能是 200 小时、300 小时等等)。根据时间段,我需要自动关闭 ec2 实例。
  • aws api 应该能够轻松处理 docs.aws.amazon.com/cli/latest/reference/ec2/… docs.aws.amazon.com/AWSEC2/latest/APIReference/… 有两个链接应该有所帮助。您应该能够让实例自行关闭。但是,如果您遇到问题,另一种方法是让 lambda 端点每隔 x 时间段查询您的 ec2 实例 api,并在某些响应时关闭 ec2 实例。

标签: ruby-on-rails amazon-web-services amazon-ec2


【解决方案1】:

#!/usr/bin/python
import os
import json
import boto3

#python script to turn off the list of vms using lambda on daily/hourly basis

'''
event = {
	"topic_arn": "arn:aws:sns:ap-southeast-1:aws-account_id:sns_topic",
	"instance_id": "i-0fbaf00d222f6f765",
	"action": "stop",
	"region": "ap-southeast-1"
}
'''

#arguments can be passed through cloudwatch event which triggers lambda function or through lambda environment variables

def lambda_handler(event, context):	
	topic_arn = event['topic_arn']
	instance_id = event['instance_id']
	action = event['action']
	region = event['region']

	subject = instance_id
	ec2_client = boto3.client('ec2')
	sns_client = boto3.client('sns')
	message = { "topic_arn" : topic_arn, "instance" : instance_id }
	
	def stop_instance(instance_id):
		stop_instance = ec2_client.stop_instances(InstanceIds=[instance_id,],Force=True)
		message['status'] = 'stopped'
		send_notification(topic_arn, subject, message)
		return message
	def start_instance(instance_id):
		start_instance = ec2_client.start_instances(InstanceIds=[instance_id,])
		message['status'] = 'started'
		send_notification(topic_arn, subject, message)
		return message
	def send_notification(topic_arn, subject, message):
		publish = sns_client.publish(   TopicArn=topic_arn, \
    									Message=json.dumps(message), \
    									Subject=subject \
    								)
	if action == 'stop':
		return(stop_instance(instance_id))
		
	else:
   		return(start_instance(instance_id))
   		

【讨论】:

  • 我需要使用 ruby​​ sdk 进行 api 调用,就像我在上面的问题中提到的那样。我不想为此使用 lambda 函数。如果 api 不可用,有什么办法吗?
  • 理想情况下,您需要一个作业调度程序或事件驱动源来完成此操作。如果你没有找到任何 api。您可以安排一个 cron 作业以在每天凌晨 12:00 轮询 vm thru bash/ruby/python 脚本的正常运行时间。如果达到所需的时间,您可以执行 halt/init 0 命令自行停止虚拟机。
  • @NeerajAmoli lambda 顺便支持 ruby​​
猜你喜欢
  • 2020-04-23
  • 1970-01-01
  • 1970-01-01
  • 2018-08-15
  • 2011-10-29
  • 2013-12-18
  • 2017-01-07
  • 2022-11-18
  • 1970-01-01
相关资源
最近更新 更多