简体   繁体   中英

How to set .env for react app deployed with azure devops pipeline on app service

I developed a pipeline with CI/CD on azure Devops for deploying a React app on Azure web app service. Locally I'm using a.env file and this file is on.gitignore. I want to know how can i set the.env for reading it on production.

You can check the documentation below:

https://create-react-app.dev/docs/adding-custom-environment-variables/#adding-development-environment-variables-in-env

.env files should be checked into source control (with the exclusion of .env*.local ).

If you don't want to check in the .env files to DevOps, you could add the variables in the pipeline variables:

在此处输入图片说明

In addition, you can refer to the following case for more suggestions:

How to use environment variables in React app hosted in Azure

Many of the proposed solutions related to this issue may not work but I solved it the following way. However, first let me explain why other solutions may not (should not) work (please correct me if I am wrong)

  • Adding pipeline variables (even though they are environment variables) should not work since a react app is run on the client side and there is no server side code that can inject environment variables to the react app.
  • Installing environment variable task on the classic pipeline should not work for the same reason.
  • Adding to Application Settings in azure app service should not work for the same reason.
  • Having.env or.env.development or.env.production file in a git repo should not be a good practice as it may compromise api keys and other sensitive information.

So here is my solution -

Step1: Add all those.env files to azure devops library as secure files. You can download these secure files in the build machine using a DownloadSecureFile@1 pipeline task (yml). This way we are making sure the correct.env file is provided in the build machine before the task yarn build --mode development in the pipeline.

在此处输入图像描述

Step2: Add the following task in your azure yml pipeline in appropriate place. I have created a github repohttps://github.com/mail4hafij/react-yarn-azure-pipeline if you want to see a complete example.

  # Download secure file from azure library
  - task: DownloadSecureFile@1
    inputs:
      secureFile: '.env.development'

  # Copy the .env file
  - task: CopyFiles@2
    inputs:
      sourceFolder: '$(Agent.TempDirectory)'
      contents: '**/*.env.development'
      targetFolder: '$(YOUR_DEFINED_PROJECT_ROOT_FOLDER_VARIABLE)'
      cleanTargetFolder: false

Keep note, secure files can't be edited but you can always re-upload.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM