ServerSpec

提供: 技術wiki
ナビゲーションに移動 検索に移動

serverspecはインフラ環境のテストツールである。 リモートサーバのファイル情報やコマンド実行結果を確認することが可能。 基本的にはOSやミドルウェア等の設定情報を確認する。 rubyのライブラリなためrubyが入っていれば動作する。 また、確認内容はテストコードとして記述する。

導入手順

gemでインストールする。

$ gem install serverspec
$ gem install rake


初回設定

作業したディレクトリでserverspec-initコマンドを実行する。 下記の例では対象サーバのホスト名を「webserver」とする。 また、sshで対象ホストに接続できることを前提とする。

$ 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: y
 Input target host name: webserver
  + spec/
  + spec/webserver/
  + spec/webserver/sample_spec.rb
  + spec/spec_helper.rb
  + Rakefile

実行完了後に必要なファイルが作成される。 Rakefileがあるディレクトリで下記のコマンドを実行するとテストが実施される。

$ rake spec:develop

サンプル

下記の例はAmazonLinuxを設定したときに使用した初期設定の確認例である。 確認内容はそれぞれコメントで記述。

require 'spec_helper'

# OSのバージョンが2016.09であること
describe file('/etc/system-release') do
  it { should be_file }
  its(:content) { should match /Amazon Linux AMI release 2016.09¥n/}
end

# ZONEがJapanになっていること
describe file('/etc/sysconfig/clock') do
  it { should be_file }
  it { should contain '^ZONE=¥"Japan¥"' }
end

# ロケールの言語設定が日本語で文字コードがUTF-8であること
describe file('/etc/sysconfig/i18n') do
  it { should be_file }
  it { should contain '^LANG=ja_JP.UTF-8' }
end

# エンコード設定が日本語で文字コードがUTF-8であること
describe file('/etc/sysconfig/i18n') do
  it { should be_file }
  it { should contain '^LC_TYPE=ja_JP.UTF-8' }
end

# ハードウェアクロックのUTC設定が無効になっていること
describe file('/etc/sysconfig/clock') do
  it { should be_file }
  it { should contain '^UTC=false' }
end

# システム日付がJSTであること
describe command('date') do
  its(:stdout) { should match /JST/ }
end

# 自動セキュリティアップデートが無効になっていること
describe file('/etc/cloud/cloud.cfg') do
  it { should be_file }
  it { should contain '^repo_upgrade: none' }
end

# アップデート時のロケール更新が無効になっていること
describe file('/etc/cloud/cloud.cfg') do
  it { should be_file }
  it { should contain '^locale: ja_JP.UTF-8' }
end

# PHPのタイムゾーンが東京になっていること
describe file('/etc/php.ini') do
  it { should be_file }
  it { should contain '^date.timezone = Asia/Tokyo' }
end

# anacron実行時間が0時〜5時になっていること
describe file('/etc/anacrontab') do
  it { should be_file }
  it { should contain '^START_HOURS_RANGE=0-5' }
end