Reputation: 48
Say I have a project to deploy with a template like: project/file.erb
node['simpe_test_value']
I want to be able to write 2 different cookbooks to deploy the same project but with different value for the attributes being used in the template, like:
cookbooks/test1/recipes/default.rb
node.default['simple_test_value'] = 'in cookbook test 1'
template "project/test.cfg" do
local true
source "project/test.erb"
end
cookbooks/test2/recipes/default.rb
node.default['simple_test_value'] = 'in cookbook test 2'
template "project/test.cfg" do
local true
source "project/test.erb"
end
Chef will evaluate all the attributes before the converge phase, and so my template file is expanded with the same value for both resources.
How can I achieve this?
My goal is to use the same code for a project and deploy it multiple times (different cookbooks/different recipes) by adjusting only some attributes.
Upvotes: 2
Views: 1960
Reputation: 15784
Ok, after comment reading I really do think you have to namespace your attributes.
If the template resource is the same (same path in destination) it can't work (or it will loop updating and you'll end up with only one file).
For some deployments we do something like:
node['company']['apps']['app1']['simple_value1']="value1"
node['company']['apps']['app1']['simple_value2']="value2"
node['company']['apps']['app2']['simple_value1']="value3"
node['company']['apps']['app2']['simple_value2']="value4"
And in recipe we render the template using something like:
template 'app1/WEB-INF/web.xml' do
source 'web.xml.erb'
cookbook 'app-templates' # specify the source cookbook to avoid duplicating the template file over many cookbooks
variables({
:app_name => 'app1',
:app_vars => node['company']['apps']['app1']
})
end
In the template we use @app_vars['simple_value1']
and @app_vars['simple_value2']
and sometimes we iterate over node['company']['apps'][@app_name]
child attributes to use the same template for different use cases with different number of values for each app.
exemple .erb:
Any line of fixed text
<% node['company']['apps'][@app_name].each do |name, value| -%>
key_<%= name %>=<%= value %>
<% end -%>
Rest of file...
(Simplified here but I think it's enough to get the concept)
Upvotes: 4