Skip to content

Instantly share code, notes, and snippets.

@cognusion
Created August 28, 2014 14:36
Show Gist options
  • Save cognusion/60825b5acd50fed67205 to your computer and use it in GitHub Desktop.
Save cognusion/60825b5acd50fed67205 to your computer and use it in GitHub Desktop.
Simple script to audit AWS EC2 instances vs a Livestatus-enabled nagios system
#!/usr/bin/env ruby
# Audits your monitored instances vs your running instances, and reports back.
# If you want to run this from an AWS instance, its IAM Role must be granted at least the following:
#
#{
# "Statement": [
# {
# "Action": [
# "ec2:DescribeInstances",
# ],
# "Effect": "Allow",
# "Resource": "*"
# }
# ]
# }
require 'rubygems'
require 'trollop' # Option parsing made stupid easy
require 'aws-sdk'
require 'socket'
opts = Trollop::options do
opt :region, "AWS Region",
:type => String,
:default => 'us-east-1'
opt :live, "Livestatus path",
:type => String,
:default => '/var/spool/nagios/cmd/live'
opt :debug, "Be noisy"
end
ec2 = AWS::EC2.new(:region => opts[:region])
Instances = Hash.new
# Collect running instances
ec2.instances.each {|i|
next unless i.status.to_s == 'running'
puts "[d] I id: #{i.id} #{i.availability_zone} #{i.instance_type}" if opts[:debug]
Instances[i.id] = i
}
# Get the monitored instances, removing them from the list.
UNIXSocket.open(opts[:live]) {|live|
live.print "GET hosts
Columns: host_alias host_name
"
live.close_write
live.each {|line|
next unless line =~ /^i-/
line.chomp!
puts "[d] M id: #{line}" if opts[:debug]
if Instances.has_key?(line)
puts "\tRemoving..." if opts[:debug]
Instances.delete(line)
end
}
}
# What's left over
Instances.each_pair {|id, i|
puts "#{id} #{i.tags['Name']}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment