|
#!/usr/bin/env node |
|
// @ts-check |
|
const fs = require('fs') |
|
const path = require('path') |
|
const yaml = require('yaml') |
|
const dotenv = require('dotenv') |
|
const { execSync } = require('child_process') |
|
const dotEnvStringify = require('dotenv-stringify') |
|
const deploymentPath = process.argv[process.argv.length - 1] |
|
|
|
try { |
|
copySandboxEnv() |
|
console.log('Copied sandbox env 💿') |
|
} catch (error) { |
|
console.error('🚨', error.message) |
|
process.exit(1) |
|
} |
|
|
|
function copySandboxEnv() { |
|
const existing = readDotEnv('.env') |
|
const values = readYaml('values.yaml')['forto-app'].app.env |
|
const sandbox = readYaml('values.sandbox.yaml')['forto-app'].app.env |
|
const secrets = readSops('secrets.sandbox.yaml')['forto-app'].app.secretenv |
|
|
|
const merged = { ...values, ...sandbox, ...secrets, ...existing } |
|
const env = replaceClusterURLs(merged) |
|
|
|
writeEnv('.env', env) |
|
} |
|
|
|
function readDotEnv(path) { |
|
return fs.existsSync(path) ? dotenv.parse(fs.readFileSync(path).toString()) : {} |
|
} |
|
|
|
/** |
|
* @param {string} path |
|
* @param {Record<string, any>} env |
|
*/ |
|
function writeEnv(path, env) { |
|
const envString = dotEnvStringify(env) |
|
fs.writeFileSync(path, envString) |
|
} |
|
|
|
/** |
|
* @param {string} file |
|
* @returns {Record<string, any>} parsed content |
|
*/ |
|
function readYaml(file) { |
|
return yaml.parse(fs.readFileSync(inDeploymentFolder(file)).toString()) |
|
} |
|
|
|
function inDeploymentFolder(file) { |
|
return path.resolve(deploymentPath, file) |
|
} |
|
|
|
function readSops(file) { |
|
try { |
|
execSync('saml2aws login', { stdio: 'pipe' }) |
|
} catch (error) { |
|
throw new Error('Login using "saml2aws login" first') |
|
} |
|
const decrypted = execSync(`sops -d ${inDeploymentFolder(file)}`, { |
|
env: { AWS_PROFILE: 'sandbox-Developer', ...process.env }, |
|
}) |
|
return yaml.parse(decrypted.toString()) |
|
} |
|
|
|
/** |
|
* @param {Record<string, any>} params |
|
* @returns {Record<string, string>} |
|
*/ |
|
function replaceClusterURLs(params) { |
|
return Object.fromEntries(Object.entries(params).map(([key, value]) => [key, replaceClusterURL(value.toString())])) |
|
} |
|
|
|
/** |
|
* @param {string} value |
|
* @returns string |
|
*/ |
|
function replaceClusterURL(value) { |
|
if (value.endsWith('.api.svc.cluster.local.')) { |
|
return value.toString().replace('http://', 'https://').replace('.api.svc.cluster.local.', '.forto.io') |
|
} |
|
return value |
|
} |