Serverspecでmysql-serverの設定をテストする方法

こんにちは!beardです!

RDSを使わないでEC2にMySQLをインストールして使うこともあるかと思います。

今回は、そんな場合にServerspecでmysql-serverのテストをできるようにしてみます。

Serverspecのインストールと基本的な操作については、過去の記事『 Amazon OSS編~Serverspecパート①~ 』をご覧ください。

  1. まずAmazonLinuxのEC2にmysqlをインストールして設定します。
1$yum -y install mysql-server2$vim /etc/my.cnf ←mysql設定変更3[mysqld_safe]4log-error = /var/log/mysqld.log5pid-file = /var/run/mysqld/mysqld.pid67[mysqld]8datadir = /var/lib/mysql9socket = /var/lib/mysql/mysql.sock10symbolic-links = 011character-set-server = utf8 ←日本語に対応するためUTF8を使用1213$service mysqld start ←サービス起動14$chkconfig mysqld on ←自動起動設定
  1. serverspecでこれらの設定を確認します。

ディレクトリ構成とRakefileとspec_helper.rbは「 Serverspecでサーバ情報をファイルに保存してテストする方法 」の記事と同じです。

1Serverspec2├Rakefile3├mysql.yml ←サーバ情報を書きます4├spec5   ├spec_helper.rb6 └mysql7    └mysql_spec.rb ←mysqlの設定を新規で作ります。

mysql.ymlの内容

1”IPアドレス”:2  :roles:3      - mysql

mysql_spec.rbの内容

1require 'spec_helper'23describe service('mysqld') do ←mysqlの起動について4  it { should be_enabled }5  it { should be_running }6end7describe port(3306) do ←mysqlのポート8    it { should be_listening } 9end1011describe file('/etc/my.cnf') do ←設定ファイル12    it {should contain('character-set-server = utf8').from(/^[mysqld]/).to(/^end/)}13    it { should be_mode 644 }14end
  1. このようにファイルを変更した後、「rake spec」コマンドでテストを開始します。
1$ rake spec2Enter Servers.yml to test(full path): /etc/serverspec/hsuzuki/mysqld.yml3/usr/bin/ruby2.0 -S rspec spec/mysql/mysql_spec.rb spec/test/test_spec.rb4......56Finished in 2.51 seconds76 examples, 0 failuresrake spec ←テスト成功

1. 解説

今回の特徴としては/etc/my.cnfのテストです。

ここでは[mysqld]からファイルの最後までの間にcharacter-set-server = utf8の記述があることを評価しています。

また、ファイルの権限もテストしておきます。

1describe file('/etc/my.cnf') do2    it {should contain('character-set-server = utf8').from(/^[mysqld]/).to(/^end/)}3    it { should be_mode 644 }4end

いかがでしたか?

なんらかの理由でRDSを使わない場合はこういった方法も必要です。

次回もお楽しみに!!

この記事を書いた人

aws-recipe-user