Connecting to CloudSQL from a service running in a GCP serverless environnement (ex: Cloud Functions)

TL;DR — use SQL Proxy (via unix sockets) with Serverless VPC Access for CloudSQL with Private IP

Razvan Culea
Google Cloud - Community
2 min readDec 9, 2020

--

Cloud Functions are a scalable solution to have pay-as-you-go functions as a service.

You can choose the region where the functions will be instantiated, but they don’t run on your network. When you need to connect to a CloudSQL instance, you will have to answer these two questions :

  • Is CloudSQL using a Public IP or Private IP ? (Private IP is safer, don’t expose your DB if you don’t need to)
  • Is SSL enabled ? (Encrypt your traffic, to avoid any unforeseen snooping)

Once you know the how the CloudSQL instance has been setup you can easily connect to it from the serverless environnement of a Cloud Function (see the documentation and the Quickstart guide for Cloud SQL using Cloud Functions).

Public or Private IP

Solid line : Public IP network path. Dotted line : Private IP path

Your CloudSQL instance has a Public IP then you can reach it from the Cloud Function directly (firewall rules apply).

Your CloudSQL instance has a Private IP then you need to configure Serverless VPC Access to connect your Cloud Function to a VPC network.

SSL Enabled ?

When you have an SSL enabled instance you can either reach the CloudSQL on its IP:port with a certificate, or use the SQL Proxy for a secure connection.

The code “cheat sheet” for a CloudSQL (Postgres) connection from a Cloud Function in Python

Without SSL, use IP & port (with serverless VPC access enabled, if private IP):

To see this snippet in the context of a web application, view the README on GitHub.

With SSL enabled, use unix sockets to pass thru the SQL Proxy (with serverless VPC access enabled, if private IP) and give cloudsql.instances.connect permission to the service account of your Cloud Function (see doc).

To see this snippet in the context of a web application, view the README on GitHub

Connecting to any CloudSQL instance from the serverless environment of a Cloud Function, has no more secrets for you. Go ahead and try it !

--

--