简体   繁体   English

在不活动的情况下以编程方式停止 AWS EC2

[英]Programmatically Stop AWS EC2 in case of inactivity

Can we stop an AWS windows server EC2 instance of a development environment when there is no activity in it, say after 2 hours of inactivity?我们可以在没有活动时停止开发环境的 AWS windows 服务器 EC2 实例吗,比如说在 2 小时不活动之后? I am having trouble identifying whether any user is connected to the server virtually.我无法确定是否有任何用户虚拟连接到服务器。

I can easily start/stop the EC2 at a fixed time, programmatically, but in order to cut the cost of my server, I am trying to stop the EC2 when it is not being used.我可以在固定时间以编程方式轻松启动/停止 EC2,但为了降低服务器成本,我试图在不使用时停止 EC2。

My intent(or use case) is : If no user is using the EC2 till a specified amount of time, it will automatically stop.我的意图(或用例)是:如果在指定的时间内没有用户使用 EC2,它将自动停止。 Developers can restart it as and when needed.开发人员可以在需要时重新启动它。

Easiest solution probably would be to set up an Alert with CloudWatch.最简单的解决方案可能是使用 CloudWatch 设置警报。

Have a read at the documentation , which basically describes your use case perfectly: 阅读文档,它基本上完美地描述了您的用例:

You can create an alarm that stops an Amazon EC2 instance when a certain threshold has been met您可以创建一个警报,在达到某个阈值时停止 Amazon EC2 实例

A condition could be the average CPU utilisation, eg CPU utilisation is below a certain point (which most probably correlates with no logged in users / no developer actually utilising the machine).一个条件可能是平均 CPU 利用率,例如 CPU 利用率低于某个点(这很可能与没有登录用户/没有开发人员实际使用机器有关)。

This is not a simple task.这不是一项简单的任务。

The Amazon EC2 service provides a virtual computer that has RAM, CPU and Disk. Amazon EC2 服务提供具有 RAM、CPU 和磁盘的虚拟计算机。 It can view the amount of activity on the CPU, Network traffic and disk access but it cannot see into the Operating System .它可以查看 CPU 上的活动量、网络流量和磁盘访问,但无法查看操作系统

So, the problem becomes how to detect 'inactivity' .所以,问题就变成了如何检测 'inactivity' This really comes down to the operating system and making some hard decisions.这实际上归结为操作系统并做出一些艰难的决定。 For example, your home computer screen turns off after a defined time of no mouse/keyboard input but the operating system is still doing activity in the background.例如,您的家庭计算机屏幕在定义的没有鼠标/键盘输入的时间后关闭,但操作系统仍在后台执行活动。 If the system is running an application such as a web server, and there are no web requests, it is hard to know whether this is 'inactive' because there are no requests, or 'active' because the web server is running.如果系统正在运行诸如 web 服务器之类的应用程序,并且没有 web 请求,则很难知道这是“不活动”,因为没有请求,还是“活动”,因为 Z2567A5EC9305EB7AC2C9840 服务器正在运行。

Bottom line: There is no out-of-the-box feature to do this.底线:没有开箱即用的功能可以做到这一点。 You would need to find your own definition of 'inactivity' and then trigger a shutdown in the Operating System.您需要找到自己对“不活动”的定义,然后在操作系统中触发关机。

If you wish to do it via schedule, this might help: Auto-Stop EC2 instances when they finish a task - DEV Community如果您希望按计划执行此操作,这可能会有所帮助: 当 EC2 实例完成任务时自动停止它们 - 开发社区

UPDATE: Lambda's aren't needed anymore, see tpschmidt's answer.更新:不再需要 Lambda,请参阅 tpschmidt 的回答。

Create a Lambda to turn off the EC2 that will be triggered by a Cloud Watch Alarm when for example the CPU goes under 20% average for an hour.创建一个 Lambda 以关闭将由 Cloud Watch 警报触发的 EC2,例如当 CPU 低于 20% 的平均值持续一小时时。 This is fine when you're coding as you will be using more than 20%, and when you have a break for over an hour that's when you want it turned off.这在您编码时很好,因为您将使用超过 20% 的电量,而当您休息一个多小时时,您希望将其关闭。

Be sure to set auto save in your IDE's.请务必在您的 IDE 中设置自动保存。

Example Python Lambda:示例 Python Lambda:

import boto3
region = 'eu-west-3'
instances = ['i-05be5c0c4039881ed']
ec2 = boto3.client('ec2', region_name=region)
def lambda_handler(event, context):
    #TODO getInstanceIDFromCloudWatch = event["instanceid"]
    ec2.stop_instances(InstanceIds=instances)
    print('stopped your instances: ' + str(instances))

Ref: https://www.howtoforge.com/aws-lambda-function-to-start-and-stop-ec2-instance/参考: https://www.howtoforge.com/aws-lambda-function-to-start-and-stop-ec2-instance/

In AWS Console:在 AWS 控制台中:

  1. Goto EC2, select the EC2 instance and copy the Instance ID转到 EC2,select EC2 实例并复制实例 ID

  2. Goto Cloud Watch and select Metrics Goto Cloud Watch 和 select 指标

  3. Under AWS Namespaces click EC2在 AWS 命名空间下单击 EC2

  4. Paste the Instance ID to find it粘贴实例 ID 以找到它

  5. Select EC2 > Per-Instance Metrics Select EC2 > 每个实例的指标

  6. Choose the first metric CPU utilisation选择第一个指标 CPU 利用率

  7. Select the second tab called Graphed Metric Select 第二个标签叫做Graphed Metric

  8. Click the Bell icon under Actions单击操作下的铃铛图标

  9. Set a threshold, also this is the hard part, leave the default of Statistic: Average over 1 hour设置一个阈值,这也是困难的部分,保留默认的统计:平均超过 1 小时

  10. Set the Condition Lower/Equal and put the value as 20% (you'll need to use the machine more than 1/5th of the hour over 20% CPU otherwise it'll turn off).设置 Condition Lower/Equal 并将值设置为 20%(您需要在超过 20% CPU 的情况下使用机器超过 1/5 小时,否则它将关闭)。

  11. Next create an alarm, setup a notification if you like or remove it接下来创建一个警报,如果你喜欢设置一个通知或删除它

  12. Once the Alarm is created创建警报后

  13. In Cloud Watch select Event > Rules在 Cloud Watch select 事件 > 规则

  14. Add a Rule添加规则

  15. Select EC2 as the Service Name and All Event Select EC2 作为服务名称和所有事件

  16. Click Target and select your Lambda.单击目标和 select 您的 Lambda。

  17. When the Alarm goes off the Lambda will turn off the instance ID当警报响起时,Lambda 将关闭实例 ID

You can set up an AWS Cloudwatch alarm that monitors activity.您可以设置监控活动的 AWS Cloudwatch 警报 Different parameters like ComparisonOperator, Period, and Threshold can be modified according to how you want to monitor your Ec2 instance. ComparisonOperator、Period 和 Threshold等不同的参数可以根据您想要监控 Ec2 实例的方式进行修改。

Then, you can set up an SQS queue and set a Python Lambda function as its target.然后,您可以设置一个 SQS 队列并设置一个 Python Lambda function 作为它的目标。 Within the lambda function, you can use boto3 to turn off the ec2 instance.在 lambda function 内,可以使用 boto3 关闭 ec2 实例。 You can read more details here: https://medium.com/geekculture/automatically-turn-off-ec2-instances-upon-inactivity-31fedd363cad您可以在此处阅读更多详细信息: https://medium.com/geekculture/automatically-turn-off-ec2-instances-upon-inactivity-31fedd363cad

Terraform setup: Terraform 设置:

https://medium.com/geekculture/terraform-setup-for-automatically-turning-off-ec2-instances-upon-inactivity-d7f414390800 https://medium.com/geekculture/terraform-setup-for-automatically-turning-off-ec2-instances-upon-inactivity-d7f414390800

You could do this very simply by combining a CloudWatch alarm with a Lambda function .您可以通过将CloudWatch 警报Lambda function组合来非常简单地做到这一点。

Start by creating a CloudWatch alarm to look at the metric(s) you're looking for, when this is met the alarm action would trigger your Lambda function.首先创建一个 CloudWatch 警报以查看您正在寻找的指标,当满足这一点时,警报操作将触发您的 Lambda function。 You would need decide what these conditions are so I would suggest that you look at the available metrics from within the AWS console.您需要确定这些条件是什么,因此我建议您查看 AWS 控制台中的可用指标。 If any metrics that you want to use you will need to look at creating a custom metric that you can have the instance add to CloudWatch.如果您想使用任何指标,您需要考虑创建一个自定义指标,您可以将实例添加到 CloudWatch。

Look at List the available CloudWatch metrics for your instances - Amazon Elastic Compute Cloud to get a comprehensive list of available metrics for your instance.查看列出您的实例的可用 CloudWatch 指标 - Amazon Elastic Compute Cloud以获取您的实例的可用指标的完整列表。

The Lambda function that gets triggered would then stop the instance that triggered the alarm.被触发的 Lambda function 将停止触发警报的实例。 To do this it would simply need to call the stop_instances function, this will be available in all SDKs.为此,只需调用stop_instances function,这将在所有 SDK 中可用。

You are looking for adding stop action to your ec2 instance, this can be easily achieved using CloudWatch alarms.您正在寻找向您的 ec2 实例添加停止操作,这可以使用 CloudWatch 警报轻松实现。 You can do this from the console using the following steps:您可以使用以下步骤从控制台执行此操作:

  1. Open the Amazon EC2 console打开Amazon EC2 控制台

  2. In the navigation pane, choose Instances .在导航窗格中,选择Instances

  3. Select the instance and choose Actions, Monitor and troubleshoot, Manage CloudWatch alarms . Select 实例并选择操作、监控和故障排除、管理 CloudWatch 警报

    Alternatively, you can choose the plus sign ( ) in the Alarm status column.或者,您可以在警报状态列中选择加号 ( )。

  4. On the Manage CloudWatch alarms page, do the following:管理 CloudWatch 警报页面上,执行以下操作:

    • Choose to Create an alarm .选择创建警报

    • To receive an email when the alarm is triggered, for Alarm notification , choose an existing Amazon SNS topic.要在触发警报时接收 email,对于警报通知,请选择现有的 Amazon SNS 主题。 You first need to create an Amazon SNS topic using the Amazon SNS console.您首先需要使用 Amazon SNS 控制台创建一个 Amazon SNS 主题。 For more information, see Using Amazon SNS for application-to-person (A2P) messaging in the Amazon Simple Notification Service Developer Guide.有关更多信息,请参阅 Amazon Simple Notification Service 开发人员指南中的使用 Amazon SNS 进行应用程序到个人 (A2P) 消息传递。

    • Toggle on the Alarm actio n, and choose Stop .切换警报操作,然后选择停止

    • For Group samples by and Type of data to sample , choose a statistic and a metric.对于Group samples byType of data to sample ,选择统计数据和指标。 In this example, choose Average and CPU utilization .在本例中,选择平均CPU 利用率

    • For Alarm When and Percent , specify the metric threshold.对于Alarm WhenPercent ,指定指标阈值。 In this example, specify <= and 10 percent.在此示例中,指定<=和 10%。

    • For the Consecutive period and Period , specify the evaluation period for the alarm.对于连续周期周期,指定警报的评估周期。 In this example, specify 1 consecutive period of 5 Minutes.在此示例中,指定 1 个连续的 5 分钟时段。

    • Amazon CloudWatch automatically creates an alarm name for you. Amazon CloudWatch 会自动为您创建警报名称。 To change the name, for the Alarm name , enter a new name.要更改名称,请为警报名称输入一个新名称。 Alarm names must contain only ASCII characters.警报名称必须仅包含 ASCII 字符。

    • Choose to Create.选择创建。

Note You can adjust the alarm configuration based on your own requirements before creating the alarm, or you can edit them later.说明 您可以在创建警报之前根据自己的需要调整警报配置,也可以稍后进行编辑。 This includes the metric, threshold, duration, action, and notification settings.这包括指标、阈值、持续时间、操作和通知设置。 However, after you create an alarm, you cannot edit its name later.但是,创建警报后,您以后无法编辑其名称。

Check this link from the documentation for terminating the instance using the same way.检查文档中的此链接以使用相同的方式终止实例。

You are looking for adding stop action to your ec2 instance, this can be easily achieved using CloudWatch alarms.您正在寻找向您的 ec2 实例添加停止操作,这可以使用 CloudWatch 警报轻松实现。

Here, I will show how to do that using Terraform :在这里,我将展示如何使用Terraform做到这一点:

    resource "aws_cloudwatch_metric_alarm" "ec2_cpu" {
    alarm_name                = "StopTheInstanceAfterInactivity"
    metric_name               = "CPUUtilization"
    comparison_operator       = "LessThanOrEqualToThreshold"
    statistic                 = "Average"
    threshold                 = var.threshold
    evaluation_periods        = var.evaluation_periods # The number of periods over which data is compared to the specified threshold
    period                    = var.period # Evaluation Period (seconds)
    namespace                 = "AWS/EC2"
    alarm_description         = "This metric monitors ec2 cpu utilization and stop the instance if it is inactive"
    actions_enabled           = "true"
    alarm_actions             = ["arn:aws:automate:${var.region}:ec2:stop"]
    ok_actions                = [] # do nothing
    insufficient_data_actions = [] # do nothing
    dimensions                = {InstanceId = aws_instance.ec2_instance.id}
}

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

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