问题描述
所以我在我的 repo 中有一个 react/typescript 应用程序,我正在我的 repo 中我有一个 .env 文件,我忽略了它,这样我的秘密就不会暴露出来,还有一个 .env-example要配置的重要环境变量的文件.我的问题是,由于我没有将 .env 文件推送到我的存储库,因此当我通过 google 应用引擎部署我的应用程序时(这是在我的 gitlab-ci.yml 文件),这些环境变量将不会出现在生产环境中,我需要它们来让我的应用程序正常工作,因为我在 webpack.config.js 文件中执行了类似的操作.
So I have a react/typescript app in my repo that I'm working on and in my repo I have a .env file that I'm ignoring so that my secrets don't get exposed and a .env-example file of important environment variables to configure. My problem is, since I'm not pushing the .env file to my repo, when I deploy my app through the google app engine(this is done in the deployment stage in my gitlab-ci.yml file), these environment variables will not be present in production and I need them for my app to work as I do something like this in my webpack.config.js file.
const dotenv = require('dotenv').config({ path: __dirname + '/.env' });
然后
new webpack.DefinePlugin({
'process.env': dotenv.parsed
})
这里是我的 .gitlab-ci 文件,供大家参考.
Here is my .gitlab-ci file for reference in case anyone here wants to see.
cache:
paths:
- node_modules/
stages:
- build
- test
- deploy
Build_Site:
image: node:8-alpine
stage: build
script:
- npm install --progress=false
- npm run-script build
artifacts:
expire_in: 1 week
paths:
- build
Run_Tests:
image: node:8-alpine
stage: test
script:
- npm install --progress=false
- npm run-script test
Deploy_Production:
image: google/cloud-sdk:latest
stage: deploy
environment: Production
only:
- master
script:
- echo $DEPLOY_KEY_FILE_PRODUCTION > /tmp/$CI_PIPELINE_ID.json
- gcloud auth activate-service-account --key-file /tmp/$CI_PIPELINE_ID.json
- gcloud config set project $PROJECT_ID_PRODUCTION
- gcloud info
- gcloud --quiet app deploy
after_script:
- rm /tmp/$CI_PIPELINE_ID.json
另外,请随时批评我的 gitlab-ci.yml 文件,以便我可以改进它.
Also, feel free to critique my gitlab-ci.yml file so I can make it better.
推荐答案
我不知道你是否还需要这个,但这就是我实现的,你想要的.
I don't know if you still need this, but this is how I achieved, what you wanted to.
在您的 gitlab 存储库配置中创建您的环境变量
Create your environment variables in your gitlab repo config
创建setup_env.sh
:
#!/bin/bash
echo API_URL=$API_URL >> .env
echo NODE_ENV=$NODE_ENV >> .env
- 修改你的
.gitlab-ci.yml
.在下面插入到您的before_script:
部分
- Modify your
.gitlab-ci.yml
. Upsert below to yourbefore_script:
section
- chmod +x ./setup_env.sh
- ./setup_env.sh
- 在
webpack.config.js
中使用 https://www.npmjs.com/package/dotenv
require('dotenv').config();
这会传递 webpack.config.js
文件中可用的 .env
变量.
This passes your .env
variables available in webpack.config.js
file.
将此添加到您的 plugins
数组中(添加您需要的那些变量):
Add this to your plugins
array (add those variables you need):
new webpack.DefinePlugin({
'process.env.API_URL': JSON.stringify(process.env.API_URL),
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
...
})
现在您的部署应该使用您在 gitlab 设置中指定的环境变量.
Now your deployment should use your environment variables specified in you gitlab settings.
这篇关于如何在部署阶段在 gitlab ci 中添加 .env 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!