Last Updated: February 25, 2016
· 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 ='domain.tld', 'user')
port ='', 3306, 3307)

  adapter: 'mysql2',
  host: '',
  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.