Skip to content

Instantly share code, notes, and snippets.

@jderrett
Last active August 29, 2015 14:15
Show Gist options
  • Save jderrett/76df1b0e42bef5f3972e to your computer and use it in GitHub Desktop.
Save jderrett/76df1b0e42bef5f3972e to your computer and use it in GitHub Desktop.
Copy a Librato instrument
#!/usr/bin/env ruby
require 'faraday'
require 'faraday_middleware'
require 'json'
require 'pry'
class LibratoApi
ENDPOINT = 'https://metrics-api.librato.com/v1'
attr_accessor :username
def initialize(username, api_key)
@username = username
@conn = Faraday.new(ENDPOINT) do |f|
f.request :json
f.response :json
f.adapter Faraday.default_adapter
f.basic_auth username, api_key
end
end
def conn
@conn
end
def get_entity(entity_path, entity_id)
resp = conn.get("#{entity_path}/#{entity_id}")
resp.status == 200 ? resp.body : (raise resp.inspect)
end
def get_instrument(instrument_id)
get_entity('instruments', instrument_id)
end
# Clean ids out of the instrument payload so we can post to another account
# Not even sure this is necessary - the API may just take it and discard the ids?
def get_instrument_dupe(instrument_id)
get_instrument(instrument_id).tap do |inst|
inst.delete('id')
inst['streams'].each {|s| s.delete('id')}
end
end
def create_instrument(payload)
conn.post do |req|
req.url 'instruments'
req.body = payload.to_json
end
end
def copy_instrument(instrument_id, new_name=nil)
payload = get_instrument_dupe(instrument_id)
if new_name
payload['name'] = new_name
else
payload['name'] += ' (copy)'
end
resp = create_instrument(payload)
resp.body
end
end
# Script starts here
username, api_key = ENV['LIBRATO_USER'], ENV['LIBRATO_TOKEN']
raise "set ENV['LIBRATO_USER'] and ENV['LIBRATO_TOKEN']" unless username && api_key
api = LibratoApi.new(username, api_key)
# Either pass as an argument, or supply here
instrument_id = ARGV[0] || 1234567
new_name = ARGV[1] || nil # set 'my new instrument name' here
# Create the new instrument
new_instrument = api.copy_instrument(instrument_id, new_name)
# Output link
puts "https://metrics.librato.com/instruments/#{new_instrument['id']}"
# Usage
# ./copy_librato_instrument.rb 1234567 # Create duplicate instrument with ' (copy)' appended to the name
# ./copy_librato_instrument.rb 1234567 'new instrument name'
# ./copy_librato_instrument.rb 1234567 | pbcopy # Grab the link
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment