Skip to content

Instantly share code, notes, and snippets.

@mpasternacki
Created January 16, 2011 20:03
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 mpasternacki/782097 to your computer and use it in GitHub Desktop.
Save mpasternacki/782097 to your computer and use it in GitHub Desktop.
Reap Node and Client instances for dead EC2 instances on a chef server.
# -*- mode: ruby; coding: utf-8 -*-
# Requires fog gem.
# Configure AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in config/rake.rb
desc <<EOF
Delete nodes and clients for nonexistent EC2 instances from chef server
YES=1 variable makes task skip confirmation questions.
EOF
task :reap_instances do
require 'fog'
require 'json'
# https://github.com/geemus/excon/issues#issue/13
# "certificate verify failed" workaround
Excon.ssl_verify_peer = false
if ENV['YES']
_y = 'yes y | '
else
_y = ''
end
EC2 = Fog::AWS::Compute.new(:aws_access_key_id => AWS_ACCESS_KEY_ID,
:aws_secret_access_key => AWS_SECRET_ACCESS_KEY)
def on_dead_instance(instance_id)
if instance_id[0..1] == 'i-'
i = EC2.servers.get(instance_id)
unless i and i.state!="shutting-down" and i.state!="terminated"
puts "Found dead instance #{instance_id}"
yield
end
end
end
JSON::load(`knife node list`).each do |node|
on_dead_instance node do
sh "#{_y}knife node delete #{node}"
end
end
JSON::load(`knife client list`).each do |client|
on_dead_instance client do
sh "#{_y}knife client delete #{client}"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment