0

I have written following template in my chef cookbook recipe

template '/etc/app.conf' do
   variables({
   my_id: Chef::HTTP.new(https://example.com).get('/',{header})
})
end

And my erb file is

Output is : <%= @my_id %>

I actually want to perform some ruby operations(mainly filter out and count the components of my_id) and then pass those values(count of each component) back to the template and use it further. What should be erb configuration or anything thats need to be added in template block?

(Here, my_id actually has the subnets and I want to get those the count of those subnets and its values so that I can use it further to perform another http request and get the nodes in each of the subnet).

Kushal Warke
  • 21
  • 1
  • 5

2 Answers2

0

Don't know much about Chef Cookbooks but you can write some ruby within an ERB template. It is not the cleanest solution I believe though.

See here on how to embed code in your ERB

aBadAssCowboy
  • 2,440
  • 2
  • 23
  • 38
  • Tried using that. Problem is the variable my_id is in JSON and I need to convert it to ruby hash before doing any operation. How to convert it? JSON.parse isn't working because my_id is not a string – Kushal Warke Jul 05 '17 at 10:46
  • You say its in JSON. If its in JSON, `JSON.parse` should work. Can you post your JSON? – aBadAssCowboy Jul 05 '17 at 11:41
0

The thing you pasted from (hopefully you were summarizing since you missed a bunch of quotes in there) was only a quick tip. To get JSON data you want to use Chef::HTTP::SimpleJSON, the will do the parsing for you and whatnot.

variables data: Chef::HTTP::SimpleJSON.new('https://whatever.com/').get('/foo')
coderanger
  • 52,400
  • 4
  • 52
  • 75