Created
August 24, 2018 15:11
-
-
Save bhalothia/cb070bcf58b0dc4c573f360be6c737e5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import print_function | |
import json | |
import boto3 | |
from datetime import datetime, timedelta | |
from dateutil.tz import tzlocal | |
print('INFO: Loading function') | |
DRY_RUN = True # Do not shut down instances | |
# Time (in seconds) after which the filtered instances must be terminated. | |
TERMINATE_AFTER_SECONDS = 21600 | |
ec2 = boto3.client('ec2') | |
def lambda_handler(event, context): | |
if DRY_RUN: | |
print('INFO: running in Dry Run mode, no action will be taken') | |
else: | |
print('INFO: All long-running gitlab-runner instances will be terminated') | |
now = datetime.now(tzlocal()) | |
now = now - timedelta(seconds=now.second, microseconds=now.microsecond) | |
print (now) | |
starttime = now - timedelta(seconds=TERMINATE_AFTER_SECONDS) | |
print (starttime) | |
terminate_instances = [] | |
active_instances = [] | |
describe_response = ec2.describe_instances( | |
Filters=[ | |
{'Name': 'instance-state-name', 'Values': ['running']}, | |
{'Name': 'tag:some-key', 'Values': ['some-value']} | |
] | |
) | |
for reservation in describe_response['Reservations']: | |
# Build the dimensions from the instances | |
for instance in reservation['Instances']: | |
instance_id = instance['InstanceId'] | |
instance_launch_time = instance['LaunchTime'] | |
if instance_launch_time < starttime: | |
terminate_instances.append(instance_id) | |
else: | |
active_instances.append(instance_id) | |
if not DRY_RUN and len(terminate_instances) > 0: | |
ec2.terminate_instances(InstanceIds=terminate_instances) | |
print('INFO: Terminated instances') | |
print(json.dumps({ | |
'active': active_instances, | |
'terminate': terminate_instances, | |
})) | |
lambda_handler(TERMINATE_AFTER_SECONDS, 21600) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment