Skip to content

Instantly share code, notes, and snippets.

@vinzenzweber
Last active March 3, 2020 10:25
Show Gist options
  • Save vinzenzweber/1e49524c5ae8d24830b989384df8022f to your computer and use it in GitHub Desktop.
Save vinzenzweber/1e49524c5ae8d24830b989384df8022f to your computer and use it in GitHub Desktop.
Connect to hidden PostgreSQL database through SSH tunnel using Ruby
# This is my local config for the host I tunnel through in ~/.ssh/config
Host mypublichost
HostName remote.hostname.com
User remotesshusername
Port remotesshport
IdentityFile ~/.ssh/subfolder/id_rsa
source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
ruby '2.5.7'
gem 'activerecord'
gem 'net-ssh-gateway'
require 'active_record'
require 'net/ssh/gateway'
class CombinedHCP < ActiveRecord::Base
self.table_name = 'schema.tablename'
self.primary_key = 'uuid'
end
# set password nil to use public key authentication
gateway = Net::SSH::Gateway.new('mypublichost', nil)
# from the host, connect to the actual database instance, which is not public
port = gateway.open('hidden-prod-db.sdu29328dh.eu-central-1.rds.amazonaws.com', 5432)
ActiveRecord::Base.establish_connection(
adapter: 'postgresql',
host: '127.0.0.1',
username: 'dbuser',
password: 'dbpassword',
database: 'dbname',
port: port
)
CombinedHCP.all.limit(10).each do |hcp|
puts hcp.attributes
end
gateway.close
require 'active_record'
require 'net/ssh/gateway'
class CombinedHCP < ActiveRecord::Base
self.table_name = 'schema.tablename'
self.primary_key = 'uuid'
end
# set password nil to use public key authentication
# as an alternative to using the local ~/.ssh/config, you can also supply all host parameters directly
gateway = Net::SSH::Gateway.new('remote.hostname.com', nil, {
user: 'remotesshusername',
port: remotesshport,
keys: ['~/.ssh/subfolder/id_rsa']
})
# from the host, connect to the actual database instance, which is not public
port = gateway.open('hidden-prod-db.sdu29328dh.eu-central-1.rds.amazonaws.com', 5432)
ActiveRecord::Base.establish_connection(
adapter: 'postgresql',
host: '127.0.0.1',
username: 'dbuser',
password: 'dbpassword',
database: 'dbname',
port: port
)
CombinedHCP.all.limit(10).each do |hcp|
puts hcp.attributes
end
gateway.close
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment