Skip to content

Instantly share code, notes, and snippets.

@jtopjian
Created October 14, 2014 01:27
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jtopjian/5302483d272e5cba7bd7 to your computer and use it in GitHub Desktop.
Save jtopjian/5302483d272e5cba7bd7 to your computer and use it in GitHub Desktop.
Ansible Dynamic Inventory with Consul
#!/usr/bin/env ruby
require 'net/http'
require 'uri'
require 'json'
require 'pp'
consul_url = 'http://localhost:8500/v1/catalog'
output = {}
s_json = JSON.parse(Net::HTTP.get_response(URI.parse("#{consul_url}/services")).body)
services = s_json.keys
services.each do |srv|
res = Net::HTTP.get_response(URI.parse("#{consul_url}/service/#{srv}")).body
json = JSON.parse(res)
json.each do |node|
t = {}
if node['ServiceTags'].length > 0
node['ServiceTags'].each do |tsrv|
output.merge!({ "#{srv}:#{tsrv}" => [node['Address']] }) do |key, old, new|
old | new
end
output.merge!({ "#{srv}_#{tsrv}" => [node['Address']] }) do |key, old, new|
old | new
end
end
end
output.merge!({ srv => [node['Address']] }) do |key,old,new|
old | new
end
end
end
puts JSON.generate(output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment