Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass variables to be rendered by erb from the command line?

I have an erb template in a chef cookbook that configures my vhost for my vagrant environment and my aws opsworks environment. I would like to utilize this template on my continuous integration server to generate the vhost for my non chef managed machines before it pushes it out.

Suppose I have the following erb:

<VirtualHost <%= @params[:http_host] %>:<%= @params[:http_port] || node['apache']['listen_ports'].first %>>
    ServerName <%= @params[:server_name] %>
    ServerAlias <% @params[:server_aliases].each do |a| %><%= a %> <% end %>

    DocumentRoot <%= @params[:docroot] %>
</VirtualHost>

How do I go about populating those variables if I wanted to call erb directly?

I know I can call erb -r library vhost.conf.erb to load a library to be leveraged, can set variables as an argument to erb or do I need to create a custom library. If I need a custom library, how would that look?

like image 291
Steve Buzonas Avatar asked Jan 17 '26 22:01

Steve Buzonas


1 Answers

As of Ruby 2.2 you can set local variables in Erb from the command line.

You would need to change your code to use local variables rather than instance variables. For example if you had (stripped down from your code):

<VirtualHost <%= http_host %>:<%= http_port %>>

You could then call it with:

$ erb http_host=http://example.com http_port=1234 my_file.erb

and the result would be:

<VirtualHost http://example.com:1234>
like image 165
matt Avatar answered Jan 20 '26 13:01

matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!