Search code examples
google-cloud-platformgoogle-cloud-sqlgoogle-cloud-rungoogle-cloud-buildcloud-sql-proxy

Connect Google Cloud Build to Google Cloud SQL


Google Cloud Run allows for using Cloud SQL. But what if you need Cloud SQL when building your container in Google Cloud Build? Is that possible?

Background

I have a Next.js project, that runs in a Container on Google Cloud Run. Pushing my code to Cloud Build (installing the stuff, generating static pages and putting everything in a Container) and deploying to Cloud Run works perfectly. 👌

Cloud SQL

But, I just added some functionality in which it also needs to some data from my PostgreSQL instance that runs on Google Cloud SQL. This data is used when building the project (generating the static pages).

Locally, on my machine, this works fine as the project can connect to my CloudSQL proxy. While running in CloudRun this should also work, as Cloud Run allows for connecting to my Postgres instance on Cloud SQL.

My problem

When building my project with Cloud Build, I need access to my database to be able to generate my static pages. I am looking for a way to connect my Docker cloud builder to Cloud SQL, perhaps just like Cloud Run (fully managed) provides a mechanism that connects using the Cloud SQL Proxy.

That way I could be connecting to /cloudsql/INSTANCE_CONNECTION_NAME while building my project!

Question

So my question is: How do I connect to my PostgreSQL instance on Google Cloud SQL via the Cloud SQL Proxy while building my project on Google Cloud Build?

Things like my database credentials, etc. already live in Secrets Manager, so I should be able to use those details I guess 🤔


Solution

  • You can use the container that you want (and you need) to generate your static pages, and download cloud sql proxy to open a tunnel with the database

      - name: '<YOUR CONTAINER>'
        entrypoint: 'sh'
        args:
          - -c
          - |
            wget https://dl.google.com/cloudsql/cloud_sql_proxy.linux.amd64 -O cloud_sql_proxy
            chmod +x cloud_sql_proxy
            ./cloud_sql_proxy -instances=<my-project-id:us-central1:myPostgresInstance>=tcp:5432 &
            <YOUR SCRIPT>