LoginSignup
94
94

More than 5 years have passed since last update.

serverspecでテスト駆動サーバ構築

Posted at

Chef と Puppet の勉強会というよりも、むしろ時代は serverspec だった #pfcasual - 彼女からは、おいちゃんと呼ばれています
こちらの記事でserverspecを見て、テストファーストでサーバ構築できたら良さげだなーと思って使ってみました。

導入

gemからserverspecインストール。serverspec-initでSSH経由でサーバをテストするようにホスト名を入力。

$ gem install serverspec
$ serverspec-init                                                                                                
Select a backend type:

  1) SSH
  2) Exec (local)
  3) Puppet providers (local)

Select number: 1

Input target host name: test-server1
 + spec/
 + spec/test-server1/
...

test-server1にはvagrantで作ったまっさらなVMを使ってみます。

テスト

spec/下に指定したホスト名でディレクトリができてるので、試しに以下のようなテストを用意。apacheとtomcat(+管理ツール)がインストール済みかつ起動状態かどうか確認します。

example_spec.rb
require 'spec_helper'

#==========
# Apache
#==========
describe 'apache2' do
  it { should be_installed }
  it { should be_enabled   }
  it { should be_running   }
end
describe 'port 80' do
  it { should be_listening }
end

#==========
# Tomcat7
#==========
describe 'tomcat7' do
  it { should be_installed }
  it { should be_enabled }
  it { should be_running }

  # admin
  describe 'tomcat7-admin' do
    it { should be_installed }

    # 設定ファイルのチェック
    describe '/etc/tomcat7/tomcat-users.xml' do
      it { should contain '<role rolename="manager-gui"/>' }
      it { should contain '<user username="tomcat" password="tomcat" roles="manager-gui"/>' }
    end
  end
end 
describe 'port 8080' do
  it { should be_listening }
end

test-server1にテストを実行。

$ rake spec
...........FFFFFFFFFFF

Failures:

  1) apache2
     Failure/Error: it { should be_installed }
       sudo dpkg -s apache2
       Package `apache2' is not installed and no info is available.
       Use dpkg --info (= dpkg-deb --info) to examine archive files,
       and dpkg --contents (= dpkg-deb --contents) to list their contents.
...
...

まだ何もセットアップしてない状態なのでエラー。chef-soloなり手動なりでセットアップして再テスト。

$ rake spec
...........

Finished in 0.47476 seconds
11 examples, 0 failures
$ 

今度はOK。更にもう一台test-server2をVMで作成して、test-server1と同様にテストしてみます。

test-server2には同じテストを実施したいので、spec/下にtest-server1へのsymlinkを作成。

$ ln -s test-server1 spec/test-server2
$ tree spec/                                                                                                         
spec/
├── spec_helper.rb
├── test-server1
│   └── example_spec.rb
└── test-server2 -> test-server1

雑な感じだけど、ひとまず動けばいいという事で・・。これで2台目のマシンにもテストが走るようになるので、あとはテストが通るまで繰り返せばOK。テスト駆動がサーバ構築でも行えていい感じ!

他にもテストのmatcherが色々用意されているので、これから試していきたいなーと思います。

94
94
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
94
94