Created
October 14, 2014 01:27
-
-
Save jtopjian/5302483d272e5cba7bd7 to your computer and use it in GitHub Desktop.
Ansible Dynamic Inventory with Consul
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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