knife-nc 0.0.0

Sign up to get free protection for your applications and to get access to all the features.
data/.gitignore ADDED
@@ -0,0 +1,34 @@
1
+ .rake_tasks~
2
+ tags
3
+ coverage
4
+ rdoc
5
+ pkg
6
+ test/tmp
7
+ test/version_tmp
8
+ tmp
9
+ pkg
10
+ *.gem
11
+ *.rbc
12
+ lib/bundler/man
13
+ spec/reports
14
+ .config
15
+ InstalledFiles
16
+ .bundle
17
+
18
+ # YARD artifacts
19
+ .yardoc
20
+ _yardoc
21
+ doc/
22
+
23
+ .DS_Store
24
+ Icon?
25
+
26
+ # Thumbnails
27
+ ._*
28
+
29
+ # Files that might appear on external disk
30
+ .Spotlight-V100
31
+ .Trashes
32
+
33
+ *.swp
34
+ *.swo
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --color
2
+ -fs
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source "http://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in knife-rackspace.gemspec
4
+ gemspec
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,82 @@
1
+ # NIFTY Cloud 向け knife プラグイン
2
+
3
+ ## 概要
4
+
5
+ knife から NIFTY Cloud のインスタンスを扱うためのプラグインです。
6
+ knife-ec2 と同じように、インスタンスを作成した上で Chef のノードとして登録 (= ブートストラップ) したり、
7
+ インスタンスを削除したりできます。
8
+
9
+ ## インストール
10
+
11
+ "chef" gem と ["ニフティクラウドSDK for Ruby" gem](http://cloud.nifty.com/api/sdk/) に依存しているので、
12
+ まだインストールしていない場合にはインストールしましょう。
13
+
14
+ # "chef" gem のインストール
15
+ gem install chef
16
+
17
+ # "ニフティクラウドSDK for Ruby" のインストール
18
+ wget http://cloud.nifty.com/api/sdk/NIFTY_Cloud_SDK_for_ruby.zip
19
+ cd NIFTY_Cloud_SDK_for_ruby
20
+ rake install
21
+
22
+ あとは gem install knife-nc を実行するだけです。
23
+
24
+ gem install knife-nc
25
+
26
+ # 設定
27
+
28
+ NIFTY CLoud REST API と通信するため、knife コマンドにアクセスキー/シークレットキーを教えてやる必要があります。
29
+ knife.rb に設定するのが一番簡単でしょう。
30
+
31
+ knife[:nc_access_key_id] = "Your NIFTY Cloud Access Key ID"
32
+ knife[:nc_secret_access_key] = "Your NIFTY Cloud Secret Access Key"
33
+
34
+ knife.rb をバージョン管理システムにコミットしている場合 (つまり誰でも閲覧可能になっている場合) には、
35
+ 環境変数から読み込ませることも可能です。
36
+
37
+ knife[:nc_access_key_id] = "#{ENV['NIFTY_CLOUD_ACCESS_KEY_ID']}"
38
+ knife[:nc_secret_access_key] = "#{ENV['NIFTY_CLOUD_SECRET_ACCESS_KEY']}"
39
+
40
+ アクセスキー/シークレットキーは knife サブコマンドの -A (--nc-access-key) と -K (--nc-secret-key) オプションで指定することもできます。
41
+
42
+ # provision a new mini instance
43
+ knife ec2 server create -r 'role[webserver]' -I 1 -T mini -A 'Your NIFTY Cloud Access Key ID' -K "Your AWS Secret Access Key"
44
+
45
+ さらに下記のオプションが knife.rb に設定可能です。
46
+
47
+ *
48
+ *
49
+
50
+ ## サブコマンド一覧
51
+
52
+ ### knife nc server create
53
+
54
+ NIFTY Cloud 上にインスタンスを作成し SSH 経由で Chef のブートストラップを行います。「ブートストラップ」というのは Chef をインストールして Chef クライアントとして Chef サーバと通信できるようにすることです。デフォルトでは centos5-gems テンプレートでブートストラップを行います。-d オプションか --template-file オプションで振る舞いを上書きすることができます。インスタンス作成時、あとから knife コマンド経由で削除可能とするために、diableApiTermination を false に設定することに注意してください。
55
+
56
+ ### knife nc server delete
57
+
58
+ 設定済みの NIFTY Cloud アカウント内のインスタンスを指定して停止・削除します。注意:デフォルトではそのインスタンスに関するノード・クライアント情報を Chef サーバ上から削除しません。削除するためには --purge フラグをつけてください。
59
+
60
+ ### knife nc server list
61
+
62
+ 現在設定されている NIFTY Cloud アカウントが持つすべてのサーバの一覧を出力します。注意:アカウントに紐づいたすべてのインスタンスを表示するので、Chef サーバに管理されていないインスタンスが表示されることもあります。
63
+
64
+ ### knife nc image list
65
+
66
+ knife-ec2 にはないオリジナルのコマンドです。現在のアカウントで利用可能なイメージの一覧を表示します。
67
+ knife nc server create コマンドの -I オプションに渡す Image ID を確認するために利用してください。
68
+
69
+ ## TODO
70
+
71
+ * nc server create の -U オプション (起動スクリプト指定) の動作確認ができていない
72
+ * nc server create の --template-file オプション (ブートストラップ用テンプレート指定) の動作確認ができていない
73
+ * nc server create の -P オプションが SSH Key のパスフレーズに適用されない
74
+ * そもそも Chef::Knife::Bootstrap が SSH キーのパスフレーズに対応していないので保留としています
75
+ * nc server create の -I オプション (イメージ ID 指定) で一部ブートストラップできないイメージがある
76
+ * CentOS 5 + 64bit の組み合わせで Ruby の OpenSSL ライブラリで "Cipher is not a module" エラーが出て止まってしまうようです
77
+ * nc server create で利用しているデフォルトの centos5-gems テンプレートを一部修正する必要があります
78
+ * EPEL rpm の URL が変更されたため現状動いていないっぽいです、Chef 本体に[こちらの修正](https://github.com/vgirnet/chef/commit/62bdc5a7415025555502583cad5f6a6543e7a954)を適用すれば動きます
79
+
80
+ ## ライセンス
81
+
82
+ Opscode Chef のプロダクトに準じて Apache Lisence, Version 2.0 を適用します。
data/Rakefile ADDED
@@ -0,0 +1,54 @@
1
+ #
2
+ # Author:: tily (<tidnlyam@gmail.com>)
3
+ # Copyright:: Copyright (c) 2012 tily
4
+ # License:: Apache License, Version 2.0
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ #
18
+
19
+ require 'bundler'
20
+ Bundler::GemHelper.install_tasks
21
+
22
+ # require 'rubygems'
23
+ # require 'rake/gempackagetask'
24
+ require 'rake/rdoctask'
25
+
26
+ begin
27
+ require 'sdoc'
28
+
29
+ Rake::RDocTask.new do |rdoc|
30
+ rdoc.title = "Chef Ruby API Documentation"
31
+ rdoc.main = "README.md"
32
+ rdoc.options << '--fmt' << 'shtml' # explictly set shtml generator
33
+ rdoc.template = 'direct' # lighter template
34
+ rdoc.rdoc_files.include("README.rdoc", "LICENSE", "spec/tiny_server.rb", "lib/**/*.rb")
35
+ rdoc.rdoc_dir = "rdoc"
36
+ end
37
+ rescue LoadError
38
+ puts "sdoc is not available. (sudo) gem install sdoc to generate rdoc documentation."
39
+ end
40
+
41
+ begin
42
+ require 'rspec/core/rake_task'
43
+
44
+ task :default => :spec
45
+
46
+ desc "Run all specs in spec directory"
47
+ RSpec::Core::RakeTask.new(:spec) do |t|
48
+ t.pattern = 'spec/unit/**/*_spec.rb'
49
+ end
50
+
51
+ rescue LoadError
52
+ STDERR.puts "\n*** RSpec not available. (sudo) gem install rspec to run unit tests. ***\n\n"
53
+ end
54
+
data/knife-nc.gemspec ADDED
@@ -0,0 +1,21 @@
1
+ # -*- encoding: utf-8 -*-
2
+ $:.push File.expand_path("../lib", __FILE__)
3
+ require "knife-nc/version"
4
+
5
+ Gem::Specification.new do |s|
6
+ s.name = "knife-nc"
7
+ s.version = Knife::Nc::VERSION
8
+ s.has_rdoc = true
9
+ s.authors = ["tily"]
10
+ s.email = ["tidnlyam@gmail.com"]
11
+ s.homepage = "https://github.com/tily/ruby-knife-nc"
12
+ s.summary = "NIFTY Cloud Support for Chef's Knife Command"
13
+ s.description = s.summary
14
+ s.extra_rdoc_files = ["README.md", "LICENSE" ]
15
+
16
+ s.files = `git ls-files`.split("\n")
17
+ s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
18
+ s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
19
+ s.require_paths = ["lib"]
20
+
21
+ end
@@ -0,0 +1,90 @@
1
+ #
2
+ # Author:: tily (<tidnlyam@gmail.com>)
3
+ # Copyright:: Copyright (c) 2011 tily
4
+ # License:: Apache License, Version 2.0
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ #
18
+
19
+ require 'chef/knife'
20
+
21
+ class Chef
22
+ class Knife
23
+ module NcBase
24
+
25
+ # :nodoc:
26
+ # Would prefer to do this in a rational way, but can't be done b/c of
27
+ # Mixlib::CLI's design :(
28
+ def self.included(includer)
29
+ includer.class_eval do
30
+
31
+ deps do
32
+ require 'NIFTY'
33
+ require 'readline'
34
+ require 'chef/json_compat'
35
+ end
36
+
37
+ option :nc_access_key,
38
+ :short => "-A ACCESS_KEY",
39
+ :long => "--access-key KEY",
40
+ :description => "Your NIFTY Cloud Access Key ID",
41
+ :proc => Proc.new { |key| Chef::Config[:knife][:nc_access_key] = key }
42
+
43
+ option :nc_secret_key,
44
+ :short => "-K SECRET_KEY",
45
+ :long => "--secret-key SECRET",
46
+ :description => "Your NIFTY Cloud API Secret Access Key",
47
+ :proc => Proc.new { |key| Chef::Config[:knife][:nc_secret_key] = key }
48
+ end
49
+ end
50
+
51
+ def connection
52
+ @connection ||= begin
53
+ connection = NIFTY::Cloud::Base.new(
54
+ :access_key => Chef::Config[:knife][:nc_access_key],
55
+ :secret_key => Chef::Config[:knife][:nc_secret_key]
56
+ )
57
+ end
58
+ end
59
+
60
+ def locate_config_value(key)
61
+ key = key.to_sym
62
+ Chef::Config[:knife][key] || config[key]
63
+ end
64
+
65
+ def msg_pair(label, value, color=:cyan)
66
+ if value && !value.to_s.empty?
67
+ puts "#{ui.color(label, color)}: #{value}"
68
+ end
69
+ end
70
+
71
+ def validate!(keys=[:nc_access_key, :nc_secret_key])
72
+ errors = []
73
+
74
+ keys.each do |k|
75
+ pretty_key = k.to_s.gsub(/_/, ' ').gsub(/\w+/){ |w| (w =~ /(ssh)|(nc)|(id)/i) ? w.upcase : w.capitalize }
76
+ if Chef::Config[:knife][k].nil?
77
+ errors << "You did not provide a valid '#{pretty_key}' value."
78
+ end
79
+ end
80
+
81
+ if errors.each{|e| ui.error(e)}.any?
82
+ exit 1
83
+ end
84
+ end
85
+
86
+ end
87
+ end
88
+ end
89
+
90
+
@@ -0,0 +1,53 @@
1
+ #
2
+ # Author:: tily (<tidnlyam@gmail.com>)
3
+ # Copyright:: Copyright (c) 2012 tily
4
+ # License:: Apache License, Version 2.0
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ #
18
+
19
+ require 'chef/knife/nc_base'
20
+
21
+ class Chef
22
+ class Knife
23
+ class NcImageList < Knife
24
+
25
+ include Knife::NcBase
26
+
27
+ banner "knife nc image list (options)"
28
+
29
+ def run
30
+ $stdout.sync = true
31
+
32
+ validate!
33
+
34
+ image_list = [
35
+ ui.color('Image ID', :bold),
36
+ ui.color('Name', :bold),
37
+ ui.color('Owner', :bold),
38
+ ui.color('State', :bold)
39
+ ]
40
+ connection.describe_images.imagesSet.item.each do |image|
41
+ image_list << image.imageId
42
+ image_list << image.name
43
+ image_list << "#{image.imageOwnerId} (#{image.imageOwnerAlias})"
44
+ image_list << "#{image.imageState} (#{image.isPublic ? 'public' : 'private'})"
45
+ end
46
+ puts ui.list(image_list, :columns_across, 4)
47
+
48
+ end
49
+ end
50
+ end
51
+ end
52
+
53
+
@@ -0,0 +1,299 @@
1
+ #
2
+ # Author:: tily (<tidnlyam@gmail.com>)
3
+ # Copyright:: Copyright (c) 2012 tily
4
+ # License:: Apache License, Version 2.0
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ #
18
+
19
+ require 'chef/knife/nc_base'
20
+
21
+ class Chef
22
+ class Knife
23
+ class NcServerCreate < Knife
24
+
25
+ include Knife::NcBase
26
+
27
+ deps do
28
+ require 'NIFTY'
29
+ require 'readline'
30
+ require 'chef/json_compat'
31
+ require 'chef/knife/bootstrap'
32
+ Chef::Knife::Bootstrap.load_deps
33
+ end
34
+
35
+ banner "knife nc server create INSTANCE_ID (options)"
36
+
37
+ attr_accessor :initial_sleep_delay
38
+
39
+ option :nc_instance_type,
40
+ :short => "-T INSTANCE_TYPE",
41
+ :long => "--instance-type INSTANCE_TYPE",
42
+ :description => "The instance type of server (small, medium, etc)",
43
+ :proc => Proc.new { |t| Chef::Config[:knife][:nc_instance_type] = t },
44
+ :default => "small"
45
+
46
+ option :nc_image_id,
47
+ :short => "-I IMAGE_ID",
48
+ :long => "--image IMAGE_ID",
49
+ :description => "The Image ID for the server",
50
+ :proc => Proc.new { |i| Chef::Config[:knife][:nc_image_id] = i }
51
+
52
+ option :security_group,
53
+ :short => "-G GROUP",
54
+ :long => "--group GROUP",
55
+ :description => "The security group for this server"
56
+
57
+ option :chef_node_name,
58
+ :short => "-N NAME",
59
+ :long => "--node-name NAME",
60
+ :description => "The Chef node name for your new node"
61
+
62
+ option :nc_ssh_key_id,
63
+ :short => "-S KEY",
64
+ :long => "--ssh-key KEY",
65
+ :description => "The NIFTY Cloud SSH key id",
66
+ :proc => Proc.new { |key| Chef::Config[:knife][:nc_ssh_key_id] = key }
67
+
68
+ option :ssh_user,
69
+ :short => "-x USERNAME",
70
+ :long => "--ssh-user USERNAME",
71
+ :description => "The ssh username",
72
+ :default => "root"
73
+
74
+ option :ssh_password,
75
+ :short => "-P PASSWORD",
76
+ :long => "--ssh-password PASSWORD",
77
+ :description => "The ssh password"
78
+
79
+ option :ssh_locally,
80
+ :short => "-L",
81
+ :long => "--ssh-locally",
82
+ :description => "bootstrap via ssh using private IP address"
83
+
84
+ option :identity_file,
85
+ :short => "-i IDENTITY_FILE",
86
+ :long => "--identity-file IDENTITY_FILE",
87
+ :description => "The SSH identity file used for authentication"
88
+
89
+ option :prerelease,
90
+ :long => "--prerelease",
91
+ :description => "Install the pre-release chef gems"
92
+
93
+ option :nc_bootstrap_version,
94
+ :long => "--bootstrap-version VERSION",
95
+ :description => "The version of Chef to install",
96
+ :proc => Proc.new { |v| Chef::Config[:knife][:nc_bootstrap_version] = v }
97
+
98
+ option :nc_distro,
99
+ :short => "-d DISTRO",
100
+ :long => "--distro DISTRO",
101
+ :description => "Bootstrap a distro using a template",
102
+ :proc => Proc.new { |d| Chef::Config[:knife][:nc_distro] = d },
103
+ :default => "centos5-gems"
104
+
105
+ option :nc_template_file,
106
+ :long => "--template-file TEMPLATE",
107
+ :description => "Full path to location of template to use",
108
+ :proc => Proc.new { |t| Chef::Config[:knife][:nc_template_file] = t },
109
+ :default => false
110
+
111
+ option :run_list,
112
+ :short => "-r RUN_LIST",
113
+ :long => "--run-list RUN_LIST",
114
+ :description => "Comma separated list of roles/recipes to apply",
115
+ :proc => lambda { |o| o.split(/[\s,]+/) },
116
+ :default => []
117
+
118
+ option :no_host_key_verify,
119
+ :long => "--no-host-key-verify",
120
+ :description => "Disable host key verification",
121
+ :boolean => true,
122
+ :default => false
123
+
124
+ option :nc_user_data,
125
+ :long => "--user-data USER_DATA_FILE",
126
+ :short => "-U USER_DATA_FILE",
127
+ :description => "The NIFTY Cloud User Data file to provision the instance with",
128
+ :proc => Proc.new { |m| Chef::Config[:knife][:nc_user_data] = m },
129
+ :default => nil
130
+
131
+ def tcp_test_ssh(hostname)
132
+ tcp_socket = TCPSocket.new(hostname, 22)
133
+ readable = IO.select([tcp_socket], nil, nil, 5)
134
+ if readable
135
+ Chef::Log.debug("sshd accepting connections on #{hostname}, banner is #{tcp_socket.gets}")
136
+ yield
137
+ true
138
+ else
139
+ false
140
+ end
141
+ rescue SocketError
142
+ sleep 2
143
+ false
144
+ rescue Errno::ETIMEDOUT
145
+ false
146
+ rescue Errno::EPERM
147
+ false
148
+ rescue Errno::ECONNREFUSED
149
+ sleep 2
150
+ false
151
+ rescue Errno::EHOSTUNREACH
152
+ sleep 2
153
+ false
154
+ ensure
155
+ tcp_socket && tcp_socket.close
156
+ end
157
+
158
+ def run
159
+ $stdout.sync = true
160
+ NIFTY::LOG.level = Logger::DEBUG
161
+
162
+ validate!
163
+
164
+ msg_pair("Instance ID", @name_args.first)
165
+ msg_pair("Instance Type", locate_config_value(:nc_instance_type))
166
+ msg_pair("Image", locate_config_value(:nc_image_id))
167
+ msg_pair("SSH Key", locate_config_value(:nc_ssh_key_id))
168
+ msg_pair("Security Group", config[:security_group])
169
+
170
+ puts "\n"
171
+ confirm("Do you really want to create this server")
172
+
173
+ # monkey patch NIFTY::Cloud::Base (ignore password option and enable user data)
174
+ connection.instance_eval do
175
+ def run_instances(options)
176
+ options[:password] = 'ignoreme'
177
+ @user_data = options[:user_data]
178
+ super(options)
179
+ end
180
+ def response_generator(params)
181
+ params.delete('Password') if params['Password'] == 'ignoreme'
182
+ if @user_data
183
+ params['UserData'] = extract_user_data(:user_data => @user_data, :base64_encoded => true)
184
+ params['UserData.Encoding'] = 'base64'
185
+ end
186
+ super(params)
187
+ end
188
+ end
189
+ server = connection.run_instances(create_server_def).instancesSet.item.first
190
+
191
+ msg_pair("Instance ID", server.instanceId)
192
+ msg_pair("Instance Type", server.instanceType)
193
+ msg_pair("Image", server.imageId)
194
+ msg_pair("SSH Key", server.keyName)
195
+
196
+ print "\n#{ui.color("Waiting for server", :magenta)}"
197
+
198
+ # wait for it to be ready to do stuff
199
+ while server.instanceState.name != 'running'
200
+ print "."
201
+ server = connection.describe_instances(:instance_id => server.instanceId).reservationSet.item.first.instancesSet.item.first
202
+ sleep 5
203
+ end
204
+
205
+ puts("done\n")
206
+
207
+ msg_pair("Public IP Address", server.ipAddress)
208
+ msg_pair("Private IP Address", server.privateIpAddress)
209
+
210
+ ssh_ip_address = config[:ssh_locally] ? server.privateIpAddress : server.ipAddress
211
+ print "\n#{ui.color("Waiting for sshd", :magenta)} (using #{ssh_ip_address})"
212
+
213
+ print(".") until tcp_test_ssh(ssh_ip_address) {
214
+ sleep @initial_sleep_delay ||= 10
215
+ puts("done")
216
+ }
217
+
218
+ bootstrap_for_node(server, ssh_ip_address).run
219
+
220
+ puts "\n"
221
+ msg_pair("Instance ID", server.instanceId)
222
+ msg_pair("Instance Type", server.instanceType)
223
+ msg_pair("Image ID", server.imageId)
224
+ msg_pair("Security Group", config[:security_group])
225
+ msg_pair("SSH Key", server.keyName)
226
+ msg_pair("Public IP Address", server.ipAddress)
227
+ msg_pair("Private IP Address", server.privateIpAddress)
228
+ msg_pair("Environment", config[:environment] || '_default')
229
+ msg_pair("Run List", config[:run_list].join(', '))
230
+ end
231
+
232
+ def bootstrap_for_node(server,fqdn)
233
+ bootstrap = Chef::Knife::Bootstrap.new
234
+ bootstrap.name_args = [fqdn]
235
+ bootstrap.config[:run_list] = config[:run_list]
236
+ bootstrap.config[:ssh_user] = config[:ssh_user]
237
+ bootstrap.config[:ssh_password] = config[:ssh_password]
238
+ bootstrap.config[:identity_file] = config[:identity_file]
239
+ bootstrap.config[:chef_node_name] = config[:chef_node_name] || server.instanceId
240
+ bootstrap.config[:prerelease] = config[:prerelease]
241
+ bootstrap.config[:bootstrap_version] = locate_config_value(:nc_bootstrap_version)
242
+ bootstrap.config[:distro] = locate_config_value(:nc_distro)
243
+ bootstrap.config[:use_sudo] = true unless config[:ssh_user] == 'root'
244
+ bootstrap.config[:template_file] = locate_config_value(:nc_template_file)
245
+ bootstrap.config[:environment] = config[:environment]
246
+ bootstrap
247
+ end
248
+
249
+ def image
250
+ @image ||= connection.describe_images(:image_id => locate_config_value(:nc_image_id)).imagesSet.item.first
251
+ end
252
+
253
+ def validate!
254
+ super([:nc_image_id, :nc_ssh_key_id, :nc_access_key, :nc_secret_key])
255
+
256
+ errors = []
257
+
258
+ if @name_args.empty?
259
+ errors << "You have not provided a valid instance ID."
260
+ end
261
+
262
+ if config[:security_group].nil?
263
+ errors << "You have not provided a valid Security Group."
264
+ end
265
+
266
+ [:identity_file, :nc_template_file, :nc_user_data].each do |x|
267
+ if (path = locate_config_value(x)) && !File.exists?(path)
268
+ errors << "File does not exist: #{path}"
269
+ end
270
+ end
271
+
272
+ if errors.each{|e| ui.error(e)}.any?
273
+ exit 1
274
+ end
275
+ end
276
+
277
+ def create_server_def
278
+ server_def = {
279
+ :instance_id => @name_args.first,
280
+ :image_id => locate_config_value(:nc_image_id),
281
+ :instance_type => locate_config_value(:nc_instance_type),
282
+ :security_group => config[:security_group],
283
+ :key_name => Chef::Config[:knife][:nc_ssh_key_id],
284
+ :disable_api_termination => false # for 'knife nc server delete' command
285
+ }
286
+
287
+ if Chef::Config[:knife][:nc_user_data]
288
+ begin
289
+ server_def.merge!(:user_data => File.read(Chef::Config[:knife][:nc_user_data]))
290
+ rescue
291
+ ui.warn("Cannot read #{Chef::Config[:knife][:nc_user_data]}: #{$!.inspect}. Ignoring option.")
292
+ end
293
+ end
294
+
295
+ server_def
296
+ end
297
+ end
298
+ end
299
+ end
@@ -0,0 +1,111 @@
1
+ #
2
+ # Author:: tily (<tidnlyam@gmail.com>)
3
+ # Copyright:: Copyright (c) 2012 tily
4
+ # License:: Apache License, Version 2.0
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ #
18
+
19
+ require 'chef/knife/nc_base'
20
+
21
+ # These two are needed for the '--purge' deletion case
22
+ require 'chef/node'
23
+ require 'chef/api_client'
24
+
25
+ class Chef
26
+ class Knife
27
+ class NcServerDelete < Knife
28
+
29
+ include Knife::NcBase
30
+
31
+ banner "knife nc server delete INSTANCE_ID_1 [INSTANCE_ID_2 ...] (options)"
32
+
33
+ option :purge,
34
+ :short => "-P",
35
+ :long => "--purge",
36
+ :boolean => true,
37
+ :default => false,
38
+ :description => "Destroy corresponding node and client on the Chef Server, in addition to destroying the NIFTY Cloud node itself. Assumes node and client have the same name as the server (if not, add the '--node-name' option)."
39
+
40
+ option :chef_node_name,
41
+ :short => "-N NAME",
42
+ :long => "--node-name NAME",
43
+ :description => "The name of the node and client to delete, if it differs from the server name. Only has meaning when used with the '--purge' option."
44
+
45
+ # Extracted from Chef::Knife.delete_object, because it has a
46
+ # confirmation step built in... By specifying the '--purge'
47
+ # flag (and also explicitly confirming the server destruction!)
48
+ # the user is already making their intent known. It is not
49
+ # necessary to make them confirm two more times.
50
+ def destroy_item(klass, name, type_name)
51
+ begin
52
+ object = klass.load(name)
53
+ object.destroy
54
+ ui.warn("Deleted #{type_name} #{name}")
55
+ rescue Net::HTTPServerException
56
+ ui.warn("Could not find a #{type_name} named #{name} to delete!")
57
+ end
58
+ end
59
+
60
+ def run
61
+
62
+ validate!
63
+
64
+ @name_args.each do |instance_id|
65
+
66
+ begin
67
+ server = connection.describe_instances(:instance_id => instance_id).reservationSet.item.first.instancesSet.item.first
68
+
69
+ msg_pair("Instance ID", server.instanceId)
70
+ msg_pair("Instance Type", server.instanceType)
71
+ msg_pair("Image ID", server.imageId)
72
+ #msg_pair("Security Groups", server.groups.join(", "))
73
+ msg_pair("SSH Key", server.keyName)
74
+ msg_pair("Root Device Type", server.root_device_type)
75
+ msg_pair("Public IP Address", server.ipAddress)
76
+ msg_pair("Private IP Address", server.privateIpAddress)
77
+
78
+ puts "\n"
79
+ confirm("Do you really want to delete this server")
80
+
81
+ print "\n#{ui.color("Waiting for server to shutdown", :magenta)}"
82
+ connection.stop_instances(:instance_id => instance_id, :force => true)
83
+ while server.instanceState.name != 'stopped'
84
+ print "."
85
+ server = connection.describe_instances(:instance_id => instance_id).reservationSet.item.first.instancesSet.item.first
86
+ sleep 5
87
+ end
88
+
89
+ puts("done\n")
90
+
91
+ connection.terminate_instances(:instance_id => instance_id)
92
+
93
+ ui.warn("Deleted server #{server.id}")
94
+
95
+ if config[:purge]
96
+ thing_to_delete = config[:chef_node_name] || instance_id
97
+ destroy_item(Chef::Node, thing_to_delete, "node")
98
+ destroy_item(Chef::ApiClient, thing_to_delete, "client")
99
+ else
100
+ ui.warn("Corresponding node and client for the #{instance_id} server were not deleted and remain registered with the Chef Server")
101
+ end
102
+
103
+ rescue NoMethodError
104
+ ui.error("Could not locate server '#{instance_id}'. Please verify it was provisioned in the '#{locate_config_value(:region)}' region.")
105
+ end
106
+ end
107
+ end
108
+
109
+ end
110
+ end
111
+ end
@@ -0,0 +1,73 @@
1
+ #
2
+ # Author:: tily (<tidnlyam@gmail.com>)
3
+ # Copyright:: Copyright (c) 2012 tily
4
+ # License:: Apache License, Version 2.0
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ #
18
+
19
+ require 'chef/knife/nc_base'
20
+
21
+ class Chef
22
+ class Knife
23
+ class NcServerList < Knife
24
+
25
+ include Knife::NcBase
26
+
27
+ banner "knife nc server list (options)"
28
+
29
+ def run
30
+ $stdout.sync = true
31
+
32
+ validate!
33
+
34
+ server_list = [
35
+ ui.color('Instance ID', :bold),
36
+ ui.color('Public IP', :bold),
37
+ ui.color('Private IP', :bold),
38
+ ui.color('Flavor', :bold),
39
+ ui.color('Image', :bold),
40
+ ui.color('SSH Key', :bold),
41
+ ui.color('Security Group', :bold),
42
+ ui.color('State', :bold)
43
+ ]
44
+ connection.describe_instances.reservationSet.item.each do |instance|
45
+ server = instance.instancesSet.item.first
46
+ group = instance.groupSet
47
+ server_list << server.instanceId
48
+ server_list << server.ipAddress.to_s
49
+ server_list << server.privateIpAddress.to_s
50
+ server_list << server.instanceType
51
+ server_list << server.imageId
52
+ server_list << server.keyName
53
+ server_list << (group ? group.item.first.groupId : '')
54
+ server_list << begin
55
+ state = server.instanceState.name
56
+ case state
57
+ when 'sotopped', 'warning', 'waiting', 'creating', 'suspending', 'uploading', 'import_error'
58
+ ui.color(state, :red)
59
+ when 'pending'
60
+ ui.color(state, :yellow)
61
+ else
62
+ ui.color(state, :green)
63
+ end
64
+ end
65
+ end
66
+ puts ui.list(server_list, :columns_across, 8)
67
+
68
+ end
69
+ end
70
+ end
71
+ end
72
+
73
+
@@ -0,0 +1,7 @@
1
+ module Knife
2
+ module Nc
3
+ VERSION = "0.0.0"
4
+ MAJOR, MINOR, TINY = VERSION.split('.')
5
+ end
6
+ end
7
+
@@ -0,0 +1,6 @@
1
+ $:.unshift File.expand_path('../../lib', __FILE__)
2
+ require 'chef'
3
+ require 'chef/knife/nc_server_create'
4
+ require 'chef/knife/nc_server_delete'
5
+ require 'chef/knife/nc_server_list'
6
+ require 'chef/knife/nc_image_list'
metadata ADDED
@@ -0,0 +1,62 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: knife-nc
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.0
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - tily
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2012-03-20 00:00:00.000000000Z
13
+ dependencies: []
14
+ description: NIFTY Cloud Support for Chef's Knife Command
15
+ email:
16
+ - tidnlyam@gmail.com
17
+ executables: []
18
+ extensions: []
19
+ extra_rdoc_files:
20
+ - README.md
21
+ - LICENSE
22
+ files:
23
+ - .gitignore
24
+ - .rspec
25
+ - Gemfile
26
+ - LICENSE
27
+ - Rakefile
28
+ - knife-nc.gemspec
29
+ - lib/chef/knife/nc_base.rb
30
+ - lib/chef/knife/nc_image_list.rb
31
+ - lib/chef/knife/nc_server_create.rb
32
+ - lib/chef/knife/nc_server_delete.rb
33
+ - lib/chef/knife/nc_server_list.rb
34
+ - lib/knife-nc/version.rb
35
+ - spec/spec_helper.rb
36
+ - README.md
37
+ homepage: https://github.com/tily/ruby-knife-nc
38
+ licenses: []
39
+ post_install_message:
40
+ rdoc_options: []
41
+ require_paths:
42
+ - lib
43
+ required_ruby_version: !ruby/object:Gem::Requirement
44
+ none: false
45
+ requirements:
46
+ - - ! '>='
47
+ - !ruby/object:Gem::Version
48
+ version: '0'
49
+ required_rubygems_version: !ruby/object:Gem::Requirement
50
+ none: false
51
+ requirements:
52
+ - - ! '>='
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ requirements: []
56
+ rubyforge_project:
57
+ rubygems_version: 1.8.13
58
+ signing_key:
59
+ specification_version: 3
60
+ summary: NIFTY Cloud Support for Chef's Knife Command
61
+ test_files:
62
+ - spec/spec_helper.rb