Chef and erb templates. How to use boolean code blocks

Tampa picture Tampa · Mar 30, 2012 · Viewed 24.9k times · Source

I am new to chef, ruby, ruby DSL, and erb. I come from python. In a ruby erb template I want to do something like this.

<% if node[:monit][:server]=='nginx' -%>

ALL OF MY NGINX TEXT 

<% end -%>

<% if node[:monit][:server]=='redis' -%>

ALL OF MY REDIS TEXT 

<% end -%>

Clearly I am missing something about proper syntax.

Thanks

Answer

Joshua Clark picture Joshua Clark · Mar 30, 2012

Try this:

<% if node[:monit][:server]=='nginx' -%>

  nginx_text=<%= node[:nginx][:text] %> 

<% end -%>

<% if node[:monit][:server]=='redis' -%>

  redis_text=<%= node[:redis][:text] %> 

<% end -%>

Code wrapped in <% %> or <% -%> is a statement that is evaluated. Code wrapped in <%= %> is code that is evaluated and the result is placed into the file. Harcoded strings dont have to be wrapped in erb tags if they are constant, but Ruby code must be wrapped in erb tags if you want the result of that code to go into your file