Search code examples
rubychef-infraknife

invoking knife in a ruby class


I'd like to create a nice wrapper class around knife to allow a program to run knife commands in a readable manner. I'm currently trying to use the knife.rb file in the chef gem as a guide to some success. However, I'm having an issue turning off the editor. If I run the following code:

    require 'chef/knife'
    knife = Chef::Knife.new
    knife.run(['client', 'create', 'new-client'], '--disable-editing')

it results in the following error:

    NoMethodError: undefined method `merge!' for "--disable-editing":String

Anyone have any ideas on how to do this successfully? Is there a library by chance that already exists that does what I need?


Solution

  • So I was able to solve this problem. It does indeed want a hash, but it wants it to be a subset of the Mixlib::CLI class. So, this is the code needed to create a client via knife programmatically:

        class MyCLI
          include Mixlib::CLI
        end
    
        #Add the option for disable editing. If you look in knife help, it's --disable-editing
        MyCLI.option(:disable_editing, :long => "--disable-editing", :boolean => true)
    
        #instantiate knife object and add the disable-editing flag to it
        knife = Chef::Knife.new
        knife.options=MyCLI.options
    
        #set up client creation arguments and run
        args = ['client', 'create',  'new_client', '--disable-editing' ]  
        new_client = Chef::Knife.run(args, MyCLI.options)
    

    It's not the most elegant solution, but it does use knife via the command line and saves someone from have to use a system call to use it.