Skip to content

Instantly share code, notes, and snippets.

@kchristensen
Last active December 10, 2015 15:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kchristensen/b34a05dc88d8ac052476 to your computer and use it in GitHub Desktop.
Save kchristensen/b34a05dc88d8ac052476 to your computer and use it in GitHub Desktop.
Notify Slack if people leave EC2 test instances running
#!/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