[chef] Re: Re: how could I use knife programmatically in a ruby script?


Chronological Thread 
  • From: Bryan Berry < >
  • To:
  • Subject: [chef] Re: Re: how could I use knife programmatically in a ruby script?
  • Date: Wed, 23 Nov 2011 18:25:46 +0100

toda raba! ata totach!

you've saved me a good bit of effort

On Wed, Nov 23, 2011 at 6:22 PM, Haim Ashkenazi < "> > wrote:
Hi Bryan

Here's part of the code I use to launch knife bootstrap programatically. It's a mix of several parts so it won't work as is, but you can figure out the variables:

require "chef"
require 'chef/knife'
require 'chef/knife/bootstrap'
require "chef/knife/core/bootstrap_context"
require 'chef/knife/ssh'
require 'net/ssh'
require 'net/ssh/multi'
config_file = File.exists?(File.join(Dir.getwd, '.chef', 'knife.rb')) ?
              File.join(Dir.getwd, '.chef', 'knife.rb') :
              File.join(File.expand_path('~'), '.chef', 'knife.rb')
Chef::Config.from_file(config_file)
kb = Chef::Knife::Bootstrap.new
kb.name_args = target
Chef::Config[:environment] = options[:env]
kb.config[:ssh_user]       = "ubuntu"
kb.config[:run_list]       = options[:run_list]
kb.config[:use_sudo]       = true
kb.config[:chef_node_name] = name
kb.run

HTH

Haim

On Wed, Nov 23, 2011 at 7:14 PM, Bryan Berry < " target="_blank"> > wrote:
https://gist.github.com/1389228


Instead of shelling out to knife each time, could I just require 'Chef', initialize a few values, and work from there?

I might be able to figure it out by looking thru the chef source code, but I am lazy, so I thought I would ask first ;)

#!/usr/bin/env ruby

servers = %x[ knife search node "name:*econ*" -i].split
servers = servers.slice(3, servers.length)

servers.each do |s|
  run_list_str = %[knife node show #{s} -r -f json]
  run_list = JSON.parse(s_run_list)
  if not run_list.include? "role[base]"
    %x[knife node run_list add #{s} "role[base]"]
  end
  if not run_list.include? "role[int0]" or not run_list.include? "role[ext0]"
    if s =~ /^ext.*$/
      %x[knife node run_list add #{s} "role[ext0]"]
    else
      %x[knife node run_list add #{s} "role[int0]"]
    end
  end
  if not run_list.include? "role[econ]"
    %x[knife node run_list add #{s} "role[econ]"]
  end
  %x[ knife ssh name:${s} "chef-client" -x root -i .chef/identity ]
end



--
Haim




Archive powered by MHonArc 2.6.16.

§