About
terraformで作った環境のテストができないなと思っていたところ、awsの構成をチェックできるawspecというツールがあるらしいので、試しに使ってみた。
準備
- gemをインストールする
Gemfile
gem 'awspec'
$ bundle install
元々aws-sdkのバージョン1が入っていた環境だったので、エラーになりました。aws-sdk のバージョン2を使っているようです。
- 初期設定する
$ mkdir awspec
$ cd awspec
$ bundle exec awspec init
+ #{dir}/
+ spec/spec_helper.rb
+ Rakefile
+ spec/.gitignore
direnvで環境変数を登録します。
$ cat .envrc
export AWS_ACCESS_KEY_ID=xxx
export AWS_SECRET_ACCESS_KEY=xxxxx
export AWS_DEFAULT_REGION=ap-northeast-1
使ってみる
既存環境のテストを作る
$ bundle exec awspec generate ec2 xxxxxxxx
describe ec2('test') do
it { should exist }
it { should be_stopped }
its(:instance_id) { should eq 'xxx' }
its(:image_id) { should eq 'xxx' }
its(:private_dns_name) { should eq 'xxx' }
its(:public_dns_name) { should eq '' }
its(:instance_type) { should eq 't2.micro' }
its(:private_ip_address) { should eq 'xxxx' }
it { should have_security_group('web') }
it { should belong_to_vpc('xxx') }
it { should belong_to_subnet('') }
end
$ bundle exec awspec generate ec2 xxxxxxxxx >> spec/ec2_spec.rb
※ xxxxxxxにはVPCを指定します
設定されてない部分は空欄になりました。自動でここまで出来ると楽です。
テストを動かしてみる
そのままだと動かないので、spec/ec2_spec.rbにrequire 'awspec'を追記しておきます。
$ bundle exec rake spec
...
Finished in 2.17 seconds (files took 3.66 seconds to load)
94 examples, 8 failures
結構気軽にできるので、良さそうな気がしますね!spec_helper.rbとかはもっと改造してもいいかも。 今はすでに追加されてます。awspec initだと.rspecが作成されなくて色が味気なかったので、後で追加しました。