ようへいの日々精進XP

よかろうもん

serverspec で複数ホストを一気にテストしてみた(1)

概要

  • 手動で設定している部分を serverspec を使ってサーバー構築後に一斉にテストしてみた

設定

テストの内容

サーバーごとに以下のファイルに適切にホスト名が設定されているかをチェックした。

  • /etc/hosts
  • /etc/hostname
  • /etc/mailname

ホストごとに spec ファイルを用意してみる

対象ごとに serverspec-init を叩こうとしたが、ちょっと待て...どうやら、spec ディレクトリ以下のホスト名(又は IP アドレス)を解析してそやつを使って対象ホストにアクセスしているようだということで...

serverspec-init

を実行した後で...

cd spec
cp -rf ${host1_dir} ${host2_dir}
cp -rf ${host1_dir} ${host3_dir} 

とひたすらコピー...

そして default_spec.rb を全てのホスト分を記載するのかと思っていたら、こちらこちらを参考に attribute.yml を利用してホストによって異なる値を外部に持たせることが出来るのでそちらを利用させて頂くことにした。

attribute を使ってみる

今回のテストは IP アドレス毎に異なるホスト名が所定のファイルに適切に設定されているかをチェックしたい為、attributes.yml は以下のように値を持たせるようにした。

作成後、attributes.ymlRakefile 等と同じディレクトリに設置し、Rakefile の一部を以下のように修正した。

そして spec ファイルは以下のように記載した。

${serverspec}/spec/${host1_dir}/default_spec.rb

また、spec_helper.rbinclude Serverspec::Helper::Attributes を追記する。(以下は一部)

テスト

以下のようにテストを実行。

ASK_SUDO_PASSWORD=1 rspec spec

敢えて失敗させてみた。

/usr/local/bin/ruby -S rspec spec/xxx.xxx.xxx.xxx/default_spec.rb spec/xxx.xxx.xxx.xxx/httpd_spec.rb spec/xxx.xxx.xxx.xxx/mysql_spec.rb
Enter sudo password: 
F.F........

Failures:

  1) File "/etc/hosts" 
     Failure/Error: it { should contain "#{attr[:ip]}  #{attr[:host_name]}.example.com #{attr[:host_name]}" }
     # ./spec/xxx.xxx.xxx.xxx/default_spec.rb:5:in `block (2 levels) in <top (required)>'

  2) File "/etc/mailname" 
     Failure/Error: it { should contain "#{attr[:host_name]}.example.com" }
     # ./spec/xxx.xxx.xxx.xxx/default_spec.rb:13:in `block (2 levels) in <top (required)>'

Finished in 0.4926 seconds
11 examples, 2 failures

Failed examples:

rspec ./spec/xxx.xxx.xxx.xxx/default_spec.rb:5 # File "/etc/hosts" 
rspec ./spec/xxx.xxx.xxx.xxx/default_spec.rb:13 # File "/etc/mailname" 
rake aborted!
/usr/local/bin/ruby -S rspec spec/xxx.xxx.xxx.xxx/default_spec.rb spec/xxx.xxx.xxx.xxx/httpd_spec.rb spec/xxx.xxx.xxx.xxx/mysql_spec.rb failed

上記のようにテストが出来た。(ただし、出力は 1 ホスト分の抜粋のみですいません。)

実は...

テストの対象が複数に渡る場合にホストごとに default_spec.rb を作成しなければいけないのかなーと思っていたら...そんなことは無かった。こちらに書かれているように spec ファイルをホスト間で共有出来るとのこと。

 serverspec のテストをホスト間で共有する方法

ということで、次回はホスト間での spec ファイルの共有を試してみたい。

まとめ

  • attribute を使うことでホスト固有の情報を別途持たせることが出来る
  • attribute を利用する場合には libyaml 等の追加の設定が必要
  • 共通の spec は共有することも出来る
  • とは言え、ruby 力が必要なことを痛感...(rspec とかよくわかりません...)