Skip to content

Instantly share code, notes, and snippets.

@tarekziade
Created October 14, 2016 14:02
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 tarekziade/649f9ea7bb514ec0cf88369c8c5c4c48 to your computer and use it in GitHub Desktop.
Save tarekziade/649f9ea7bb514ec0cf88369c8c5c4c48 to your computer and use it in GitHub Desktop.
Detect and kill an idling loads ec2 instance

On the EC2 instance A few variable to set:

Run a docker with the docker sock linked and a few variables set:

docker run -t -v /var/run/docker.sock:/run/docker.sock -v $(which docker):/bin/docker  -i ubuntu /bin/bash
apt-get update && apt-get install -y python-pip && pip install docker-py==1.6.0

export CID=`cat /proc/self/cgroup | grep -o  -e "docker-.*.scope" | head -n 1 | sed "s/docker-\(.*\).scope/\\1/"`
export EC2_AVAIL_ZONE=`curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone`
export EC2_REGION="`echo \"$EC2_AVAIL_ZONE\" | sed -e 's:\([0-9][0-9]*\)[a-z]*\$:\\1:'`"
export EC2_INSTANCE_ID=`curl -s http://169.254.169.254/latest/meta-data/instance-id`
export AWS_ACCESS_KEY_ID=XXX
export AWS_SECRET_ACCESS_KEY=XXX

Detect within that container what else is running:

import os
from docker import Client

cli = Client(base_url='unix://var/run/docker.sock')
cli.containers()
containers = [cont for cont in cli.containers() if cont['Id'] != os.environ['CID']]

If nothing runs, you can self-terminate the box from the container :

aws ec2 terminate-instances --instance-ids $EC2_INSTANCE_ID --region $EC2_REGION
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment