gcp-monorepo-secret-manager
Version:
A Google Cloud Secret Manager utility for managing environment variables across different environments and services within a monorepo.
124 lines • 5.58 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadConfig = loadConfig;
const initSecretManagerClient_1 = require("./initSecretManagerClient");
const dotenv_1 = __importDefault(require("dotenv"));
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
/**
* Initializes configuration by fetching environment variables from Secret Manager
* This function pulls the service environment variables from Secret Manager and writes them to a .env file
*
* @param options Configuration options for the service
*/
async function initializeConfig(options) {
try {
const { serviceName, envPath, secretName } = options;
// Determine the .env file path
const defaultEnvPath = path.resolve(process.cwd(), ".env");
const resolvedEnvPath = envPath || defaultEnvPath;
// Check if .env file already exists
console.log(`Checking if .env file exists...${resolvedEnvPath}`);
if (fs.existsSync(resolvedEnvPath)) {
console.info(`Using existing .env file for ${serviceName}`);
// Load environment variables from existing .env file
dotenv_1.default.config({ path: resolvedEnvPath });
return resolvedEnvPath;
}
console.info(`Initializing config for ${serviceName} from Secret Manager...`);
// Initialize Secret Manager client
const secretManagerClient = (0, initSecretManagerClient_1.initSecretManagerClient)();
// Determine environment and project ID
const projectId = options.projectId;
const resolvedSecretName = secretName || `${serviceName.toUpperCase()}_ENV_FILE`;
const secretPath = `projects/${projectId}/secrets/${resolvedSecretName}/versions/latest`;
console.info(`Fetching secret: ${secretPath}`);
// Access the secret
const [version] = await secretManagerClient.accessSecretVersion({
name: secretPath,
});
if (!version.payload || !version.payload.data) {
throw new Error(`No data found for secret ${resolvedSecretName}`);
}
// Get the secret data
const envContent = Buffer.from(version.payload.data).toString();
// Write to .env file
fs.writeFileSync(resolvedEnvPath, envContent);
console.info(`Successfully loaded environment variables for ${serviceName} from Secret Manager`);
// Load the newly written environment variables into process.env
dotenv_1.default.config({ path: resolvedEnvPath });
// Verify that critical environment variables are now set
if (!process.env.ENV) {
console.error("ENV variable not set after loading from Secret Manager");
throw new Error("ENV is not set after loading from Secret Manager");
}
return resolvedEnvPath;
}
catch (error) {
console.error("Failed to initialize config from Secret Manager:", error);
if (error instanceof Error) {
console.error(`Error: ${error.message}`);
}
throw new Error(`Failed to initialize config for ${options.serviceName} from Secret Manager`);
}
}
/**
* Loads configuration for a service
*
* @param options Configuration options for the service
* @returns void
*/
async function loadConfig(options) {
// Initialize config from Secret Manager
const envPath = await initializeConfig(options);
// Load the environment variables from the .env file
dotenv_1.default.config({ path: envPath });
// Verify environment variables are loaded
if (!process.env.ENV) {
throw new Error("ENV is not set");
}
// Check required environment variables if specified
if (options.requiredEnvVars && options.requiredEnvVars.length > 0) {
const missingVars = options.requiredEnvVars.filter((varName) => !process.env[varName]);
if (missingVars.length > 0) {
throw new Error(`Missing required environment variables: ${missingVars.join(", ")}`);
}
}
}
//# sourceMappingURL=loadConfig.js.map