summaryrefslogtreecommitdiff
path: root/aws/lambda/terminate_citest_instances.py
blob: ddc4710c5f19f2af80af275137ef2ded3b63045e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Terminate all "citest*" instances after given interval so they
# don't keep running eating our budget
#
# see http://boto3.readthedocs.io/en/latest/guide/ec2-example-managing-instances.html
# for more boto examples.

import boto3
import pprint
from datetime import datetime, timezone, timedelta
import re

MAX_HOURS = 12


# Initialize PrettyPrinter
pp = pprint.PrettyPrinter(indent=2)


# Terminate after 12h
limit = timedelta(hours=MAX_HOURS)


def lambda_handler(event, context):

    now = datetime.now(timezone.utc)

    ec2 = boto3.client('ec2')
    response = ec2.describe_instances()

    reservations = response['Reservations']

    for reservation in reservations:
        instance=reservation['Instances'][0]
        id  = instance['InstanceId']

        # 'LaunchTime': datetime.datetime(2017, 6, 17, 16, 12, 50, tzinfo=tzutc()),
        launch = instance['LaunchTime']
        uptime = now - launch

        # Get instance tags
        tags_response = ec2.describe_tags(
            Filters=[{
                'Name': 'resource-id',
                'Values': [ id ],
            }])
        tags = tags_response['Tags']

        # Get instance node_name from tags
        node_name = ''
        for tag in tags:
            key = tag['Key']
            if key == 'node_name':
                node_name = tag['Value']
                break

        print(id + ': node_name=' + node_name + ', uptime=' + str(uptime), end='')

        if re.match(r'citest.*', node_name ):
            if (launch + limit) < now:
                print(', running longer than ' + str(MAX_HOURS) + 'h. TERMINATING.')
                response_terminate = ec2.terminate_instances( InstanceIds=[id] )
                pp.pprint(response_terminate['TerminatingInstances'])
                print()
            else:
                print(', running less than ' + str(MAX_HOURS) + 'h. Ignoring.')
        else:
            print(', not a citest instance. Ignoring.')


lambda_handler('test', 'test')