f8ster f8ster - 5 months ago 35
Ruby Question

Chef recipe: can't capture output from backticks to variable in ruby_block

I have a Chef recipe with a ruby_block containing this:

myoutput = `keytool -import -alias #{al} -keystore #{ks} -storepass #{pw} -file #{ca} -trustcacerts -noprompt`
puts ":" + myoutput + ":"
Chef::Log.error('Error installing CA Cert') unless myoutput.include? "Certificate was added to keystore"


(All of the variables are properly set.) Here's the relevant output:

Certificate was added to keystore
::
[2013-07-03T21:26:41-07:00] ERROR: Error installing CA Cert


Notice the ::. Why isn't myoutput being set correctly? When I run that command by hand, I get the expected output. The command in the backticks does what it's supposed to, so I know it's running, but for some reason the standard output from the command is not getting assigned to myoutput and I can't figure out why. Any ideas? Thanks -- Dave

Edit: the reason is because the output of this particular 'keytool' invocation is going to stderr, not stdout.

Answer

It could be that the output is directed to STDERR instead of STDOUT. Try this:

myoutput = `keytool -import -alias #{al} -keystore #{ks} -storepass #{pw} -file #{ca} -trustcacerts -noprompt 2>&1`

I don't have any certificate to import to test this, but running `keytool` alone sends output to STDERR, whereas `keytool 2>&1` works fine. So I'm guessing this application writes to STDERR normally (very odd).

Comments