-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexport-env.ts
More file actions
76 lines (62 loc) · 1.67 KB
/
export-env.ts
File metadata and controls
76 lines (62 loc) · 1.67 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import yargs from 'yargs/yargs'
import {
SSMClient,
GetParametersByPathCommand,
ParameterType,
} from '@aws-sdk/client-ssm'
import { writeFile } from 'fs/promises'
import sst from '../sst.json'
const appName = sst.name
const defaultStage = 'dev'
const { stage } = yargs(process.argv.slice(2))
.usage('Usage: $0 --stage [string]')
.example(
'$0 dev',
`Generates an .env file with all the ssm variables found under path /${appName}/dev`
)
.default('stage', defaultStage)
.help().argv
type Parameter = {
name: string
value?: string
}
const main = async () => {
const client = new SSMClient({})
const path = `/${appName}/${stage}/`
console.log(`Getting parameters for path: ${path}`)
const response = await client.send(
new GetParametersByPathCommand({
Path: path,
})
)
const parameters = (response.Parameters || [])
.filter((parameter) => parameter.Type !== ParameterType.SECURE_STRING)
.map((parameter) => {
const path = parameter.Name || ''
return {
name: path.substring(path.lastIndexOf('/') + 1),
value: parameter.Value,
}
})
if (parameters.length == 0)
throw new Error(`Found no ssm parameters in path: ${path}`)
console.log('Generating .env with the following parameters:')
console.table(parameters)
await writeEnvFile(parameters)
}
const writeEnvFile = async (parameters: Parameter[]) => {
const fileContents = `
${parameters.reduce(
(contents, { name, value }) => `${contents}\n${name}=${value}`,
''
)}`.trim()
await writeFile('.env', fileContents)
}
main()
.then(() => {
process.exit(0)
})
.catch((err) => {
console.error(err)
process.exit(1)
})