Search code examples
google-cloud-platformgoogle-cloud-sqlgoogle-cloud-build

Run node.js database migrations on Google Cloud SQL during Google Cloud Build


I would like to run database migrations written in node.js during the Cloud Build process.

Currently, the database migration command is being executed but it seems that the Cloud Build process does not have access to connect to Cloud SQL via an IP address with username/password.


Solution

  • In the case with Cloud SQL and Node.js it would look something like this:

    steps:
      # Install Node.js dependencies
      - id: yarn-install
        name: node:18
        entrypoint: yarn
        args: ["install", "--frozen-lockfile"]
        waitFor: ["-"]
    
      # Install Cloud SQL proxy
      - id: proxy-install
        name: node:18
        entrypoint: sh
        args:
          - "-c"
          - "wget https://storage.googleapis.com/cloud-sql-connectors/cloud-sql-proxy/v2.4.0/cloud-sql-proxy.linux.amd64 -O cloud_sql_proxy && chmod +x cloud_sql_proxy"
        waitFor: ["-"]
    
      # Migrate database schema to the latest version
      - id: migrate
        name: node:18
        entrypoint: sh
        args:
          - "-c"
          - "mkdir /cloudsql; chmod 777 /cloudsql; (./cloud_sql_proxy --unix-socket /cloudsql <CLOUD_SQL_CONNECTION> & sleep 2) && yarn knex migrate:latest"
        timeout: "1200s"
        waitFor: ["yarn-install", "proxy-install"]
    timeout: "1200s"
    

    You would launch yarn install and download Cloud SQL Proxy in parallel. Once these two steps are complete, you run launch the proxy, wait 2 seconds and finally run yarn knex migrate:latest.

    For this to work you would need Cloud SQL Admin API enabled in your GCP project.

    Where <CLOUD_SQL_INSTANCE> is your Cloud SQL instance connection name that can be found here. The same name will be used in your SQL connection settings, e.g. host=/cloudsql/example:us-central1:pg13.

    Also, make sure that the Cloud Build service account has "Cloud SQL Client" role in the GCP project, where the db instance is located.