SSH Tunnel using Google Cloud Function

Viewed 249

Is there a way to do something like the following in GCF?

import pymysql
import paramiko
from sshtunnel import SSHTunnelForwarder
    
def hello_world(request, data=''):
    with SSHTunnelForwarder(ssh_address_or_host='56.48.28.32', ssh_username='ubuntu', ssh_pkey='id_rsa', remote_bind_address=('aval.myixal.net', 3306)) as tunnel:
        conn = pymysql.connect(host='127.0.0.1', user='xian', passwd='bwQi', db='avails', port=tunnel.local_bind_port)
        cursor = conn.cursor()
        cursor.execute('SELECT * FROM global_event LIMIT 10')
        data = str(cursor.fetchone())
        conn.close()
    return data

I have included the id_rsa key and the requirements. This will work locally, but I'm guessing the whole 'port-forwarding' thing might be a non-starter on GCF. Is there a way to do something like the above?

enter image description here

1 Answers

Totally possible. Quick test i did:

import io
import pymysql
import paramiko
from sshtunnel import SSHTunnelForwarder
    
def hello_world(request):
    k = '''-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAB
...
zLFzhIqql0Av4K4XKQAAABVqYWJic29uQHRlc3QtaW5zdGFuY2UBAgME
-----END OPENSSH PRIVATE KEY-----'''

    key = paramiko.RSAKey.from_private_key(io.StringIO(k))
    
    with SSHTunnelForwarder(ssh_address_or_host='<ssh-ip-address>', ssh_username='<ssh-user-name>', ssh_pkey=key, remote_bind_address=('127.0.0.1', 3306)) as tunnel:
        conn = pymysql.connect(host='127.0.0.1', user='<mysql-user>', passwd='<mysql-pass>', port=tunnel.local_bind_port)
        cursor = conn.cursor()
        cursor.execute('SELECT NOW();')
        data = str(cursor.fetchone())
        conn.close()
    return data

result:

gcurl https://us-central1-my-project.cloudfunctions.net/function-1
(datetime.datetime(2021, 5, 13, 5, 4, 16),)

make sure not to hardcode your values like I did, instead use env variables.

Related