简体   繁体   English

管理Amazon EC2实例

[英]Managing Amazon EC2 instances

I have started to use Amazon EC2 extensively and inorder to contain costs, I manually shutdown the instances before I leave work and bring them up when I come in. Sometimes I forget to shut them down. 我已经开始广泛使用Amazon EC2,并且为了控制成本,我在下班前手动关闭了实例,并在进来时将其启动。有时我忘记了关闭它们。 Is there a mechanism within the Amazon dashboard (or any other way) to automatically shut down the instances at say 6pm and bring them up at 6am? Amazon仪表盘内是否有一种机制(或其他方式)可在例如晚上6点自动关闭实例并在早上6点将其启动? I am happy to write scripts or programs if there are any API's available. 如果有可用的API,我很乐意编写脚本或程序。 If you have some code written already, it would be great if you can share. 如果您已经编写了一些代码,那么可以共享就很好了。

There are 2 solutions. 有2个解决方案。

AWS Data Pipeline - You can schedule the instance start/stop just like cron . AWS Data Pipeline-您可以像cron一样调度实例的启动/停止。 It will cost you one hour of t1.micro instance for every start/stop 每个启动/停止将花费您一个小时的t1.micro实例

AWS Lambda - Define a lambda function that gets triggered at a pre defined time. AWS Lambda-定义在预定时间触发的lambda函数。 Your lambda function can start/stop instances. 您的lambda函数可以启动/停止实例。 Your cost will be very minimal or $0 您的费用将非常低或$ 0

I used Data Pipeline for a long time before moving to Lambda. 在迁移到Lambda之前,我使用了Data Pipeline很长时间。 Data Pipeline is very trivial. 数据管道非常琐碎。 Just paste the AWS CLI commands to stop and start instances. 只需粘贴AWS CLI命令即可停止和启动实例。 Lambda is more involved. Lambda参与其中。

I actually happened to have a cron job running for this. 我实际上恰好为此运行了一个cron作业。 I'll put up my 'start instance' code here (for reference to get you started) 我将在此处放置“启动实例”代码(以供您入门参考)

#!/usr/bin/python

import boto.ec2
import boto
import boto.regioninfo
import time
import sys
import boto.ec2.connection
from boto.ec2 import EC2Connection
from boto.regioninfo import RegionInfo
from boto import ec2
from boto import regioninfo

ec2_region = ec2.get_region(aws_access_key_id='QWERTACCESSKEY', aws_secret_access_key='QWERTSECRETKEY', region_name='ap-southeast-2')
conn = boto.ec2.connection.EC2Connection(aws_access_key_id='QWERTACCESSKEY', aws_secret_access_key='QWERTSECRETKEY', region=ec2_region)

instance1 = conn.get_only_instances(instance_ids=['i-xxxxxxx1'])
instance2 = conn.get_only_instances(instance_ids=['i-xxxxxxx2'])
instance3 = conn.get_only_instances(instance_ids=['i-xxxxxxx3'])
instance4 = conn.get_only_instances(instance_ids=['i-xxxxxxx4'])

def inst():  # updates states of instances
        instance1[0].update()
        instance2[0].update()
        instance3[0].update()
        instance4[0].update()

def startservers():
        inst()
        if instance1[0].state in 'stopped':
            instance1[0].start()
        if instance2[0].state in 'stopped':
            instance2[0].start()
        if instance3[0].state in 'stopped':
            instance3[0].start()
        if instance4[0].state in 'stopped':
            instance4[0].start()

def check(): # a double check to make sure the servers are down
    inst()
    while instance1[0].state in 'stopped' or instance2[0].state in 'stopped' or instance3[0].state in 'stopped' or instance4[0].state in 'stopped':
        startservers()
        time.sleep(30)

startservers()
time.sleep(60)
check()

This is my cronjob 这是我的cronjob

31 8 * * 1-5 python /home/user/startaws

This runs at 8:31am from monday to friday. 此活动从星期一至星期五上午8:31进行。

Please Note This script works fine for me BUT it is definitely possible to make it much cleaner and simpler. 请注意,此脚本对我来说很好用,但是绝对有可能使它更加简洁。 There are also much better ways than this too. 还有比这更好的方法。 (I wrote this in a hurry so I'm sure I have some unnecessary lines of code in there) I hope it gives you an idea on how to start off :) (我急着写了这个,所以我确定里面有一些不必要的代码行)我希望它能给您一个入门的思路:)

If your use case permits terminating and re-launching, you might consider Scheduled Scaling in an Auto Scaling group. 如果您的用例允许终止并重新启动,则可以考虑在Auto Scaling组中使用Scheduled Scaling AWS recently added tools to manage scheduling rules in the Management Console UI. AWS最近添加了用于在管理控制台UI中管理调度规则的工具。

But I don't believe Auto Scaling will cover starting and stopping the same instance, preserving state. 但是我不相信Auto Scaling会涵盖启动和停止同一实例,并保持状态。

You don't need to write any scripts to achieve this, just use AWS console API. 您无需编写任何脚本即可实现此目的,只需使用AWS控制台API。 This is a perfect use case for AutoScaling with Scheduled Scaling. 这是带有计划扩展的AutoScaling的理想用例。 Steps: 脚步:

  1. Create a new Autoscaling group create a new autoscaling group . 创建一个新的Autoscaling组创建一个新的Autoscaling Example group: MY_AUTOSCALING_GROUP1 示例组:MY_AUTOSCALING_GROUP1
  2. In your case you need to create 2 new recurring schedules create new schedule . 在您的情况下,您需要创建2个新的定期计划,并创建新计划 Example: 例:

Scale up every morning 每天早晨放大

aws autoscaling put-scheduled-update-group-action --scheduled-action-name scaleup-schedule --auto-scaling-group-name MY_AUTOSCALING_GROUP1 --recurrence "0 6 * * *" --desired-capacity 5 aws autoscaling put-scheduled-update-group-action --scheduled-action-name scaleup-schedule --auto-scaling-group-name MY_AUTOSCALING_GROUP1 --recurrence“ 0 6 * * *”-所需容量5

Scale down every evening 每晚缩小

aws autoscaling put-scheduled-update-group-action --scheduled-action-name scaledown-schedule --auto-scaling-group-name MY_AUTOSCALING_GROUP1 --recurrence "0 18 * * *" --desired-capacity 0 AWS自动缩放–计划更新组操作–计划操作名称缩排计划–自动缩放组名称MY_AUTOSCALING_GROUP1 –重复执行“ 0 18 * * *”-所需容量0

5 EC2 instances will start every morning (6 AM) and terminate in evening (6 PM) everyday by applying above scheduled actions to your autoscaling group. 通过将上述计划的操作应用于您的自动伸缩组,每天早晨(6 AM)会开始有5个EC2实例,而在每天晚上(6 PM)会结束。

Can you just start with a simple solution like a cron job and AWS CLI? 您可以从简单的解决方案开始,例如cron作业和AWS CLI吗?

start.sh start.sh

# some preparations
# ...
$(aws ec2 start-instances --instance-ids $LIST_OF_IDS)
$(aws ec2 wait instance-running --instance-ids $LIST_OF_IDS)

stop.sh 停止

# some preparations
# ...
$(aws ec2 stop-instances --instance-ids $LIST_OF_IDS)
$(aws ec2 wait instance-stopped --instance-ids $LIST_OF_IDS)

Then crontab -e and add something like 然后crontab -e并添加类似

* 6 * * 1,2,3,4,5 start.sh
* 18 * * 1,2,3,4,5 stop.sh

Using AWS Lambda is definitely simple with scheduled event . 通过计划事件使用AWS Lambda绝对简单。 You can find the complete code script here 您可以在此处找到完整的代码脚本

For example, to start EC2 instances 例如,启动EC2实例

  1. From AWS Console , configure a lambda function AWS控制台配置lambda函数
  2. Copy following code to "Edit code inline" 将以下代码复制到“内联编辑代码”
 import boto3 def lambda_handler(event, context): client = boto3.client('ec2') response = client.start_instances( InstanceIds=[ 'i-xxxxxx', 'i-xxxxxx', ] ) print response 
  1. Give it basic execution role 赋予它基本的执行角色
 { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents", "ec2:StartInstances" ], "Resource": [ "arn:aws:logs:*:*:*", "arn:aws:ec2:*:*:*" ] } ] } 
  1. Click create lambda function and add Event Source (CloudWatch events - schedule) 单击创建lambda函数并添加事件源(CloudWatch事件-时间表)

  2. Finally, test your function to see if it work correctly 最后,测试您的功能以查看其是否正常运行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM