DBI hangs while connecting to MySQL Over SSH TUnnel

Apologies, Even after doing extensive research, I could not find how to
format post on ruby-forum. So, please point me in right direction as
this is my 1st post on ruby-forum.

I am trying to connect to a MySQL DB Over SSH tunnel.

Here is my code:

#!/usr/local/bin/ruby
require ‘net/ssh/gateway’
require ‘dbi’

puts “Creating SSH Tunnel …”
gateway = Net::SSH::Gateway.new(‘bastion_host’, ‘ubuntu’, :keys =>
["/home/ubuntu/ssh_key.pem"])
gateway.open(‘MySQL_End_Point’, 3306, 40000)

puts “Connectinge to MySQL Over the tunnel …”

dbh =
DBI.connect(‘DBI:Mysql:database=information_schema;host=127.0.0.1;port=40000’,
‘db_username’, ‘db_password’)

puts “Preparing the query …”
sth = dbh.prepare(“SHOW DATABASES”)

puts “Executing the query …”
sth.execute

while row = sth.fetch_array
puts row
end

sth.finish
dbh.disconnect

When I run this code, I get below output:

Creating SSH Tunnel …
Connecting to MySQL Over the tunnel …

Meaning, DBI is hanging on connecting over the SSH tunnel. It never
reaches the point where it should have printed “Preparing the query …”

If I create the SSH tunnel on the command line and then try connecting
using the MySQL CLI, then it works just fine. In fact, I am running
mysqldump via ruby by connecting it over the tunnel.

However, in this case, I am using DBI to make the DB connection and it
gets hanged.

Any suggestions?