首页 > 解决方案 > 如何从 Cloud Build 连接到 Cloud SQL 以运行 knex 数据库迁移?

问题描述

我在 StackOverflow 上调查了这个问题,但不幸的是对我没有任何帮助。

我有cloudbuild.yaml档案

steps:
  - name: 'node:14.16.0'
    entrypoint: 'yarn'
    id: yarn-install
    args: ['install']
    waitFor: ["-"]

  - name: gcr.io/cloud-builders/yarn
    id: proxy-install
    entrypoint: sh
    args:
      - "-c"
      - "wget https://storage.googleapis.com/cloudsql-proxy/v1.23.0/cloud_sql_proxy.linux.amd64 -O /workspace/cloud_sql_proxy && chmod +x /workspace/cloud_sql_proxy"
    waitFor: ["-"]

  - id: migrate
    name: gcr.io/cloud-builders/yarn
    env:
      - NODE_ENV=$_NODE_ENV
      - DB_NAME=$_DB_NAME
      - DB_USER=$_DB_USER
      - DB_PASSWORD=MY_FAKE_PASSWORD
      - CLOUD_SQL_CONNECTION_NAME=$_CLOUD_SQL_CONNECTION_NAME
    entrypoint: sh
    args:
      - "-c"
      - "(./workspace/cloud_sql_proxy -dir=/workspace -instances=$_CLOUD_SQL_CONNECTION_NAME & sleep 2) && yarn run knex migrate:latest"
    timeout: "1200s"
    waitFor: ["yarn-install", "proxy-install"]

我想连接到我的 Cloud SQL 数据库以使用yarn run knex migrate:latest.

但它在迁移步骤失败

来自 Cloud Build 的日志

info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
error Command failed with exit code 1.
    at PipeConnectWrap.afterConnect [as oncomplete] (net.js:1145:16)
Error: connect ENOENT /cloudsql/project:us-east1:project-posgresql1/.s.PGSQL.5432
Using environment: production
Working directory changed to /workspace/src/infrastructure/knex
Requiring external module ts-node/register
$ ./node_modules/knex/bin/cli.js --knexfile=./src/infrastructure/knex/knex.config.ts migrate:latest --env production migrate:latest
yarn run v1.22.5
sh: 1: ./workspace/cloud_sql_proxy: not found
Already have image (with digest): gcr.io/cloud-builders/yarn

我不知道如何正确调试它......你能帮我找到问题的根本原因吗?

附言

...@cloudbuild.gserviceaccount.com 具有以下角色

PSS knex是一个用于类似 SQL 的数据库的 JavaScript 查询构建器

标签: google-cloud-sqlgoogle-cloud-build

解决方案


按照设计,您需要在与代理安装步骤相同的步骤中运行 cloud-sql prowy。但是,我从未使用 waitFor["-"] 进行测试,这可能是一种解决方法。但是这个解决方案应该适合你

  - name: gcr.io/cloud-builders/yarn
    id: proxy-install
    entrypoint: sh
    env:
      - NODE_ENV=$_NODE_ENV
      - DB_NAME=$_DB_NAME
      - DB_USER=$_DB_USER
      - DB_PASSWORD=MY_FAKE_PASSWORD
      - CLOUD_SQL_CONNECTION_NAME=$_CLOUD_SQL_CONNECTION_NAME
    args:
      - "-c"
      - |
         wget https://storage.googleapis.com/cloudsql-proxy/v1.23.0/cloud_sql_proxy.linux.amd64 -O /workspace/cloud_sql_proxy && chmod +x /workspace/cloud_sql_proxy
         (./workspace/cloud_sql_proxy -dir=/workspace -instances=$_CLOUD_SQL_CONNECTION_NAME & sleep 2) && yarn run knex migrate:latest
    timeout: "1200s"

试一试,让我知道


推荐阅读