Full Stack Brain
Full Stack Brain

Reputation: 485

How to set environment variable for node js build job in azure devops pipeline

I am importing some secrets from Azure Key Vault to Variable Group to CI / CD pipeline.

I am able to map the required secrets in VariableGroup from KeyVault using Azure Devops UI.

In my pipeline YAML i am able to read and print those VariableGroup variables which are AzureKeyVault secrets.

    trigger:
      - dev

    # define the VM image 
    pool:
      vmImage: "Ubuntu 16.04"

    # define variables to use during the build
    variables:
    - group: SecretVarGroup # it has keyvault variable 'KV_API_KEY'
    - group: PublicVarGroup # it has a variable 'API_CLIENTID'

    # define the step to export key to env varaiable
    steps:

      - script: echo $MYSECRETAPIKEY
        env:
          MYSECRETAPIKEY: $(KV_API_KEY)

      ## Run the npm build
      - script: |
          npm run build
        displayName: "npm build"

I am able to see value for 'KV_API_KEY' secret printed as *** value in the build output log which i assume its able to consume. I also see value for API_CLIENTID printed in build log as well as node js process.env object.

I was assuming the variable "MYSECRETAPIKEY" will be available in my node js process.env object. But it's not avaialble.

The way i tested it is in my node js project build config i have a print statement which prints process.env object. It printed all the environment variables of pipeline build agent including my PUBLICVARGROUP variable 'API_CLIENTID'. But i don't see my secret variable 'MYSECRETAPIKEY' in the process.env object.

   env:
          MYSECRETAPIKEY: $(KV_API_KEY)

I thought above line would export variable to specific language process environment. But it is not. How can i fix this?

Upvotes: 7

Views: 17628

Answers (1)

Full Stack Brain
Full Stack Brain

Reputation: 485

# define the step to export key to env varaiable
steps:

  ## Run the npm build
  - script: |
      npm run build
    displayName: "npm build"
    env:
      MYSECRETAPIKEY: $(KV_API_KEY)

Looks like secrets are scoped on the agent for individual tasks and scripts to use. The issue was I had the env: declaration in a separate adhoc task. Moving it to the same place of my script declaration in the above code has fixed the issue.

Upvotes: 15

Related Questions