简体   繁体   中英

sshtunnel forwarding and mysql connection on google cloud function

I am trying to connect to a MySQL server through ssh tunnel on one of my google cloud functions. This works fine in my home environment. I assume it is some port issue on cloud function.

Edit: For clarification the MySQL server sits on a Namecheap shared hosting web server. Not Google Cloud SQL

Every time I run this I timeout with "unknown error". The tunnel appears to be successful. I am however unable to get the mysql connection to work.

import base64
import sshtunnel
import mysql.connector

def testing(event, context):
    """
    Testing function
    """
    with sshtunnel.SSHTunnelForwarder(
        ("server address", port),
        ssh_username="user",
        ssh_password="password",
        remote_bind_address=("127.0.0.1",3306),
    ) as server:
        print(server.local_bind_port)
        with mysql.connector.connect(
            user="user",
            password="password",
            host="localhost",
            database="database",
            port=server.local_bind_port
        ) as connection:
            print(connection)

在此处输入图片说明

There's too many steps to list, but I'm wondering if the "connector" setup plays a difference even for SSH. Maybe you have to create a connector as shown here (notice how the instructions in "Private IP" tab are different than on your local computer). Then, configure Cloud Functions to use that connector. Make sure you also use the right port.

A Serverless VPC Access connector handles communication to your VPC network. To connect directly with private IP, you need to:

  1. Make sure that the Cloud SQL instance created above has a private IP address. If you need to add one, see the Configuring private IP page for instructions.

  2. Create a Serverless VPC Access connector in the same VPC network as your Cloud SQL instance. Unless you're using Shared VPC, a connector must be in the same project and region as the resource that uses it, but the connector can send traffic to resources in different regions. Serverless VPC Access supports communication to VPC networks connected via Cloud VPN and VPC Network Peering. Serverless VPC Access does not support legacy networks.

  3. Configure Cloud Functions to use the connector.

  4. Connect using your instance's private IP and port 3306.

Keep in mind, this "unknown" error could also very well be due to the Cloud SQL Admin API not being enabled here . As a matter of fact, make sure you follow that entire page as it's a broad question.

Let us know what worked for this type of error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM