Skip to content

Instantly share code, notes, and snippets.

@apsoto
Created September 5, 2011 05:20
Show Gist options
  • Save apsoto/1194158 to your computer and use it in GitHub Desktop.
Save apsoto/1194158 to your computer and use it in GitHub Desktop.
Chef EC2 Node Cleanup task
namespace :ec2 do
# setup chef config
#
config = File.join(File.dirname(__FILE__), '..', '.chef', 'knife.rb')
Chef::Config.from_file(config)
load_gem_or_report(%w{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.empty? || aws_secret_key.empty?
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