Skip to content

Instantly share code, notes, and snippets.

@masha256
Last active February 5, 2016 05:35
Show Gist options
  • Save masha256/4a005f9a6446c63c639d to your computer and use it in GitHub Desktop.
Save masha256/4a005f9a6446c63c639d to your computer and use it in GitHub Desktop.
nagios check script to check for max age of files in an s3 bucket. written in ruby, requires aws-sdk v2 gem.
require 'aws-sdk'
CONFIG = {
# nil to load from env
:aws_access_key => nil,
:aws_secret_access_key => nil,
:aws_region => nil,
# in seconds
:warning_age => 86400 * 1,
:critical_age => 86400 * 2,
# regex that key must match, nil for all keys.
# use /pattern/ syntax
:name_pattern => nil
}
class CheckS3Age
def initialize
@debug = ENV['CHECK_S3_AGE_DEBUG'] == 'true'
end
def run(args)
bucket = args[0]
abort "usage: #{$0} <bucket>" unless bucket
objects = get_bucket_objects(bucket)
newest = newest_object(objects.contents)
puts "newest object was last modified at: #{Time.at newest}" if @debug
now = Time.now.to_i
if now - CONFIG[:critical_age] > newest
puts "CRITICAL - no file newer than #{CONFIG[:critical_age]} seconds ago was found"
exit 2
elsif now - CONFIG[:warning_age] > newest
puts "WARNING - no file newer than #{CONFIG[:warning_age]} seconds ago was found"
exit 1
else
puts "OK - recent file found"
exit 0
end
end
def api_init
if CONFIG[:aws_access_key] && CONFIG[:aws_secret_access_key]
Aws.config[:credentials] = Aws::Credentials.new(CONFIG[:aws_access_key], CONFIG[:aws_secret_access_key])
end
Aws.config[:region] = CONFIG[:aws_region] || ENV['AWS_REGION'] || 'us-east-1'
Aws::S3::Client.new
end
def api
@api ||= api_init
end
def get_bucket_objects(bucket)
api.list_objects({:bucket => bucket})
end
def newest_object(objects)
newest = 0
objects.each do |obj|
if CONFIG[:name_pattern]
next unless obj.key =~ CONFIG[:name_pattern]
end
puts "found #{obj.key} last modified at #{obj.last_modified}" if @debug
if obj.last_modified.to_i > newest
newest = obj.last_modified.to_i
end
end
newest
end
end
if __FILE__ == $0
CheckS3Age.new.run(ARGV)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment