To use a knife plugin programmatically, from any ruby script, you need first
know the source of the plugin. you have to know the config options for all the
command line arguments you are interested to use. All knife plugin use mixlib-cli
interface, and the command line options can be found at the beginning of the file
(convention), declared using option
method. if you are curious take a look at
mixlib-cli readme
1.require the corresponding plugin file
require '/path/to/plugin'
- Load the corresponding class' dependencies
Knife::Plugin.load_deps
- All those arguments that are not pass via flags are assigned via
name_args
. assign an array to it
plugin = Knife::Plugin.new
plugin.name_args = ['argument']
- Assign all arguments that are passed via command line flags , using the config helper method
plugin.config[:argument] = 'value'
- Run the plugin
plugin.run
Following is an example of bootstrapping using knife ssh, that i use to bootstrap LXC. for reference, knife-ssh configs plugin can be seen here.
require 'chef/knife/bootstrap'
Chef::Knife::Bootstrap.load_deps
plugin = Chef::Knife::Bootstrap.new
plugin.name_args = ['1.2.3.4'] # ip or hostname of the target node
plugin.config[:run_list] = ['role[base]'] # should be an array
plugin.config[:use_sudo] = true
plugin.config[:ssh_user] = 'ubuntu'
plugin.config[:ssh_password] = 'ubuntu'
plugin.run
Generally this is available as a helper method. where i can pass the ip and run list
require 'chef/knife/bootstrap'
Chef::Knife::Bootstrap.load_deps
def knife_bootstrap(ip, run_list)
plugin = Chef::Knife::Bootstrap.new
plugin.name_args = ['1.2.3.4'] # ip or hostname of the target node
plugin.config[:run_list] = ['role[base]'] # should be an array
plugin.config[:use_sudo] = true
plugin.config[:ssh_user] = 'ubuntu'
plugin.config[:ssh_password] = 'ubuntu'
plugin.config[:use_sudo_password] = true
plugin.config[:distro] = 'chef-full'
plugin.run
end
knife_bootstrap('1.2.3.4', ['role[base]'])