Passing JSON into cookbook

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"

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?


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']) 

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.

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 %>


Many thanks all, it works!

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


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?


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

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

 template_source = 'x.erb'
 template_source = 'y.erb'

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

also, you can do conditionals straight inside erb templates

<% if %>
<% end%>

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