How can I dynamically create a dotenv .env file using Octopus Deploy variables for my NodeJS application?

logic-in-deployments
(Mark Harrison) #1

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?

(Mark Harrison) #2

Octopus Variables are accessible within a Powershell Script step using the $OctopusParameters global variable (https://octopus.com/docs/deployment-examples/custom-scripts/using-variables-in-scripts#Customscripts-VariablesinPowerShellscripts)

To write these out to your .env file, you could create a script like below:

:warning: Note: This script is intended as a sample only. :warning:

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:

image

The resulting .env file looks like this:

image

(Mark Harrison) listed #3