如何将带有秘密管理器的 google 应用引擎连接到 Postgres?

How to connect google app engine with secret manager to Postgres?

我正在尝试通过秘密管理器从 GAE 中的 nodejs/typescript 代码库 运行 连接到 GCP 管理的 Postgres 数据库。

我得到:

 Error: 7 PERMISSION_DENIED: Permission denied on resource project DATABASE_USER.   

当我在 GAE 中 运行 它时。

首先,确保您已在 IAM 中授予对 GAE 服务帐户的机密访问权限。

然后使用以下代码示例从 secret manager 获取您的 ENV 变量。

import * as path from 'path';
import {SecretManagerServiceClient} from '@google-cloud/secret-manager';
import deasync from 'deasync';


require('dotenv').config();

const SnakeNamingStrategy =
  require('typeorm-naming-strategies').SnakeNamingStrategy;

const googleProjectId = process.env.GOOGLE_CLOUD_PROJECT;
const isInGAE = googleProjectId !== undefined;
const isLocalUsingCloudProxy = process.env.USE_CLOUD_SQL_AUTH_PROXY !== undefined;


const getSecretSync = deasync((name: string, cb:any) => {
  const c = new SecretManagerServiceClient();
  
  c.accessSecretVersion({name: c.secretVersionPath(googleProjectId, name, "latest")}).then(([secret]) => {
    cb(null, secret.payload.data.toString());
  }).catch((err) => {
    cb(err);
  });
});

  

let config = {
  type: 'postgres',
  host: process.env.DATABASE_HOST || 'localhost',
  port: parseInt(process.env.DATABASE_PORT, 10) || 5432,
  username: process.env.DATABASE_USER,
  password: process.env.DATABASE_PASSWORD,
  database: process.env.DATABASE_NAME,
  synchronize: false,
  logging: false,
  subscribers: [path.join(__dirname, '..', 'subscribers', '*.{ts,js}')],
  entities: [path.join(__dirname, '..', 'models', '*.{ts,js}')],
  migrations: [path.join(__dirname, '..', 'migrations', '*.{ts,js}')],
  cli: {
    entitiesDir: [path.join(__dirname, '..', 'models', '*.{ts,js}')],
    migrationsDir: [path.join(__dirname, '..', 'migrations', '*.{ts,js}')],
  },
  namingStrategy: new SnakeNamingStrategy(),
};


if (isInGAE || isLocalUsingCloudProxy) {
  config.username = getSecretSync("DATABASE_USER");
  config.password = getSecretSync("DATABASE_PASSWORD");
  config.database = getSecretSync("DATABASE_NAME");
  config.host = isInGAE ? "/cloudsql/" + getSecretSync("DATABASE_HOST") : 'localhost';
  config.port = isInGAE ? parseInt(getSecretSync("DATABASE_PORT"), 10) : 5432;
  console.log("dbuser", config.username);

}

请务必注意,DATABASE_HOST 应采用 SQL 选项卡上“连接名称”的形式,如 project-id:us-central1:db-name