Skip to content

Instantly share code, notes, and snippets.

@mauricio
Created May 20, 2016 20:17
Show Gist options
  • Save mauricio/e298ec0cc82f0a14a04a046e86c9bb12 to your computer and use it in GitHub Desktop.
Save mauricio/e298ec0cc82f0a14a04a046e86c9bb12 to your computer and use it in GitHub Desktop.
Deletes stuff that's gone from ec2 from chef
require 'chef/knife'
module KnifeNeat
class NodeDead < Chef::Knife
banner "knife node dead ENVIRONMENT"
option :id_source,
short: '-i SOURCE',
long: '--id-source SOURCE',
description: 'Where to receive the instance id: [ec2.instance_id|name], default: ec2.instance_id',
default: 'ec2.instance_id'
option :dry_run,
short: '-n',
long: '--dry-run',
description: 'Output items that would have been deleted. No action taken.',
required: false,
boolean: true,
default: false
deps do
require 'chef/node'
require 'chef/search/query'
end
def run
config[:yes] = true
ui.info('Dry run mode enabled, all following logs are informational only.') if dry_run?
Chef::Node.list_by_environment(name_args[0]).keys.each do |node_name|
node = Chef::Node.load(node_name)
instance_id = case config[:id_source]
when 'ec2.instance_id'
node[:ec2] && node[:ec2][:instance_id]
when 'name'
node.name.scan(/(i-[0-9a-f]{8})/).flatten.last
else
ui.error("Unknown instance id source: #{config[:id_source]}")
exit(1)
end
if !instance_id.nil? && !exists?(instance_id)
delete(node)
end
end
end
def delete(node)
ui.info("Deleting node #{node.name}")
node.destroy unless dry_run?
clients, start, total = searcher.search('client', "name:#{node.name}")
clients.each do |client|
ui.info("Deleting client #{client.name}")
client.destroy unless dry_run?
end
end
def searcher
@searcher ||= Chef::Search::Query.new
end
def exists?(instance_id)
instance = instances[instance_id]
instance.exists? && instance.status.to_s != 'terminated'
end
def instances
@instances ||= AWS::EC2.new.instances
end
def dry_run?
config[:dry_run]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment