forked from opengovsg/lambda-virus-scanner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
envLoader.mjs
57 lines (47 loc) · 1.73 KB
/
envLoader.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { SSMClient, GetParameterCommand } from '@aws-sdk/client-ssm'
import fs from 'fs'
import { exit } from 'process'
const SHORT_ENV_MAP = {
dev: 'dev',
develop: 'dev',
development: 'dev',
prod: 'prod',
production: 'prod',
stg: 'staging',
staging: 'staging',
test: 'test',
testing: 'test',
uat: 'uat',
vapt: 'vapt',
}
// This is a helper for local file runs or jest, as specified in package.json
// It emulates the loading of SSM which Lambda will do.
// This file is not meant to be used in a deployment and is .mjs so we can use top-level await
async function saveAllParameters() {
// If process.env.ENV is not a key in SHORT_ENV_MAP, then it is not a valid environment
if (!Object.keys(SHORT_ENV_MAP).includes(process.env.ENV)) {
console.log(`Invalid ENV=${process.env.ENV}. Must be a valid env in SHORT_ENV_MAP`)
exit(1)
}
console.log(`Retrieving parameters for ENV=${process.env.ENV}`)
const devEnvs = ['dev', 'develop', 'development']
if (devEnvs.includes(process.env.ENV)) {
console.log('In develop mode! Not fetching from SSM param store.')
console.log(
'Please reference .env.example to populate .env.development file for development environment',
)
exit(0)
}
const client = new SSMClient({ region: 'ap-southeast-1' })
const parameterName = `/virus-scanner/${SHORT_ENV_MAP[process.env.ENV]}`
const res = await client.send(
new GetParameterCommand({
Name: parameterName,
}),
)
const parameterString = (res.Parameter?.Value ?? '')
// Add on NODE_ENV
const parameterStringWithNodeEnv = parameterString.concat(`\nNODE_ENV=${process.env.ENV}`)
await fs.promises.writeFile(`.env.${process.env.ENV}`, parameterStringWithNodeEnv)
}
await saveAllParameters()