linux - Equivalent of String.Format in a Chef/Bash Recipe -


looking similar .net string format in chef recipe ie.

string phone = string.format("phone: {0}",_phone); 

i have chef recipe need build command string 30 of these params hoping tidy way build string, in principle im doing this

a=node['some_var'].to_s ruby_block "run command"   block     cmd = shell_out!("node mycommand.js #{a}; exit 2;")              end end 

when try error

arguments path.join must strings tips appreciated

chef runs in 2 phases:

compile , execute (see https://www.chef.io/blog/2013/09/04/demystifying-common-idioms-in-chef-recipes/ more details).

your variable assignment a happens @ compile time, e.g. when chef loads recipes. ruby block execute in execution mode @ converge time , cannot access variable a.

so easiest solution might putting attribute ruby block:

   ruby_block "run command argument #{node['some_var']}"      block        shell_out!("node mycommand.js #{node['some_var']}")      end    end 

however:

  1. if don't need execute ruby code, consider using execute or bash resource instead.

  2. keep in mind, must have unique resource name, if you're building kind of loop around it. easy way put unique name ruby_block "something unique per loop iteration" ... end

  3. what don't understand exit code 2. error code. make chef throw exception each time. (shell_out! throws exception if exit code != 0, see https://github.com/chef/chef/blob/master/lib/chef/mixin/shell_out.rb#l24-l28)

  4. the resource executed on each chef run. not in interest. consider adding guard (test), prevent unnecessary execution, see https://docs.chef.io/resource_common.html#guards


Comments