Connect ActiveRecord via SSH Tunnel

 Feb 17, 2014

Wow… its been a while since I’ve written anything on here. Christmas was time out with the family and then the year started with a big project, but with a little time to spare and a useful tip today I thought I’d throw a post up.

I really enjoy working in Ruby and while my day to day work centres around PHP, I generally write my tools in Ruby to keep my hand in. Recently an issue came up with some data in an application that needed to be updated using various meta data from other tables in a way that just didn’t allow for pure SQL. I quickly put something together in Ruby and tested it locally on a copy of the database, and everything worked just fine.

Then realisation stuck. No Ruby installed on this particular production server. Never one to shy away from the task I started playing around with connecting the ActiveRecord script to the remote database via an SSH tunnel so that my new script could update the data without actually running on the server.

Here’s what I came up with


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

port = Net::SSH::Gateway.new('domain.tld', 'user').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
)

with this connection made, all the models I created extended ActiveRecord::Base would have full access to the remote database.