Skip to content

Instantly share code, notes, and snippets.

@diskshima
Last active April 19, 2018 04:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diskshima/becc3364a73459627e81357d59eb54f6 to your computer and use it in GitHub Desktop.
Save diskshima/becc3364a73459627e81357d59eb54f6 to your computer and use it in GitHub Desktop.
Mackerel CLI
source 'https://rubygems.org'
gem 'mackerel-client'
#! /usr/bin/env ruby
# vim: set ft=ruby:
# frozen_string_literal: true
require 'mackerel/client'
require 'optparse'
SECRET_FILE = '.mackerel'
def api_key
File.read(File.join(Dir.home, SECRET_FILE)).chomp
end
def client
Mackerel::Client.new(mackerel_api_key: api_key)
end
def host_ids(hosts, only_non_working = true)
tmp_hosts = if only_non_working
hosts.reject { |h| h.status == 'working' }
else
hosts
end
tmp_hosts.map(&:id)
end
def retire_hosts(options)
hosts = client.get_hosts
all = options[:a]
hids(hosts, !all).each do |hid|
mackerel.retire_host(hid)
puts "Retired #{hid}."
end
end
def check_reason(reason)
return if reason && reason.chomp != ''
puts 'Please specify reason.'
exit(-1)
end
def close_alerts(options)
reason = options[:reason]
check_reason(reason)
alerts = client.get_alerts
alert_ids = alerts.map(&:id)
alert_ids.each do |aid|
client.close_alerts(aid, reason)
puts "Closed alert ##{aid}."
end
end
options = {}
subcommands = {
'hosts' => {
opts: OptionParser.new do |opts|
opts.banner = 'List hosts'
end
},
'retire' => {
opts: OptionParser.new do |opts|
opts.banner = 'Retire hosts'
opts.on('-a', '--all', 'All hosts (otherwise only non-working)') do |a|
options[:all] = a
end
end,
call: :retire_hosts
},
'close_alerts' => {
opts: OptionParser.new do |opts|
opts.banner = 'Close alerts'
opts.on('-r REASON', '--reason', 'Close all alerts') do |reason|
options[:reason] = reason
end
end,
call: :close_alerts
}
}
subcommand = subcommands[ARGV.shift]
if subcommand
subcommand[:opts].order!
method = self.method(subcommand[:call])
method.call(options)
end
@diskshima
Copy link
Author

Preparation

  1. Obtain an API key from Mackerel.
  2. Create a file called .mackerel in your home directory and paste the API key from ⬆️
  3. Download the two files (Gemfile and mck.rb)
  4. bundle install

Retiring hosts

bundle exec ruby mck.rb retire

Closing Alerts

bundle exec ruby mck.rb close_alerts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment