Passing JSON into cookbook


#1

Hi There,

In my ./attributes directory in the default.rb I have the following:
default[:db][:jdbc_sqlserver_url] = “test”

And in ./templates/default in the template.rb file I have:
url <%= node[:db][:jdbc_sqlserver_url] %>

And want to use in the default recipe:

template “/path/to/config.conf” do
source "default.erb"
end

And then pass in:

{
“db”: {
“jdbc_sqlserver_url”: “bob”
}
}

And write it to the config.conf file.

How do i pass the variables in on the “template “/path/to/config.conf” do” definition?

Cheers,
Simon.


#2

What the problem ? it’s really unclear to me what you want to do there.

A guess if I understood properly is that you want to change the default value set in your cookbook.

First option:

The template could become:

url <%=  @jdbc_sqlserver_url  %>

And the template call be:

template "/path/to/config.conf" do
  source "default.erb"
  variables ("jdbc_sqlserver_url" => node['db']['jdbc_sqlserver_url']) 
end

And you can change the variable value for another template using the same default.erb file

Second option:
If you wish to override the url value for a specific node, create a wrapper cookbook which:

  1. depends "original"in its metadata.rb file
  2. redefine the attribute in its attribute file
  3. call include_recipe 'original_cookbook' in its recipe file

and set this wrapper in your node runlist instead of original one.


#3

Hi Simon
template config.conf do source “my.conf.erb” mode “0644” ---- whatever read,write execute permissions you want on the file variables( :var1 => node[:attr1][:childattr1], :var2 => node[:attr1][:childattr2] )end
Assume your my.conf.erb file is as follows:
key1=<%= @var1 %>key2=<%= @var2 %>

HTH


#4

Many thanks all, it works!

Within the config file I have:
(they have a comment sign in front, #)

#set.myvalue.initialSize=50
#set.mymin.minval=10
#set.mymax.maxvalue=40
#set.maxnumber=43
#set.minmumber=24

Is there a way of using an if jsonvalue = enabled, uncomment the items above. I know they are defined in the template file as variables so I cant just uncomment the “key” unless there’s a way of doing this?

Cheers,
Simon.


#5

Unless i could define if to use mytemplate1.erb or mytemplate2.erb depending on the attribute?


#6

yeah, you can define the source parameter based on attributes.

if node.foo.bar
 template_source = 'x.erb'
else
 template_source = 'y.erb'
end

template '/path/to/file' do
 source template_source
end

also, you can do conditionals straight inside erb templates

<% if node.foo.enable %>
<% end%>

lastly, you can also use template partials. read chef docs and erb , that should answer a lot of things