ruby-on-rails - 如何在启动后根据指定时间自动停止 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
有什么方法可以传递时间变量并基于此我可以执行适当的操作?
解决方案
#!/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))
推荐阅读
- sql - T-SQL: why sp_executesql requires it's parameters types?
- python - discord.py:交替“播放”状态不起作用,命令被禁用
- html - 按百分比更改图像高度不起作用
- math - 在网格螺旋上返回 X 或 Y 的公式,但只有方向改变?
- java - 为什么子方法在主方法中找不到符号?
- php - 无法接收从 Vue 通过 axios 发送到 PHP 的 Post 数据
- vb.net - 将未过滤的文本放入文本框中
- sharepoint - 如何根据文件名获取文档库中新上传文件的ID?PNP JS
- node.js - 如何将字符串添加到集合中的数组 | MongoDB | 节点JS
- algorithm - 查找单链表的第 k 个最后一个元素:答案解释