简体   繁体   English

延迟从 Lambda 停止 AWS EC2 实例,直到用户处于非活动状态

[英]Delay Stopping AWS EC2 Instance from Lambda until User is Inactive

I am using a simple AWS Lambda function to stop EC2 instances given a region and instance IDs (see python code below).我正在使用一个简单的 AWS Lambda 函数来停止给定区域和实例 ID 的 EC2 实例(请参阅下面的 python 代码)。 The Lambda function is being triggered by an AWS CloudWatch rule (specifically a schedule everyday at 6pm). Lambda 函数由 AWS CloudWatch 规则触发(特别是每天下午 6 点的时间表)。 This has all been tested and works.这一切都已经过测试和工作。

import boto3
def lambda_handler(event, context):
    region = event.get('region')
    instances = event.get('instances')
    ec2 = boto3.client('ec2', region_name=region)
    ec2.stop_instances(InstanceIds=instances)
    print 'started your instance: ' + str(instances)

If a user is actively logged into the EC2 instance and the function is triggered, the EC2 instance will force shutdown the instance.如果用户主动登录到 EC2 实例并触发该功能,则 EC2 实例将强制关闭该实例。

So, is there a way (either in CloudWatch or Lambda) to delay and/or ignore the shutdown until either the user is inactive or totally logged out?那么,有没有办法(在 CloudWatch 或 Lambda 中)延迟和/或忽略关闭,直到用户处于非活动状态或完全注销? Perhaps using boto3 code?也许使用 boto3 代码?

UPDATE:更新:

Considered using a waiter, but the only one I could find waits until the instance is in use, as opposed to not in use.考虑过使用服务员,但我能找到的唯一一个等待实例被使用,而不是未被使用。 Perhaps there is a wait for that?也许需要等待? Also considered CloudWatch alarms, which works for stopping an instance after a period of inactivity, but not for triggering at an exact time.还考虑了 CloudWatch 警报,它适用于在一段时间不活动后停止实例,但不适用于在准确时间触发。

waiter = ec2.get_waiter('volume_in_use')
waiter.wait(
    WaiterConfig={
    'Delay': 900, # In Seconds (900 = 15 mins)
    'MaxAttempts': 47 # Number of Attempts (47 = 11.75 hours)
    }
) # Default wait is 15 seconds 40 times

Lambda can utilize SSM Run command to check if anyone is logged in locally before initiating the shutdown. Lambda 可以使用 SSM Run 命令在启动关闭之前检查是否有人在本地登录。

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

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