Jacqueline Casey
Jacqueline Casey

Reputation: 13

erb file with chef syntax

Trying to output the contents of

node['a'] = {:b "1" :c "2"}

by doing this:

a: 
<% a = node['a'] %>
 b: <% a[:b] %>
 c: <% a[:c] %>
<% end %>

to generate this:

a: 
 b: 1
 c: 2

However not entirely sure the correct syntax to do this being new to ruby, chef and erb.

Upvotes: 0

Views: 1119

Answers (1)

coderanger
coderanger

Reputation: 54211

Okay, so let's rewind a bit. The first thing is that you generally don't want to reference node attributes directly in templates. In some cases like attributes coming from Ohai it can be okay as a shorthand, but for important data I would also pass it in via the variables property like this:

template '/etc/whatever.conf' do
  source 'whatever.conf.erb'
  variables a: node['a']
end

With that in place we've now expose the data as a template variable. The second piece of improving this is to let Ruby do the heavy lifting of generating YAML. We can do this using the .to_yaml method in the template:

<%= @a.to_yaml %>

That should be all you need!

Upvotes: 1

Related Questions