Last Updated: February 25, 2016
·
2.491K
· fully_baked

Connect ActiveRecord via SSH Tunnel

Recently I was building a CLI tool to do some data maintanence, and while the tooling was developed in Ruby, the server in question didn't have it installed. Therefore I had to connect to the remote database over an SSH tunnel. Here's how I got ActiveRecord to connect to the remote database via SSH, just incase anyone else finds it useful

require 'net/ssh/gateway'
require 'active_record'

# there is no password here as the local user `user` has an SSH key stored on the remote server
gateway = Net::SSH::Gateway.new('domain.tld', 'user')
port = gateway.open('127.0.0.1', 3306, 3307)

ActiveRecord::Base.establish_connection(
  adapter: 'mysql2',
  host: '127.0.0.1',
  username: 'dbuser',
  password: 'dbpassword',
  database: 'dbname',
  port: port
)

Once this connection is established, normal models that extend ActiveRecord::Base could access the database as if it were local.