首页 > 解决方案 > 如何在启动后根据指定时间自动停止 EC2 实例?

问题描述

我知道如何使用 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

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

标签: ruby-on-railsamazon-web-servicesamazon-ec2

解决方案


#!/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))
   		


推荐阅读