こんにちは!beardです!
Serverspecでは、複数のサーバを一括テストするために便利な方法があります。今回は、テスト項目ごとにコードを整理する方法も合わせてご紹介します。
Serverspecのインストールと基本的な操作については、過去の記事『 Amazon OSS編~Serverspecパート①~ 』をご覧ください。
1. 今回テストする環境
Serverspecがインストールされたサーバから以下の二つのサーバをテストします。
サーバAにhttpdをインストールして稼動させ、OSの時刻設定をJSTにしています。
サーバBはその状態でAMIを取得したものからEC2インスタンスを立ち上げたので設定はまったく同じになります。
サーバAのIPアドレス:54.64.15.205
サーバBのIPアドレス:54.64.126.211
- Serverspecがインストールされたサーバの/usr/local/serverspecに移動してserverspec-initをします。
その後テスト項目ごとにディレクトリを分けて配置します。
ディレクトリとファイル構成を以下のように変更します。
1serverspec2├Rakefile3├spec4| └web5| └httpd_spec.rb ←****_spec.rbの形式のみserverspecで読み込まれる6└ common7 └time_spec.rb ←****_spec.rbの形式のみserverspecで読み込まれるそれぞれのファイルの中身は以下のようになっています。
1#httpd_spec.rb httpdが有効になっているかの確認2require 'spec_helper'34describe package('httpd') do5 it { should be_installed }6end78describe service('httpd') do9 it { should be_enabled }10 it { should be_running }11end1213describe port(80) do14 it { should be_listening }15end1617# time_spec.rb 時刻設定の確認1819require 'spec_helper'2021describe command('date') do22 it { should return_stdout /JST/ }23end- サーバを複数まとめてテストするにはRakefileを編集します。
注意するべきはhostsの部分だけです。後はコピペで大丈夫です。
1require 'rake'2require 'rspec/core/rake_task'34hosts = [5 {6 :name => '54.64.15.205', ←テスト対象サーバAのhost名orIPアドレス7 :roles => %w( web common ), ←上のディレクトリ名がテスト項目になる8 },9 {10 :name => '54.64.126.211', ←テスト対象サーバBのhost名orIPアドレス11 :roles => %w( web common ), ←上のディレクトリ名がテスト項目になる12 },13]1415hosts = hosts.map do |host|16 {17 :name => host[:name],18 :short_name => host[:name].split('.')[0],19 :roles => host[:roles],20 }21end2223desc "Run serverspec to all hosts"24task :spec => 'serverspec:all'2526class ServerspecTask < RSpec::Core::RakeTask2728 attr_accessor :target2930 def spec_command31 cmd = super32 "env TARGET_HOST=#{target} #{cmd}"33 end3435end3637namespace :serverspec do38 task :all => hosts.map {|h| 'serverspec:' + h[:short_name] }39 hosts.each do |host|40 desc "Run serverspec to #{host[:name]}"41 ServerspecTask.new(host[:short_name].to_sym) do |t|42 t.target = host[:name]43 t.pattern = 'spec/{' + host[:roles].join(',') + '}/*_spec.rb'44 end45 end46end- spec_helper.rbも以下のように変更します。
ここではuser名だけ気をつけましょう。
1require 'serverspec'2require 'net/ssh'34include SpecInfra::Helper::Ssh5include SpecInfra::Helper::DetectOS67RSpec.configure do |c|8 c.host = ENV['TARGET_HOST']9 options = Net::SSH::Config.for(c.host)10 user = 'root'11 c.ssh = Net::SSH.start(c.host, user, options)12 c.os = backend.check_os13end- ではテストを実行します。
1$rake spec23env TARGET_HOST=54.64.15.205 /usr/bin/ruby2.0 -S rspec spec/common/time_spec.rb spec/web/httpd_spec.rb4.....56Finished in 0.19234 seconds75 examples, 0 failures89env TARGET_HOST=54.64.126.211 /usr/bin/ruby2.0 -S rspec spec/common/time_spec.rb spec/web/httpd_spec.rb10.....1112Finished in 0.16743 seconds135 examples, 0 failures2. 複数のサーバがまとめてテストされました!
いかがでしたか。
今回は同じ構成のサーバが2台ですが、もっとサーバが増えたり、テスト項目をサーバごとに変えたりといった運用も可能です。
次回もお楽しみに!!