Mayur
Mayur

Reputation: 31

How to use dynamic variables defined in chef recipe to replace the expression in template file

I am stuck with a situation where I have created a templates/test.sh.erb file with below content:

#!/bin/bash

ls -ltr <%= "#{tomcat_home}/instance1/bin" %>
ls -ltr <%= "#{tomcat_home}/instance1/conf" %>

For this erb file, I wanted to pass "tomcat_home" which can be either "/opt/tomcat" or "/opt/apacheTomcat". This data I am parsing using if else condition which is returning me tomcat home either one of this path.

eg: tomcat_home="/opt/tomcat"

I wanted to create the test.sh file at /tmp location on server in which I wanted to replace the tomcat_home variable dynamically whenever it will create the test.sh file . template resource logic:

    template "/tmp/test.sh" do
        source 'test.sh.erb' # <-- this is your directory in files/default/local_directory
        owner 'tomcat'                                                                 
        group 'tomcat'
        mode '0755'
        action :create                                                                   
    end    

Desired output I am expecting when template resource will run:

#!/bin/bash

ls -ltr /opt/tomcat/instance1/bin
ls -ltr /opt/tomcat/instance1/conf

Upvotes: 1

Views: 734

Answers (1)

seshadri_c
seshadri_c

Reputation: 7350

For variable interpolation in Chef templates (.erb files), <%= %> markers should be used. In your case, only the tomcat_home variable should be inside these markers, i.e. <%= tomcat_home %>.

Also, the files that need templating, should be under the <cookbook_name>/templates/default directory. The files/ directory is for static files, where variable interpolation does not happen.

Example:

templates/default/test.sh.erb:

#!/bin/bash

ls -ltr <%= @tomcat_home %>/instance1/bin
ls -ltr <%= @tomcat_home %>/instance1/conf

Then in recipe:

template '/tmp/test.sh' do
  source 'test.sh.erb'
  owner 'tomcat'                                                                 
  group 'tomcat'
  mode '0755'
  variables(
    tomcat_home: '/opt/tomcat'
  )
end

Note that the :create action is default for the template resource, so I omitted it. Also, the templates can refer to node attributes directly, like:

ls -ltr <%= node['cookbook_name']['tomcat_home'] %>/instance1/bin

Upvotes: 2

Related Questions