|
#!/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() { |
|
console.log(1) |
|
const existing = readDotEnv('.env'); |
|
console.log(2) |
|
console.log(JSON.stringify(readYaml('values.yaml'), null, 4)) |
|
const values = readYaml('values.yaml')['forto-app'].app.env; |
|
console.log(3) |
|
const sandbox = readYaml('values.sandbox.yaml')['forto-app'].app.env; |
|
console.log(4) |
|
const secrets = readSops('secrets.sandbox.yaml'); |
|
console.log(5) |
|
|
|
const merged = { ...values, ...sandbox, ...secrets, ...existing }; |
|
console.log(6) |
|
const env = replaceClusterURLs(merged); |
|
console.log(7) |
|
|
|
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'); |
|
} |
|
try { |
|
const decrypted = execSync(`sops -d ${inDeploymentFolder(file)}`, { |
|
env: { AWS_PROFILE: 'sandbox-Developer', ...process.env }, |
|
}); |
|
return yaml.parse(decrypted.toString())['forto-app'].app.secretenv; |
|
} catch (err) { |
|
return {}; |
|
} |
|
} |
|
|
|
/** |
|
* @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; |
|
} |