Skip to content

Instantly share code, notes, and snippets.

@ryancragun
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ryancragun/11633fec7108ede07880 to your computer and use it in GitHub Desktop.
Save ryancragun/11633fec7108ede07880 to your computer and use it in GitHub Desktop.

Mapping Nodes to Organizations

Chef 11.x

You'll need to run this on the Server in Orgmapper, eg:

/opt/opscode/bin/orgmapper
orgmapper>> eval(::File.read("/path/to/code.rb"))

This is the code file you'll want to save

node_map = Hash.new { |h, k| h[k] = [] }
node_map[:orgs] = {}

sql.select(:name, :org_id, :serialized_object).from(:nodes).each do |node|
  begin
    so = Zlib::GzipReader.new(StringIO.new(node[:serialized_object])).read
    node[:serialized_object] =
      JSON.parse(so, create_addtions: false, symbolize_names: true)
  rescue
    # If the JSON doesn't parse just move on
  end
  node_map[:orgs][node[:org_id]] ||= {}
  node_map[:orgs][node[:org_id]][:nodes] ||= []
  node_map[:orgs][node[:org_id]][:nodes] << node
end

node_map[:orgs].dup.each do |org_id, _|
  org_name = ORGS.all.find { |org| org['guid'] == org_id }['name']
  node_map[:orgs][org_name] = node_map[:orgs].delete(org_id)
end

File.open('/tmp/nodes.json', 'w') { |f| f.write JSON.pretty_generate(node_map) }

Chef 12.x

Chef 12 moved everything to pgsql, so you can just query postgres

/opt/opscode/embedded/bin/psql -U opscode_chef -h 127.0.0.1
SELECT
  n.name AS node,
  o.name AS org
FROM nodes n
INNER JOIN orgs o ON n.org_id = o.id
GROUP BY
  n.name,
  o.name;

Or you can still use Ruby

su opscode-pgsql -c "/opt/opscode/embedded/bin/pry -r json -r zlib -r stringio -r sequel -r chef"
node_map = Hash.new { |h, k| h[k] = [] }
node_map[:orgs] = {}

secrets = JSON.parse(File.read('/etc/opscode/private-chef-secrets.json'))
sql = Sequel.connect(['postgres://opscode_chef:',
                      "#{secrets['postgresql']['sql_password']}",
                      '@127.0.0.1:5432/opscode_chef'].join)
sql.from(:orgs).join(:nodes, org_id: :id).each do |node|
  begin
    so = Zlib::GzipReader.new(StringIO.new(node[:serialized_object])).read
    node[:serialized_object] =
      JSON.parse(so, create_addtions: false, symbolize_names: true)
  rescue
    # If the JSON doesn't parse just move on
  end
  node_map[:orgs][node[:full_name]] ||= {}
  node_map[:orgs][node[:full_name]][:nodes] ||= []
  node_map[:orgs][node[:full_name]][:nodes] << node
end

File.open('/tmp/nodes.json', 'w') { |f| f.write JSON.pretty_generate(node_map) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment