简体   繁体   中英

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). The Lambda function is being triggered by an AWS CloudWatch rule (specifically a schedule everyday at 6pm). 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.

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? Perhaps using boto3 code?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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