| 16 | |
| 17 | // Load the Cloud SQL config from Secret Manager |
| 18 | function getCredConfig() { |
| 19 | // [START cloudrun_user_auth_secrets] |
| 20 | // CLOUD_SQL_CREDENTIALS_SECRET is the resource ID of the secret, passed in by environment variable. |
| 21 | // Format: projects/PROJECT_ID/secrets/SECRET_ID/versions/VERSION |
| 22 | const {CLOUD_SQL_CREDENTIALS_SECRET} = process.env; |
| 23 | if (CLOUD_SQL_CREDENTIALS_SECRET) { |
| 24 | try { |
| 25 | // Parse the secret that has been added as a JSON string |
| 26 | // to retrieve database credentials |
| 27 | return JSON.parse(CLOUD_SQL_CREDENTIALS_SECRET.toString('utf8')); |
| 28 | } catch (err) { |
| 29 | throw Error( |
| 30 | `Unable to parse secret from Secret Manager. Make sure that the secret is JSON formatted: ${err}` |
| 31 | ); |
| 32 | } |
| 33 | } |
| 34 | // [END cloudrun_user_auth_secrets] |
| 35 | logger.info( |
| 36 | 'CLOUD_SQL_CREDENTIALS_SECRET env var not set. Defaulting to environment variables.' |
| 37 | ); |
| 38 | if (!process.env.DB_USER) throw Error('DB_USER needs to be set.'); |
| 39 | if (!process.env.DB_PASSWORD) throw Error('DB_PASSWORD needs to be set.'); |
| 40 | if (!process.env.DB_NAME) throw Error('DB_NAME needs to be set.'); |
| 41 | if (!process.env.CLOUD_SQL_CONNECTION_NAME) |
| 42 | throw Error('CLOUD_SQL_CONNECTION_NAME needs to be set.'); |
| 43 | |
| 44 | return { |
| 45 | DB_USER: process.env.DB_USER, |
| 46 | DB_PASSWORD: process.env.DB_PASSWORD, |
| 47 | DB_NAME: process.env.DB_NAME, |
| 48 | CLOUD_SQL_CONNECTION_NAME: process.env.CLOUD_SQL_CONNECTION_NAME, |
| 49 | }; |
| 50 | } |
| 51 | |
| 52 | module.exports = { |
| 53 | getCredConfig, |