Thursday, October 31, 2019

How to access environment variables in react app on azure devops.



When you don’t want to access values through .env files, then follow the below procedure to access it from azure devops.

First remove env files and set the variables in pipeline
You can set a variable for a build pipeline by following these steps:
·         Navigate to Pipelines page, select the appropriate pipeline, and then select Edit.
·         Locate the Variables for this pipeline.
·         Add or update the variable.


To use a variable group, open your pipeline, select the Variables tab, select Variable groups, and then choose Link variable group. In a build pipeline, you see a list of available groups


CREATE VARIABLE GROUP
Navigate to Library and select  "Variable group" which opens the below screen
Toggle the Azure Key vault radio button to link the key vault.


CREATE BUILD PIPELINE TO ACCESS THE ENVIRONMENT VARIABLES.
The variables created under pipeline variables will be exposed to env and can be accessed without any issues. Since we are using react app make sure to prefix the variable name with “REACT_APP_”
The variables under “variable groups” will not be exposed to env.

Build pipeline Tasks:

1.       Add the “Azure key vault” task and fill out the properties as per your need and select the required key vault

2.       PowerShell Script
This task is required as the variables under “variable groups” are not exposed to env.
Add the below script which will set the env variables.
echo '##vso[task.setvariable variable=REACT_APP_API_URL]$(REACT-APP-API-URL-TEST)'
echo '##vso[task.setvariable variable=REACT_APP_TEST_EXPORT]$(API-URL-TEST)'

3.       Npm install – to install the npm packages.
4.       Npm custom – run build
5.       Archive files
6.       Copy file
7.       Publish


CREATE KEY VAULT



1 comment: