Template source dependent on an attribute set

Hi,

Basic syntax issue

I posted a question similar to this for controlling template contents but wanted to know if i can further this to select template source.

Attribute

default['app']['version2'] = true

recipe

template node['app'][version]['path']  do
  <% if node['app']['version2'] -%>
    source 'file_version2.erb'
  <% end -%>
  source 'file.erb'
  local false
end

I had hoped this would select file.erb as the source of the template unless ‘version2’ is set to ‘true’ which would then use source file_version2.erb

Currently errors with -

syntax error, unexpected tIDENTIFIER, expecting keyword_end

<% if node['app']['version2'] -%>
^ under first [

keyword_end - missing a close bracket??

hopefully something obvious …

many thanks

You can’t put ERB inside a recipe, but you can put pure ruby. There are multiple ways to make an attribute conditional, assuming that node['app']['version2'] will never change mid chef run, you could try something like this

template node['app'][version]['path']  do
  source 'file_version2.erb' if node['app']['version2']
  source 'file.erb' unless node['app']['version2']
  local false
end

Or another way that is a little more verbose but easier to read.

node.run_state['version'] = ''
node.run_state['version'] = '_version2' if node['app']['version2']

template node['app'][version]['path']  do
  source "file#{node.run_state['version']}.erb"
  local false
end

If the node['app']['version2'] could ever change mid chef run, then it would be better to put this in a custom resource or use lazy interpolation.

thanks a lot for your response - that makes a lot of sense and will use shortly.