Serverspecでテストを自動化してみた

こんにちはKuboです。

ある現場ではお客様にサーバを引き渡すときにチェックリストを用意して一項目づつエビデンスのキャプチャとってテストして渡してるって聞いて涙が出そうになりました。

どうにかして自動で出来ないの?

そこでServerspecを使ってそのテスト自動化してみます。

 

Serverspecとは

Serverspec(サーバスペック)とは、サーバ状態のテスト自動化フレームワークで言語はRubyで実装されており、RubyやRuby向けのテストフレームワーク「RSpec」の機能を活用して構築されている。UNIX/LinuxサーバとWindowsサーバに対応します。

環境構築

では早速インストールしてみます。

rubyのインストール

rubyのインストールはyumで行います。

$ yum installruby

Serverspecのインストール

ServerspecはRuby向けのパッケージ管理システムでRubyGems向けパッケージとして提供されています。

また、Serverspecに付属するひな形生成ツールで作られたスクリプトの実行にはRakeが必要となり一緒にインストールします。

$ gem install serverspecrake highline

インストール確認

Severspecが入ったか確認します。

$ gem list serverspec

*** LOCAL GEMS ***

serverspec (2.41.3)

テストを行う

テストコードの雛形生成

テストの雛形を作るコマンドを実行します。

$ serverspec-init

すると以下のように対話形式で雛形を作っていきます。

Select OS type:

1) UN*X
2) Windows

Select number: 1

Select a backend type:

1) SSH
2) Exec (local)

Select number: 1

Vagrant instance y/n: n
Input target host name: hogehoge.local
+ spec/
+ spec/hogehoge.local/
+ spec/hogehoge.local/sample_spec.rb
+ spec/spec_helper.rb
+ Rakefile

テストコードを書く

ファイルを開いて見ます。

vi spec/hogehoge.local/sample_spec.rb

するとこんなにたくさん!雛形が!

require 'spec_helper'

describe package('httpd'), :if => os[:family] == 'redhat' do
it { should be_installed }
end

describe package('apache2'), :if => os[:family] == 'ubuntu' do
it { should be_installed }
end

describe service('httpd'), :if => os[:family] == 'redhat' do
it { should be_enabled }
it { should be_running }
end

describe service('apache2'), :if => os[:family] == 'ubuntu' do
it { should be_enabled }
it { should be_running }
end

describe service('org.apache.httpd'), :if => os[:family] == 'darwin' do
it { should be_enabled }
it { should be_running }
end

describe port(80) do
it { should be_listening }
end

っと思ったら「redhat」と「ubuntu」で分かれてるだけなのでいらないのを消す。

require 'spec_helper'

describe package('httpd'), :if => os[:family] == 'redhat' do
it { should be_installed }
end

describe service('httpd'), :if => os[:family] == 'redhat' do
it { should be_enabled }
it { should be_running }
end

describe port(80) do
it { should be_listening }
end

テストの内容は以下の3つです。

  • httpdがインストールされているか
  • httpdのサービスが起動しているか
  • 80番ポートがリッスンか

テスト実行

$ rake spec

するとこんな感じで結果が返ってきます。

Package "httpd"
  should be installed

Service "httpd"
  should be enabled
  should be running

Port "80"
  should be listening

Finished in 0.41725 seconds (files took 0.24948 seconds to load)
4 examples, 0 failures

何のテストをしてOKだったのか出力結果を見るとわかるのでこのログ・ファイルをエビデンスにすればいいですね!

みんなの喜ぶ顔が目に浮かぶぜ!

以上、Kuboでした。

タイトルとURLをコピーしました