Skip to content

Instantly share code, notes, and snippets.

@jcmartins
Last active January 14, 2016 14:15
Show Gist options
  • Save jcmartins/604f968b874c906082f4 to your computer and use it in GitHub Desktop.
Save jcmartins/604f968b874c906082f4 to your computer and use it in GitHub Desktop.
Sensu EC2 remove client
require 'timeout'
require 'rubygems' if RUBY_VERSION < '1.9.0'
require 'sensu-handler'
require 'fog'
class Ec2Node < Sensu::Handler
def filter; end
def handle
# #YELLOW
puts "Client = #{@event["client"]}"
puts "Name = #{@event["client"]["name"]}"
puts "Id = #{@event["client"]["name"].split(".")[0]}"
puts "Address = #{@event["client"]["address"]}"
unless ec2_node_exists? # rubocop:disable UnlessElse
delete_sensu_client!
else
puts "[EC2 Node] #{@event['client']['name']} appears to exist in EC2"
end
end
def delete_sensu_client!
response = api_request(:DELETE, '/clients/' + @event['client']['name']).code
deletion_status(response)
end
def ec2_node_exists?
states = acquire_valid_states
filtered_instances = ec2.servers.select { |s| states.include?(s.state) }
instance_ids = filtered_instances.map(&:id)
instance_ids.each do |id|
return true if id == @event['client']['name'].split(".")[0]
end
false # no match found, node doesn't exist
end
def ec2
@ec2 ||= begin
key = settings['aws']['access_key'] || ENV['AWS_ACCESS_KEY_ID']
secret = settings['aws']['secret_key'] || ENV['AWS_SECRET_ACCESS_KEY']
region = settings['aws']['region'] || ENV['EC2_REGION']
Fog::Compute.new(provider: 'AWS',
aws_access_key_id: key,
aws_secret_access_key: secret,
region: region)
end
end
def deletion_status(code)
case code
when '202'
puts "[EC2 Node] 202: Successfully deleted Sensu client: #{@event['client']['name'].split(".")[0]}"
when '404'
puts "[EC2 Node] 404: Unable to delete #{@event['client']['name'].split(".")[0]} , doesn't exist!"
when '500'
puts "[EC2 Node] 500: Miscellaneous error when deleting #{@event['client']['name'].split(".")[0]}"
else
puts "[EC2 Node] #{res}: Completely unsure of what happened!"
end
end
def acquire_valid_states
if @event['client'].key?('ec2_states')
id_states = @event['client']['name'].split(".")[0]['ec2_states']
puts " Id_States = #{id_states}"
return id_states
else
return ['running']
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment