I am experimenting with an AWS RDS postgres instance that is sitting in a private subnet.
For access to my other private EC2 instances I have been using an SSH bastion.
This all works fine and great - but then I found out that IDEA can actually already help me access my private RDS instance.
All I had to do was configure the "Use SSH tunnel" section in the IDEA datasource settings:
Awesome, it worked - god damn I love IDEA.
But the question is... how does it work?
Is IDEA just doing some kind of crazy SSH tunnelling for me behind the scenes (in which case, I'm even more impressed)?
Or is this a feature of the Postgres JDBC driver that I can leverage in my own code? That is, is there some way I can configure the Postgres JDBC to do this SSH tunnelling to my RDS instance?
I really like the way this avoids having to have previously setup specific tunnelling configuration at the OS level, like this.
So the question is: How can I do the same thing as IDEA is doing using only code in my project?
Accepted jdevelop's answer.
Here's the groovy snippet I used to test, for anyone else that might want to do this:
JSch jsch = new JSch()
jsch.addIdentity("~/mykeys/bastion.pem")
jsch.setConfig("StrictHostKeyChecking", "no")
Session session=jsch.getSession("ec2-user", bastionServer, 22)
session.connect()
int localPort = 65432
session.setPortForwardingL(localPort, dbHostServer, dbHostPort)
testDbConnection(
"localhost", Integer.toString(localPort), dbName, dbUser, dbPassword)
session.disconnect()