2

I'm curious, is there a possibility to use shellout in ruby scripts outside of Chef? How to set up this?

laimison
  • 1,409
  • 3
  • 17
  • 39

1 Answers1

1

gem install mixlib-shellout

and in the ruby script

require 'mixlib/shellout'
cmd = Mixlib::ShellOut.new('linux cmd')
cmd.run_command
# And then optionally, to raise an exception if the command fails like shell_out!()
cmd.error!

ETA: If you want to avoid creating the instance yourself, I usually dump this wrapper fucntion in scripts where I use it:

def shellout(cmd, ok_exits = [0])
  run = Mixlib::ShellOut.new(cmd)
  run.run_command
  if run.error? || !ok_exits.include?(run.exitstatus)
    puts "#{cmd} failed: #{run.stderr}"
    exit 2
  end
  run.stdout
end
Karen B
  • 2,693
  • 1
  • 17
  • 19
  • 2
    That will only give you the base API, the `shell_out()` helper actually comes from Chef. I'll edit your example :) – coderanger Jul 16 '16 at 03:07
  • So to summarize `Mixlib::ShellOut.new` should be used? The helper `shell_out` is offered only by Chef? – laimison Jul 18 '16 at 13:51
  • 1
    `Mixlib::Shellout` is a class, so you need to initialize instances of it. Chef wraps this in a module which can be included to get the class methods, but it's Chef-environment-dependent. You could wrap your own module, though. https://github.com/chef/chef/blob/c1a389c2a8452e9b796aa1d34c4d9e51f4af30c7/lib/chef/mixin/shell_out.rb – Karen B Jul 18 '16 at 22:20
  • Personally, I define `require 'mixlib/shellout'; def shell_out(cmd); so = Mixlib::ShellOut.new(cmd, timeout: 60); so.run_command; so; end`. This works exactly as Chef component in terms of `stdout`, `stderr` and `exitstatus`. Try `a = shell_out('ls')` and `puts a.stdout`. Mixlib must be installed with gem. – laimison Sep 07 '17 at 16:50