Q:

Unable to set node environment variable in yml file

Using Azure's DevOps and azure-pipeline.yml file I am trying to define a process.env variable to be used in my node.js code which gets run when npm run test is called. I'm setting the git commit version from Build.SourceVersion to process.env.BATCH_ID. 
The azure-pipelines.yml looks like: 
trigger:
    - master

pool:
     vmImage: 'Ubuntu-16.04'

steps:
    - task: NodeTool@0
      inputs:
        versionSpec: '8.x'
        displayName: 'Install Node.js' 

- script: |
    npm install
    process.env['BATCH_ID']  = $(Build.SourceVersion)
    process.env['myVar']  = 'nick' 
    npm run start &
    npm run test 

In my Nodejs code both BATCH_ID and myVar are returning undefined. I realize I don't have a node process running at this point which is one problem. npm run test is running the jest which is running a bunch of tests where I want access to those variables. How can I set those variables?

A:

You can define the variables in the beginning of the .yaml file:
# Set variables once
variables:
  BATCH_ID: $(Build.SourceVersion)
  myVar: nick

steps:
 - task: NodeTool@0
   inputs:
     versionSpec: '8.x'
     displayName: 'Install Node.js' 

- script: |
   npm install
   npm run start &
   npm run test 

Another option to set the variables in the script phase:
- script: |
  npm install
  echo '##vso[task.setvariable variable=BATCH_ID]$(Build.SourceVersion)'
  echo '##vso[task.setvariable variable=myVar]nick'
  npm run start &
  npm run test 

In the Node.js you read the variables like each environment variable.

