Last active
December 10, 2015 15:28
-
-
Save kchristensen/b34a05dc88d8ac052476 to your computer and use it in GitHub Desktop.
Notify Slack if people leave EC2 test instances running
This file contains hidden or 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
#!/usr/bin/env python | |
import boto3 | |
import json | |
import requests | |
from datetime import datetime | |
filter = [{'Name': 'tag:Name', 'Values': ['test-kitchen', 'Packer']}] | |
boto3.setup_default_session(profile_name='prod') | |
ec2 = boto3.resource('ec2') | |
instances = [] | |
time_now = int(datetime.now().strftime("%s")) | |
time_limit = 2 | |
for instance in ec2.instances.filter(Filters=filter): | |
time_running = (time_now - int(instance.launch_time.strftime("%s"))) / 3600 | |
if instance.state['Code'] == 16 and time_running > time_limit: | |
instances.append([ | |
instance.instance_id, instance.key_pair.name, time_running]) | |
if len(instances): | |
slack_message = "*Found orphaned test-kitchen or packer instance(s):*\n" | |
for instance in instances: | |
slack_message = slack_message + \ | |
"{0} started by <@{1}> running for {2} hours\n".format( | |
instance[0], instance[1], instance[2]) | |
slack_payload = { | |
'channel': '#ops-notifications', | |
'username': 'Leroy', | |
'text': slack_message | |
} | |
slack_url = 'https://hooks.slack.com/services/' \ | |
+ 'YOUR/TOKENHERE' | |
requests.post(slack_url, data=json.dumps(slack_payload)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment