Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chef template - Conditionally inserting a block of text

With Chef, is there a way to insert a block of text from a template only if a condition is met?

Let's say we have an attribute:

node["webapp"]["run"] = "true"

And we only want an entry in the nginx .conf in sites-enabled/app.conf if the webapp is true, like this:

#The nginx-webapp.conf.erb template file

SOME WORKING NGINX CONFIG STUFF

<% if node["webapp"]["run"]=="true" -%>
location /webapp {      
    try_files  $uri @some_other_location;
}

<% end -%>

SOME OTHER WORKING NGINX CONFIG STUFF

As it stands, the conditional text doesn't error out, it just never appears. I've double-checked that the template can see the node attribute by using this:

<%= node["webapp"]["run"] %>

Which DID insert the text "true" into the config file.

I saw in Chef and erb templates. How to use boolean code blocks that I could insert what appears to be just text with an evaluated variable from the node.

I have tried changing to

<% if node[:webapp][:run]=="true" -%>
TEXT
<% end -%>

to no avail.

Any ideas what I'm doing wrong? Thanks!

EDIT:

Per Psyreactor's answer, in the template itself I stopped trying to evaluate the string "true" and instead used this:

SOME WORKING NGINX CONFIG STUFF

<% if node["webapp"]["run"] -%>
location /webapp {      
    try_files  $uri @some_other_location;
}

<% end -%>

SOME OTHER WORKING NGINX CONFIG STUFF

This DOES correctly insert the text block in the config file if the node attribute is set to "true"! I suppose I just assumed it was still a string that needed to be evaluated as such.

like image 686
KingsRook Avatar asked Jul 21 '14 22:07

KingsRook


1 Answers

assuming you have an attribute

node[:test][:bool] = true

in the template would have to do

<% if node[:apache][:bool] -%>
  ServerAlias ​​<% = node[:apache][:aliasl]%>
<% end -%>

another option is to check if the attribute is null

<% unless node [:icinga][:core][:server_alias].nil? %>
  ServerAlias ​​<% = node[:icinga][:core][:server_alias]%>
<% end%>
like image 108
Psyreactor Avatar answered Oct 23 '22 13:10

Psyreactor