Skip to content

Instantly share code, notes, and snippets.

@sjourdan
Forked from apsoto/chef-ec2.rake
Created September 5, 2011 12:57
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 sjourdan/1194934 to your computer and use it in GitHub Desktop.
Save sjourdan/1194934 to your computer and use it in GitHub Desktop.
Chef EC2 Node Cleanup task
namespace :ec2 do
# setup chef config
# assumes this file is sibling to .chef dir, ex: CHEF_REPO/tasks
config = File.join(File.dirname(__FILE__), '..', '.chef', 'knife.rb')
Chef::Config.from_file(config)
require 'active_support'
require 'aws'
desc 'Delete any ec2-based chef nodes that no longer exist'
task :cleanup_nodes do
aws_access_key = ENV['AMAZON_ACCESS_KEY_ID']
aws_secret_key = ENV['AMAZON_SECRET_ACCESS_KEY']
raise "Amazon Environment variables not defined" if aws_access_key.blank? || aws_secret_key.blank?
ec2 = Aws::Ec2.new(aws_access_key, aws_secret_key)
# list or running ec2 instance ids
ec2_instances = ec2.describe_instances.reject{|i| i[:aws_state] == "terminated"}.collect{|i| i[:aws_instance_id]}
# list of all currently registered chef clients (only ec2 nodes). Assumes instance id is the node name
chef_ec2_clients = Chef::ApiClient.list.keys.grep(/i-[a-zA-z0-9]+/)
# list of registered chef clients that aren't currently running.
dead_chef_ec2_clients = chef_ec2_clients - ec2_instances
# delete clients
dead_chef_ec2_clients.each do |dead_client_name|
dead_client = Chef::ApiClient.load(dead_client_name)
dead_client.destroy
end
chef_ec2_nodes = Chef::Node.list.keys.grep(/i-[a-zA-z0-9]+/)
dead_ec2_nodes = chef_ec2_nodes - ec2_instances
# delete nodes
dead_ec2_nodes.each do |dead_node_name|
dead_node = Chef::Node.load(dead_node_name)
dead_node.destroy
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment