Skip to content

Instantly share code, notes, and snippets.

@diogok
Last active August 29, 2015 14:01
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 diogok/24cf050e880731783d40 to your computer and use it in GitHub Desktop.
Save diogok/24cf050e880731783d40 to your computer and use it in GitHub Desktop.
More complete "docker inspect" into etcd
#!/usr/bin/env ruby
require 'uri'
require 'json'
require 'net/http'
def http_get(uri)
JSON.parse(Net::HTTP.get(URI(uri)))
end
def http_put(uri,doc)
uri = URI.parse(uri)
header = {'Content-Type'=> 'application/x-www-form-urlencoded'}
if doc.class == Hash then
header = {'Content-Type'=> 'application/json'}
end
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Put.new(uri.request_uri, header)
request.body = doc
if doc.class == Hash then
request.body=doc.to_json
end
response = http.request(request)
JSON.parse(response.body)
end
def flatten(obj,sub)
flat={}
sub=sub.gsub("-","_").downcase
obj.keys.each {|k|
key=k.gsub("-","_").gsub("/","_").downcase
if obj[k].class == Array then
if(obj[k][0].class == Hash) then
flat=flat.merge(flatten(obj[k][0],"#{sub}/#{k}"))
end
elsif obj[k].class == Hash then
flat=flat.merge(flatten(obj[k],"#{sub}/#{k}"))
else
flat["#{sub}/#{key}"] = obj[k].to_s
end
}
flat
end
host = ENV['HOST'] || `hostname -I | awk '{ print $2 }'`.gsub("\n","")
etcd = ENV['ETCD'] || "http://#{host}:4001"
`docker ps | tail -n+2 | awk '{ print $1 }'`.split("\n")
.map { |id| `docker inspect #{id}` }
.map { |inspect| JSON.parse(inspect)[0]}
.map { |data| flatten(data,/([^\/]+\/)?([a-zA-Z\-_]+):?/.match(data["Config"]["Image"])[2]) }
.each { |container|
name = container.keys.first.split("/").first
port = `docker inspect #{container["#{name}/id"]} | grep -o '[0-9]\\+/tcp' | head -n1 | grep -o '[0-9]\\+'`.gsub("\n","")
hport = container["#{name}/networksettings/ports/#{port}/tcp/hostport"]
container["#{name}/url"] = "http://#{host}:#{hport}"
container.keys.each {|key|
if container[key] != nil then
puts "#{key} = #{container[key]}"
http_put("#{etcd}/v2/keys/#{key}","value=#{URI.encode(container[key])}")
end
}
}
#!/usr/bin/env ruby
# how to use:
# $ eval "#(./etcd2env.rb)"
require 'uri'
require 'json'
require 'net/http'
def http_get(uri)
JSON.parse(Net::HTTP.get(URI(uri)))
end
host = ENV['HOST'] || `hostname -I | awk '{ print $1 }'`.gsub("\n","")
etcd = ENV['ETCD'] || "http://#{host}:4001"
data = http_get("#{etcd}/v2/keys/?recursive=true")
def flatten(obj)
flat = {}
if obj["dir"] then
obj["nodes"].each { |n|
flat = flat.merge(flatten(n))
}
else
key = obj["key"].gsub("/","_").gsub("-","_")
flat[key[1..key.length]]=obj["value"]
end
flat
end
final = flatten( data["node"] )
final.keys.each {|k|
puts "export #{k}=\"#{final[k]}\""
puts "export #{k.upcase}=\"#{final[k]}\""
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment