Skip to content

Instantly share code, notes, and snippets.

@ranjib
Last active August 29, 2015 14:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ranjib/2db397f06f8d074eb8a0 to your computer and use it in GitHub Desktop.
Save ranjib/2db397f06f8d074eb8a0 to your computer and use it in GitHub Desktop.

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'
  1. Load the corresponding class' dependencies
Knife::Plugin.load_deps
  1. 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'] 
  1. Assign all arguments that are passed via command line flags , using the config helper method
plugin.config[:argument] = 'value'
  1. 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]'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment