I am developing a service orientated platform in NodeJS and all settings are entered manually into a .ENV file (during development locally).
NodeJS then loads all these values into its environment via the dotenv module (https://www.npmjs.com/package/dotenv)
Because NodeJS expects to locate an .ENV file in order to be able to run, I’d like to create this file dynamically from within a Step within Octopus Deploy where all of my variables for the application are stored.
Is this possible to do in Octopus Deploy?
Octopus Variables are accessible within a Powershell Script step using the $OctopusParameters global variable (Redirecting to https://octopus.com/docs/deployments/custom-scripts/using-variables-in-scripts)
To write these out to your .env file, you could create a script like below:
Note: This script is intended as a sample only.
It is not recommended to write out sensitive variable values.
Write-Host "Creating .env file"
$PathToDeployedFiles = "D:\Work\"
$EnvFilePath = "$PathToDeployedFiles\.env"
if(Test-Path $EnvFilePath) {
Remove-Item $EnvFilePath
}
New-Item -Path $EnvFilePath -ItemType File
foreach($key in $OctopusParameters.Keys)
{
if($key.StartsWith("Octopus") -or $key.StartsWith("env:"))
{
Write-Verbose "Skipping key $key"
continue
}
else
{
Write-Host "Writing key $key"
$rawValue = $OctopusParameters[$key]
"$key='$rawValue'" | Out-File $EnvFilePath -encoding ascii -Append
}
}
The script removes the .env file if it already exists, and re-creates it.
It then loops over the Variables in the $OctopusParamaters variable, ignoring ones which start with Octopus
or env:
and writes out the values to the file.
In the case of a sample project I have set up, with variable values like this:
The resulting .env file looks like this: