読者です 読者をやめる 読者になる 読者になる

複数サーバの設定をserverspecに食わせて実行するサンプル

dev.yaml

"host1":
  :roles:
    - foocheck
  :ssh_opts:
    :user: centos
    :keys: ~/.ssh/bar.pem
    :paranoid: false
"host2":
  :roles:
    - foocheck
  :ssh_opts:
    :user: centos
    :keys: ~/.ssh/bar.pem
    :paranoid: false

Rakefile

require 'rake'
require 'rspec/core/rake_task'
require 'yaml'

task :spec    => 'spec:all'
task :default => :spec


namespace :spec do
  spec_env = ENV['SPEC_ENV']
  if spec_env
    properties = YAML.load_file("./#{spec_env}.yaml")
  else
    raise RuntimeError, "HPB-ERROR: No hosts defined for \"#{spec_env}\""
  end

  task :all => properties.keys.map {|key| 'spec:' + key }

  properties.each_key do |key|
    desc "Run serverspec to #{key}"
    RSpec::Core::RakeTask.new(key.to_sym) do |t|
      t.fail_on_error = false
      ENV['TARGET_HOST'] = key
      t.pattern = 'spec/{' + properties[key][:roles].join(',') + '}/*_spec.rb'
    end
  end

end

spec_helper.rb

require 'serverspec'
require 'net/ssh'

set :backend, :ssh

if ENV['ASK_SUDO_PASSWORD']
  begin
    require 'highline/import'
  rescue LoadError
    fail "highline is not available. Try installing it."
  end
  set :sudo_password, ask("Enter sudo password: ") { |q| q.echo = false }
else
  set :sudo_password, ENV['SUDO_PASSWORD']
end

host = ENV['TARGET_HOST']
options = Net::SSH::Config.for(host)

options[:user] ||= Etc.getlogin

# add ssh options
spec_env = ENV['SPEC_ENV']
properties = YAML.load_file("./#{spec_env}.yaml")
unless properties[host][:ssh_opts].nil?
  options.merge!(properties[host][:ssh_opts])
end

# add pty option
set :request_pty, true

set :host,        options[:host_name] || host
set :ssh_options, options

# Disable sudo
# set :disable_sudo, true


# Set environment variables
# set :env, :LANG => 'C', :LC_MESSAGES => 'C'

# Set PATH
# set :path, '/sbin:/usr/local/sbin:$PATH'

実行方法

SPEC_ENV=dev /usr/local/rbenv/shims/bundle exec rake spec:all -t