I’ve inherited some shell scripts that are helpful for setting up our application environment using Chef and knife. That’s nice.
But what I’d really like to do is have the power and flexibility of a Ruby script to do the same thing.
If I shell out to knife I lose the real time output of the command.
It seems like I should be able to call all of knife’s functionality from within Ruby by including the ‘chef’ gem and maybe the ‘cloudstack-fog’ plug-in I use.
But I haven’t found any examples or API documentation. Trying to dig through the chef gem source is an exercise in frustration.
Shouldn’t I be able to do the equivalent of a knife cloudstack server create -E ... etc. from a Ruby script?
You can do this by using the
Kernelmodule’ssystemmethod[1], which will execute your command in a subshell and pipe its output to your current shell. I use this in many of my custom Knife plugins when I want to be able to see the realtime output of programmatically built up arguments Knife commands likeknife ssh.Here’s an example where I construct and execute what could be a very complex command:
query = "chef_environment:#{environment.name}" options = [ "-x #{::Chef::Config[:node_name]}" ].join(' ') command = %Q{knife ssh "#{query}" #{options} "#{chef_command}"} system(command)[1] http://www.ruby-doc.org/core-1.9.3/Kernel.html#method-i-system