Carl_Friedrich_Gauss Carl_Friedrich_Gauss - 11 days ago 6
Ruby Question

Chef not processing sed correctly

Whenever I write a recipe, Chef never seems to use sed correctly. I can generally work around it with some creative grep'ing, but not in this case. I'm just trying to extract the Distinguished Name from some cert files. Removing the backslash before the single quotes, this command executes just fine on the command line. Chef also doesn't throw any errors. The "not working" part comes in because the output that is stored in the "DN" variable is just the openssl command contents, as if the sed was never ran at all. I also ran this as straight Ruby code and it executed fine. It appears to be just Chef that is casuing the issue.

filesAndExpArray = splitArray.map! do |file|
DN = shell_out("openssl x509 -noout -subject -in #{file} | sed \'s/^.*CN=//\'")
DN = DN.stdout
file + ";" + DN
end

Answer

Names starting with a capital letter in Ruby are constants, that is probably related. Use dn instead. Also while you could do this, it's going to be easier and faster to do the regex in Ruby code instead as you don't need to sort out how to fix your quoting (you probably don't need those backslashes).

filesAndExpArray = splitArray.map! do |file|
  cmd = shell_out("openssl x509 -noout -subject -in #{file}")
  dn = cmd.stdout[/^.*CN=(.*)$/, 1]
  file + ";" + dn
end

If you wanted to go even further you could ditch shell_out entirely:

filesAndExpArray = splitArray.map! do |file|
  subject = OpenSSL::X509::Certificate.new(IO.read(file)).subject
  cn = subject.to_a.find {|part| part.first == 'CN'}
  dn = cn && cn[1]
  file + ";" + dn
end