LoginSignup
6
7

More than 5 years have passed since last update.

Serverspecにて~/.ssh/configを設定したけどIdentityFileで%hが使えない

Last updated at Posted at 2015-11-05

Serverspecを使って大量サーバでテスト!

ServerspecやAnsibleを使用して、大量のサーバへ一括テストするために~/.ssh/configの設定をしています

~/.ssh/config
Host server*
        user userA
        Hostname %h
        IdentityFile /root/.ssh/id_rsa_%h
        ServerAliveInterval 60

クライアント単位にキーペアを作成し、上記の設定を使って対象サーバへのログインを管理しています。(server~ に関しては/root/.ssh/id_rsa_サーバー名の鍵を使う)
※server1,server2…というホスト名と、id_rsa_server1,id_rsa_server1.pub…という鍵を大量作成

しかしAnsibleではうまくいくのですが、なぜだかServerspecではうまく行きません。どうやらRubyのNet::SSH::Configあたりでうまく%hが解釈できていないようです。(IdentityFileに%hがあると解釈してくれない)

Net::SSH::Configのリファレンスはこちら

対策(spec_helper.rbをいじる)

spec_helper.rboptions[:keys] = "/root/.ssh/id_rsa_" + hostの記載を追加しました。
これにより、SSH認証の際に指定のホスト名の鍵を参照するようになります。

spec_helper.rb
#  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[:keys] = "/root/.ssh/id_rsa_" + host

options[:user] ||= Etc.getlogin

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'


6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7