Serverspecを使ってAmazon Linuxのテストをしてみた。
ChefやPuppetで構築した環境のテストはどうするという議論があると思いますが、TLを見ていると@mizzyさん製のServerspecというありがたいとものがあるらしいので、READMEに書いてある部分まで試してみました。
そこまでの記録を(ほぼREADMEのままですが)残しておきたいと思います。
環境準備
まずはServerspecをインストールします(Rspecが入ってない場合はそちらもインストールします)。
$ gem install rspec $ gem install serverspec
お好みのディレクトリでserverspec-initを実行すると対話形式でテスト環境の設定が出来ます。
今回テスト先の環境はAmazon Linuxなので、Red Hatを選択しています。
$ serverspec-init Select a backend type: 1) SSH 2) Exec (local) Select number: 1 Input target host name: www.okochang.com Select OS type of target host: 1) Red Hat 2) Debian 3) Gentoo 4) Solaris 5) None Select number: 1 + spec/ + spec/www.okochang.com/ + spec/www.okochang.com/httpd_spec.rb + spec/spec_helper.rb + Rakefile
こんな感じでファイルが作成されます。
$ tree ./ ./ ├── Rakefile └── spec ├── spec_helper.rb └── www.okochang.com └── httpd_spec.rb 2 directories, 3 files
Apache用のサンプルファイルが作成されていますので、自分の環境に合わせて編集します。
require 'spec_helper' describe 'httpd' do it { should be_installed } it { should be_enabled } it { should be_running } end describe 'port 80' do it { should be_listening } end describe '/etc/httpd/conf/httpd.conf' do it { should be_file } it { should contain "ServerTokens ProductOnly" } it { should contain "HostnameLookups Off" } it { should contain "ServerSignature Off" } end describe '/etc/httpd/conf.d/vhosts.conf' do it { should be_file } it { should contain "ServerName www.okochang.com" } end
せっかくなので自分なりにsshd用のテストも作ってみました。
$ vi spec/www.okochang.com/sshd_spec.rb require 'spec_helper' describe 'openssh-server' do it { should be_installed } end describe 'sshd' do it { should be_enabled } it { should be_running } end describe 'port 22' do it { should be_listening } end describe '/etc/ssh/sshd_config' do it { should be_file } it { should contain "PermitRootLogin forced-commands-only" } it { should contain "PasswordAuthentication no" } end
テスト対象にはSSHで接続するので、~/.ssh/configファイルに接続先情報を追記する事をお忘れなく。
$ vi .ssh/config 3 Host www.okochang.com 4 User ec2-user 5 Port 22 6 IdentityFile ~/.ssh/okochang-key.pem 7 StrictHostKeyChecking no 8 UserKnownHostsFile /dev/null
テストを実行してみると無事にテストが完了しました。
$ rake spec /Users/yanase/.rvm/rubies/ruby-1.9.3-p392/bin/ruby -S rspec spec/www.okochang.com/httpd_spec.rb spec/www.okochang.com/sshd_spec.rb ................. Finished in 2.3 seconds 17 examples, 0 failures
まとめ
rubygems.orgに登録されているのでServerspecの導入は簡単に出来るようです。
基本はサーバの設定を変更したらテストが通るか実行するのだと思いますが、うまーく監視サーバとかと組み合わせて定期的に実行出来ないものかなーと思っていたりもしました。