0

I want to get the recipes that a cookbook contains, through chef-server-api. Following is the code I'm using for getting the cookbook list, individual cookbook details through the api :

require 'rubygems'
require 'chef/config'
require 'chef/log'
require 'chef/rest'
require 'chef/cookbook_version'

client_name = "admin"
signing_key_filename="c:/chef-repo/.chef/admin.pem"
server_url = "https://10.132.17.244:443"

rest = Chef::REST.new(server_url, client_name, signing_key_filename)
cookbooks = rest.get_rest("/cookbooks?all_versions")

cookbooks.keys.each do |name|
cookbook_versions = rest.get_rest("/cookbooks/#{name}")
print "#{name}\n"

cookbook_versions[name]["versions"].each do |cv|

version = cv["version"]
cookbook = rest.get_rest("/cookbooks/#{name}/#{version}")
 print "\t#{cookbook}\n"
 #parsed = JSON[cookbook]

end
end

The problem I'm facing is to get the recipe list from the 'cookbook' object. I tried parsing it to ruby hash and then read, but of no use. If I directly print the 'cookbook' variable, the output is something like the screenshotenter image description here

I'm not able to get how to interpret the output I am getting by hitting the '/cookbooks/NAMEW/VERSION' endpoint, and get the recipes present in an individual cookbooks.

tortuga
  • 737
  • 2
  • 13
  • 34
  • So you get an object, hava a look at this object definition [here](https://github.com/opscode/chef/blob/master/lib/chef/cookbook_version.rb) Iterating over `cookbook['recipe_filenames']` should be what you're looking for. – Tensibai Aug 29 '14 at 08:01
  • iterating over cookbook['recipe_filenames'] give an error. "undefined method '[]'" – tortuga Aug 29 '14 at 08:55
  • In this cas I would start printing cookbook.methods or cookbook.inspect, I may be wrong on the access method here – Tensibai Aug 29 '14 at 08:57
  • hey, got it to work. We had to iterate on the method recipe_filenames, as in iterate on 'cookbook.recipe_filenames' method. – tortuga Aug 29 '14 at 09:46
  • That's what I was saying when I said "I may be wrong on the access method" :) - FWIW you should mark @coderanger answer as accepted as it is really much complete and clearest. – Tensibai Aug 29 '14 at 12:07

2 Answers2

1

When using the Chef gem it automatically decodes some responses into Ruby objects for you. You can either use the object directly (specifically you want #recipe_filenames and then parse those to the cookbook_name::recipe_name format) or you could use a better API client like Chef-API or PyChef.

coderanger
  • 52,400
  • 4
  • 52
  • 75
0

Need a ruby solution? The following example uses jq to filter the JSON resultset returned by knife:

$ knife cookbook show apache2 2.0.0 recipes -Fj | jq '.[]|.name'
"mod_cgi.rb"
"mod_proxy_http.rb"
"mod_proxy_html.rb"
"mod_access_compat.rb"
"mod_authz_dbd.rb"
"mod_proxy_express.rb"
..
..
Mark O'Connor
  • 76,015
  • 10
  • 139
  • 185