Environment
- serverspec 2.41.5
- aws-cli 2.13.7
- Python 3.11.4
spec_helper.rb
- EC2 tag name から Instance ID を取得し, start-session の引数に渡す.
Net::SSH::Proxy::Command
class を利用し, SSH 接続のプロキシとして start-session を OS のコマンドライン上で実行する.
require 'serverspec'
require 'net/ssh'
require 'yaml'
require 'net/ssh/proxy/command'
set :backend, :ssh
set :request_pty, true
RSpec.configure do |c|
c.before :all do
set :host, ENV['TARGET_HOST']
options = Net::SSH::Config.for(host)
set :disable_sudo, true
options = Net::SSH::Config.for(host).merge(properties['shared_settings'][:ssh_opts])
options[:proxy] = build_proxy_command(host)
end
set :ssh_options, options
end
def build_proxy_command(host)
command = "sh -c \"aws ssm start-session --target $(aws ec2 describe-instances --filters 'Name=tag:Name,Values=#{host}' \
--output text --query 'Reservations[*].Instances[*].InstanceId' --profile #{property[:aws_profile]}) \
--document-name AWS-StartSSHSession --parameters 'portNumber=22' --profile #{property[:aws_profile]}\""
Net::SSH::Proxy::Command.new(command)
end
properties.yaml
- 共通設定で ssh の設定パラメータとして ssh user, ssh 認証鍵を指定する.
- aws_profile の property を指定し, start-session と describe-instance の引数に渡す.
shared_settings:
:ssh_opts:
:user: ssh_user
:keys: ~/.key/example.pem
test-server-001:
:aws_profile: TestRole
:roles:
- hoge_role
Execute
$ rake serverspec:test-servers-001 --trace
...
Finished in 5.4 seconds (files took 0.28465 seconds to load)
19 examples, 0 failures