Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chef and erb templates. How to use boolean code blocks

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

like image 269
Tampa Avatar asked Mar 30 '12 01:03

Tampa


People also ask

What is an ERB template?

An ERB template looks like a plain-text document interspersed with tags containing Ruby code. When evaluated, this tagged code can modify text in the template. Puppet passes data to templates via special objects and variables, which you can use in the tagged Ruby code to control the templates' output.

What is a template in chef?

Chef uses templates to be able to fill the configuration file with dynamic values. Chef provides templates as a resource which can be used in the recipe.

How do you comment on ERB?

erb is by definition "embedded ruby", you can embed every ruby code between: <%= and the other: %> , typically all written in one line. In addition, ruby one-line comments start always with # , so the <%=# Comment %> style matches perfectly with both pure-ruby and erb styles for one-line comments.


1 Answers

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

like image 138
Joshua Clark Avatar answered Sep 21 '22 10:09

Joshua Clark