5

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.

Community
  • 1
  • 1
KingsRook
  • 113
  • 1
  • 8
  • 2
    Do you understand the difference between `"true"` and `true`? – sethvargo Jul 22 '14 at 02:28
  • I do now. It seems like everything except true and false are stored as strings though. Does Chef store only those attributes as boolean values instead of strings? – KingsRook Jul 22 '14 at 22:43
  • 1
    It stores whatever you set it. You can set a node attribute to an object, but once it's persisted to the server, it will become a string because of the JSON representation. – sethvargo Jul 22 '14 at 22:47

1 Answers1

7

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%>
Psyreactor
  • 343
  • 2
  • 7