ServerspecのサンプルをCentOS 6.5環境で実行するまで

■インストール

yum install ruby rubygems
gem install serverspec
gem install rake

■サンプル作成

mkdir /opt/serverspec/
cd /opt/serverspec/
serverspec-init

# 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: host.to.check
 + spec/
 + spec/host.to.check/
 + spec/host.to.check/sample_spec.rb
 + spec/spec_helper.rb
 + Rakefile
 + .rspec

■SSH接続用秘密鍵設置

mkdir -p /opt/hosts/host.to.check
# /opt/hosts/host.to.check/ssh.key に秘密鍵を設置
chmod -R 0600 /opt/hosts/host.to.check/

#SSH接続確認
ssh -v serverspec@host-to-check.com -i /opt/hosts/host.to.check/ssh.key

■SSH接続設定

vim ~/.ssh/config

----
Host
  HostName host-to-check.com
  Port 22
  User serverspec
  IdentityFile /opt/hosts/host.to.check/ssh.key

----

■specファイル調整

vim /opt/serverspec/spec/spec_helper.rb
----
# オプション追加
set :request_pty, true
----


vim /opt/serverspec/spec/host.to.check/sample_spec.rb
---
# ファイルの一番上に追記
require 'rubygems'
---

■接続先サーバーでチェック用ユーザーがsudo出来るように準備 【重要】visudoの設定は必ず最後に戻しておくこと!!

useradd serverspec
# visudo
----
serverspec   ALL=(ALL) NOPASSWD:     ALL
----

su - serverspec
mkdir ~/.ssh
vi ~/.ssh/autorized_keys
# 公開鍵追加

chmod 0700 ~/.ssh
chmod 0600 ~/.ssh/autorized_keys

■サンプル実行

cd /opt/serverspec
rake spec

■サンプル実行結果

/usr/bin/ruby -I/usr/lib/ruby/gems/1.8/gems/rspec-support-3.1.2/lib:/usr/lib/ruby/gems/1.8/gems/rspec-core-3.1.7/lib /usr/lib/ruby/gems/1.8/gems/rspec-core-3.1.7/exe/rspec --pattern spec/host.to.check/\*_spec.rb

Package "httpd"
  should be installed

Service "httpd"
  should be enabled
  should be running

Port "80"
  should be listening

Finished in 0.1808 seconds (files took 0.74127 seconds to load)
4 examples, 0 failures