John Trammell
John Trammell

Reputation: 703

How to escape powershell command arguments when calling from Ruby/Chef?

I'm currently running into a bog-standard Bobby Tables problem, but the environment is Chef + Ruby + powershell.

All of the solutions I've seen so far appear inadequate: they surround the arguments with quotes, but do not fully escape the arguments. Shellwords and shellescape look promising, but they appear to be bash-specific.

For example, I may want to construct in Chef this windows shell command:

.\foo.exe BAR="#{node['baz']}"

Generalizing from the SQL dev world I'd naively anticipate an interface something like this:

cmd = "foo.exe BAR=?"
args = (node['baz'])
run-command(cmd, args)

Where run-command would handle escaping any arguments. Instead I see interfaces that remind me of the bad old SQL days when developers had to construct SQL as a string, and escape any arguments "by hand".

Any pointers to best practices on how to proceed? Use system? Thanks!

Edit: to be clear, the argument baz above can be expected to include arbitrary text, including possibly any combination of characters. Think of it as being identical to the Bobby Tables problem.

Upvotes: 0

Views: 755

Answers (1)

coderanger
coderanger

Reputation: 54181

The easiest generic solution is to use the array form for the execute resource's command property. This avoids all shell parsing an runs the command verbatim.

execute 'whatever' do
  command ['foo.exe', "BAR=#{node['baz']}"]
end

This doesn't work for script style resources though, which take a string for the script chunk to run, including powershell_script. There you would need something more tailored to PowerShell and I don't know its rules well enough to say if Shellwords would match.

Upvotes: 1

Related Questions