forked from karmi/chef-hello-cloud
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRakefile
88 lines (65 loc) · 2.76 KB
/
Rakefile
1
2
3
4
5
6
7
8
9
10
11
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
require 'json'
begin
# Let's work around Bundler messing up with require and gems
path = Dir[ Gem.path.first + '/gems' + '/terminal-notifier-*/lib/terminal-notifier.rb' ].first
require path
rescue Exception
end
def notify options={}
return nil unless defined?(TerminalNotifier)
TerminalNotifier.notify options[:message],
title: options[:name],
subtitle: options[:public_ip],
open: "http://#{options[:public_ip]}"
end
namespace :chef do
desc "Synchronize all resources (cookbooks, roles, etc.)"
task :sync do
sh "knife cookbook upload --all --yes"
sh "knife role from file roles/*.rb"
end
end
namespace :server do
desc "Create server with specified name and role"
task :create do
["NAME", "ROLE"].each { |argument| ( puts("[!] You need to specify #{argument}"); exit(1) ) unless ENV[argument] }
start = Time.now
flavor = ENV["FLAVOR"] || "c1.xlarge"
sh "knife ec2 server create --node-name #{ENV["NAME"]} \
--ssh-user ec2-user \
--run-list 'role[#{ENV["ROLE"]}]' \
--groups #{ENV["ROLE"]} \
--flavor #{flavor} \
--distro amazon"
node = JSON.parse(`knife node show #{ENV["NAME"]} --format json --attribute ec2`) rescue nil
duration = ((Time.now-start).to_i/60.0).round
notify name: ENV["NAME"], public_ip: node["ec2"]["public_hostname"], message: "Created in #{duration} minutes" if node
end
desc "Delete server"
task :delete do
["NAME"].each { |argument| ( puts("[!] You need to specify #{argument}"); exit(1) ) unless ENV[argument] }
node = JSON.parse(`knife node show #{ENV["NAME"]} --format json --attribute ec2`) rescue nil
( puts "[!] No node named #{ENV["NAME"]} found"; exit(1) ) unless node
instance_id = node["ec2"]["instance_id"]
if instance_id
sh "knife ec2 server delete #{instance_id.strip} --print-after --yes"
sh "knife node delete #{ENV["NAME"]} --yes"
sh "knife client delete #{ENV["NAME"]} --yes"
else
puts "[!] No server for node #{ENV["NAME"]} found"
end
end
desc "Delete and terminate all nodes"
task :teardown do
prefix = ENV['PREFIX'] || 'ec2'
nodes = JSON.parse(`knife search node name:#{prefix}* --format json --attribute ec2`) rescue {}
unless nodes.empty?
nodes["rows"].each do |node|
instance_id = node["ec2"]["instance_id"] rescue nil
sh "knife ec2 server delete #{instance_id.strip} --print-after --yes" if instance_id
end
sh "knife node bulk delete '#{prefix}' --yes"
sh "knife client bulk delete '#{prefix}' --yes"
end
end
end