EC2是AWS的虚拟主机。 比较常见的EC2的计费方式是按照实际使用时间计费。如果一个主机只需要每天白天使用10个小时,那么这个主机的费用将节省差不多50%。(停机的时候也会收取EBS磁盘的费用)
为了达到这个目的,需要让AWS每天早上执行一个定时任务,将符合条件的EC2筛选出来,并对这些EC2执行启动操作;每天晚上执行一个定时任务,将符合条件的EC2筛选出来,并对这些EC2执行关闭操作。
AWS的Lambda和CloudWatch Event满足的要求,但是对于大部分用户,配置Lambda和CloudWatch Event都存在一定的困难,为此我们准备了专门的CloudFormation自动化脚本。
特别需要指出的是,由于代码的原因,这个CloudFormation堆栈需要在东京区域创建。模板的地址是:
https://s3.awstweaker.com.s3-ap-northeast-1.amazonaws.com/onekey/EC2/managerEC2.json
参考下图,可以在创建堆栈的过程中通过参数配置所在的时区,希望的EC2启动和停止时间(本地时间),以及希望自动启停的EC2范围(EC2上的标记名称以及标记的Name)。
默认的选项表示,希望在北京时间早上8:00自动启动所有已经做了名为"Online"的tag,且该Tag的值为" DayofBeijingTime"的EC2实例,并在北京时间晚上22:00关闭这些实例。和其他的模板一样,依次点击下一步,同意创建IAM角色,大概1分钟后,所有的资源创建成功,自动启停的任务就部署成功了。
如附图所示在CloudWatch的界面可以看到相应的启动和停止规则。
最后,如果想调整自动启停的EC2的范围,只需要给EC2增加或者删除相应的标记就可以了。
EC2 is AWS's virtual server. The most common EC2 billing method charges based on actual usage time. If a server only needs to be used for 10 hours during the day, the cost can be saved by approximately 50%. (EBS disk charges still apply when stopped)
To achieve this, AWS needs to execute a scheduled task every morning to filter out qualifying EC2 instances and start them; and execute a scheduled task every evening to filter out qualifying EC2 instances and stop them.
AWS Lambda and CloudWatch Events meet these requirements, but for most users, configuring Lambda and CloudWatch Events presents certain difficulties. Therefore, we have prepared a dedicated CloudFormation automation script.
It should be noted that due to code reasons, this CloudFormation stack needs to be created in the Tokyo region. The template URL is:
https://s3.awstweaker.com.s3-ap-northeast-1.amazonaws.com/onekey/EC2/managerEC2.json
As shown in the figure below, during stack creation, you can configure the timezone, desired EC2 start and stop times (local time), and the scope of EC2 instances for automatic start/stop (tag name and tag value on EC2) through parameters.
The default options indicate that you want to automatically start at 8:00 AM Beijing time all EC2 instances tagged with "Online" and tag value "DayofBeijingTime", and stop these instances at 10:00 PM Beijing time. Like other templates, click Next sequentially, agree to create IAM roles, and after about 1 minute, all resources are created successfully, and the automatic start/stop task is deployed successfully.
As shown in the figure, you can see the corresponding start and stop rules in the CloudWatch interface.
Finally, if you want to adjust the scope of EC2 instances for automatic start/stop, simply add or remove the corresponding tags from the EC2 instances.