double-z
6/2/2011 - 8:55 PM

Set node attributes, run_list, chef_environment, etc

Set node attributes, run_list, chef_environment, etc

# put this in CHEF_REPO/nodes/my_node.example.com

chef_environment("production")

run_list([
  "role[base]",
  "role[webapp]"
])

normal["something"] = {
  :this => "that"
}
require 'chef/knife'

module Limelight
  class NodeConfigure < Chef::Knife

    deps do
      require 'chef/search/query'
      require 'chef/knife/search'
    end

    banner "knife node configure NODE"

    def display_node(node, name, color)
      ui.msg(ui.color("", color))
      ui.msg(ui.color("#{name}:", color, :bold))
      ui.msg("  #{ui.color('Environment: ', color, :bold)}#{ui.color(node.chef_environment, color)}")
      ui.msg(ui.color("  Run List:", color, :bold))
      node.run_list.each do |item|
        ui.msg(ui.color("    #{item}", color))
      end
      ui.msg ""
    end

    def run
      unless @node_name = name_args[0]
        ui.error "You need to specify a node"
        exit 1
      end
      @file = File.join("nodes", "#{@node_name}")

      ui.msg "Looking for #{@node_name} configuration file in #{@file}"

      if !File.exist?(@file)
        ui.error "#{@file} does not exist"
        exit 1
      end

      new_node = Chef::Node.new
      new_node.from_file(@file)

      ui.msg "Found configuration. Loading node details."

      searcher = Chef::Search::Query.new
      result = searcher.search(:node, "name:#{@node_name}")

      knife_search = Chef::Knife::Search.new
      nodes = result.first.select{|node| !node.nil?}
      current_node = nodes.first

      if current_node.nil?
        ui.error "Could not find an existing node named #{@node_name}"
        exit 1
      end

      display_node(new_node, "New Node", :green)
      display_node(current_node, "Current Node", :red)

      response = ask_question("Are you sure you want to update this node? (Y/N): ")

      if response == "Y"
        ui.msg "Loaded node details. Applying configuration from file."
        current_node.from_file(@file)
        current_node.save

        ui.msg "Updated node. Printing new state."

        knife_search = Chef::Knife::Search.new
        knife_search.name_args = ['node', "name:#{@node_name}"]
        knife_search.run
      else
        ui.error("You are not sure.  Exiting.")
      end
    end
  end
end
knife node configure my_node.example.com