在ruby课中调用刀

我想围绕刀创建一个很好的包装类,以允许程序以可读的方式运行刀命令。 我目前正在尝试使用chef gem中的knife.rb文件作为一些成功的指南。 但是,我在关闭编辑器时遇到了问题。 如果我运行以下代码:

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

它会导致以下错误:

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

任何人对如何成功地有任何想法? 是否存在一个已经存在的库,可以满足我的需要?

所以我能够解决这个问题。 它确实需要一个哈希,但它希望它是Mixlib :: CLI类的一个子集。 因此,这是以编程方式通过刀创建客户端所需的代码:

  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) 

它不是最优雅的解决方案,但它确实通过命令行使用刀并节省了必须使用系统调用来使用它。

看起来Knife正在期待你有’禁用编辑’的哈希。 试试这个:

 knife.run(['client', 'create', 'new-client'], {:"disable-editing" => true}) 

当发生类似这样的事情时,请尝试查看Array / Hash api文档以查找错误吐出的方法。 这将使您了解应该进入该参数的内容(如果您没有库的文档并且源很难阅读)。

您可以参考以下解决方案: http : //lists.opscode.com/sympa/arc/chef/2011-08/msg00014.html

  require 'rubygems' require "chef" require "chef/knife/core/bootstrap_context" require 'chef/knife' require 'chef/knife/ssh' require 'net/ssh' require 'net/ssh/multi' require 'chef/knife/bootstrap' Chef::Config.from_file(File.expand_path('~/.chef/knife.rb')) kb = Chef::Knife::Bootstrap.new kb.name_args = "some.host" kb.config[:ssh_user] = "ubuntu" kb.config[:run_list] = "role[test]" kb.config[:use_sudo] = true kb.run 

刀子解析自己。

 require 'chef/knife' Chef::Knife.run(%w(bootstrap -N chef-n1 --sudo -x dan chef-n1.dan.lan))