Last active
March 3, 2020 10:25
-
-
Save vinzenzweber/1821fa0da031f0853624cee32f9593a3 to your computer and use it in GitHub Desktop.
Connect to a private PostgreSQL database through an SSH tunnel using Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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