Passing dynamic ruby variables into a .js.erb file



I’m hoping someone could please assist with this problem.

got a scenario where I use these dynamic variables within a template
.dashboard.js.erb file (using it to construct a grafana dashboard):


/* global _ */

‘use strict’;

var windows, document, $, jQuery, moment, kbn, ARGS;
var dashboard;
var rows = 5;
var env = <%= metric %>;
var nodes_env = <%= node %>;

and my recipe uses the following resource:-


dashboard_path = "/usr/share/public/grafana"
file = "dashboard.js"
metric = "blue-monolith"
node = “nodes.production_blue”

template File.join(dashboard_path, file) do
source "dashboard.js.erb"
:metric => metric,
:node => node

I’ve tried the following inside my .js.erb file:-
var env = <%= metric %>;
var env = ‘<%= metric %>’;
var env = <%= metric.to_json %>;

All of which result in error at the end of a chef run:-
Chef::Mixin::Template::TemplateError (undefined local variable or method `metric’ for #Chef::Mixin::Template::TemplateContext:0x00000005f49ed0)

Does anyone know how to represent these dynamic variables (metric and node) in a .js.erb file?

Many thanks


Hi Angela,

You are passing in a Ruby symbol so try

var env = <%= @metric %>;


var env = <%= @:metric %>;


Hi Chris,

Thanks you very much! That worked.