Class: VagrantChefnode::Command

Inherits:
Object
  • Object
show all
Defined in:
lib/vagrant-chefnode/command.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, env) ⇒ Command

Returns a new instance of Command.



7
8
9
10
# File 'lib/vagrant-chefnode/command.rb', line 7

def initialize(app, env)
  @app = app
  @env = env
end

Instance Method Details

#call(env) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/vagrant-chefnode/command.rb', line 12

def call(env)
  require 'chef'
  require 'chef/config'
  require 'chef/knife'
  knife_config = File.expand_path("../../../../../../.chef/knife.rb", File.dirname(__FILE__))
  ::Chef::Config.from_file(knife_config)

  chef_server_url = ::Chef::Config[:chef_server_url]
  defined_chef_server_url = ""

  provisioners = env[:machine].config.vm.provisioners.map do |provisioner|
    if provisioner.name == :chef_client then
      defined_chef_server_url = provisioner.config.chef_server_url
    end
  end

  if chef_server_url == "" || defined_chef_server_url == "" || chef_server_url != defined_chef_server_url then
    @app.call(env)
    return
  end

  node = env[:machine].config.vm.hostname
  message = "Are you sure you want to remove node and client named '#{node}' from chef server ? [y/N] "
  choice = env[:ui].ask(message)
  if choice.upcase != "Y" then
    @app.call(env)
    return
  end

  ["client", "node"].each do |elm|
    env[:ui].info "Attempting to remove #{elm} '#{node}' from chef server."
    begin
      ::Chef::REST.new(chef_server_url).delete_rest("#{elm}s/#{node}")
    rescue Net::HTTPServerException => e
      if e.message == '404 "Not Found"'
        env[:ui].info "#{elm} '#{node}' not found."
      else
        env[:ui].error "An error occured. You will have to remove the #{elm} manually."
      end
    rescue Exception => e
        env[:ui].error "An error occured. You will have to remove the #{elm} manually."
    else
      env[:ui].info "#{elm} '#{node}' successfully removed from chef server."
    end
  end

  @app.call(env)
end