How to setup environment variable in Gitlab CI and make it testable in local

Viewed 2022

Current project structure:

…
-src
-.env.development
-.env.uat
-.env.production
-webpack
    -webpack.base.js
    -webpack.dev.js
    -webpack.uat.js
    -webpack.prod.js

In webpack, I set new Dotenv({ path: "./.env.development" }) for development environment, etc

webpack.dev.js

const { merge } = require("webpack-merge");

const base = require("./webpack.base");

const Dotenv = require("dotenv-webpack");

module.exports = merge(base, {
  mode: "development",
  output: {...},
  devServer: {...},
  plugins: [new Dotenv({ path: "./.env.development" })],
});

webpack.uat.js

const { merge } = require("webpack-merge");
const base = require("./webpack.base");

const Dotenv = require("dotenv-webpack");

module.exports = merge(base, {
  mode: "production",
  output: {...},
  module: {...},
  plugins: [
    new Dotenv({ path: "./.env.uat" }),
    ...
  ],
});

webpack.prod.js

const { merge } = require("webpack-merge");
const base = require("./webpack.base");

const Dotenv = require("dotenv-webpack");

module.exports = merge(base, {
  mode: "production",
  output: {...},
  module: {...},
  plugins: [
    new Dotenv({ path: "./.env.prod” }),
    ...
  ],
});

package.json

  "scripts": {
    "build:uat": "cross-env NODE_ENV=uat webpack --config ./webpack/webpack.uat.js",
    "build": "webpack --config ./webpack/webpack.prod.js",
  },

I am going to use Gitlab CI and CI/CD, so I am thinking how to handle the .env variables.
I’ve added environment variables in gitlab Settings > CI/CD > Variables.
After adding it, I have no idea how to proceed to next step.
Also, how to I test if the environment variables is set in gitlab?

1 Answers

Take a look at the Gitlab CI/CD Docs. They are quite good: https://docs.gitlab.com/ee/ci/variables/

You can define variables in a number of different ways, like through the web portal of your project, or within the .gitlab-ci.yml file. Regardless of where you are defining them, access the values in your .gitlab-ci.yml file is the same:

test_variable:
  stage: test
  script:
    - echo "$MY_AWESOME_VAR"

$MY_AWESOME_VAR is the name of the variable you created, with a $ prepended to it.

Gitlab also creates a bunch of standard environment variables related to the CI/CD process that you can tie into as well. https://docs.gitlab.com/ee/ci/variables/predefined_variables.html

These can be handy for a bunch of different things. For example, in projects that I am working on I save build artifacts and name the generated artifacts using a concatenation of $CI_ENVIRONMENT_NAME-$CI_COMMIT_REF_SLUG-$CI_COMMIT_SHORT_SHA

Related