Skip to content

Instantly share code, notes, and snippets.

@spjmurray
Created July 8, 2016 09:23
Show Gist options
  • Save spjmurray/e9f7d5f755cec0067355c5da6d6f5daf to your computer and use it in GitHub Desktop.
Save spjmurray/e9f7d5f755cec0067355c5da6d6f5daf to your computer and use it in GitHub Desktop.
Consul Hash Retrieval
#!/usr/bin/env ruby
require 'base64'
require 'deep_merge'
require 'json'
require 'net/http'
require 'pp'
uri = URI("http://localhost:8500/v1/kv/#{ARGV[0]}?recurse")
raw = JSON.parse(Net::HTTP.get(uri))
data = raw.inject({}) do |res, x|
# Split the keys up, decode, and return all but the first element
# e.g. 'host/vars/architecture' => ['vars', 'architecture']
path = x['Key'].split('/').collect{|x| URI.unescape(x)}[1..-1]
# Value is always base 64 encoded
# e.g. 'YW1kNjQ=' => 'amd64'
value = Base64.decode64(x['Value'])
# Build a nested hash from the path and value
# e.g. { 'vars' => { 'architecture' => 'amd64' }}
res.deep_merge!(path.reverse.inject(value){|x, y| { y => x }})
end
pp data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment