How to get ENV variable set on build step based on deploy ENV

How to get build ENV variables set based on Deploy environments?

During the build step, there is a need to pass ENVIRONMENT variables, for the build as well. On branch develop, deploy environment is dev, for the build step we need to pass PROJECT_ENV as development, on branch release, deploy environment is staging, for the build step, PROJECT_ENV should be set as staging.

setting the PROJECT_ENV is not sufficient

global variables dont show up in build step and if environment is not declared. Is there an obvious solution I am missing here with dynamic variables?

I can only think of introducing CI Triggers to invoke a pipeline with a variable name

build:backend:
  stage: build
  image: node:12
  rules:
    - if: '$CI_COMMIT_BRANCH == "develop"'
    - if: '$CI_COMMIT_BRANCH == "release"'
  script:
    - echo "NX_PROJECT_ENV=$NX_PROJECT_ENV" > .env

build:frontend:
  stage: build
  image: node:12
  rules:
    - if: '$CI_COMMIT_BRANCH == "develop"'
    - if: '$CI_COMMIT_BRANCH == "release"'
  script:
    - echo "NX_PROJECT_ENV=$NX_PROJECT_ENV" > .env

Deploy Dev:
  stage: deploy
  environment:
    name: dev
    url: https://${BACKEND_DOMAIN}
  rules:
    - if: '$CI_COMMIT_BRANCH == "develop"'

Hi @sairam-oe

when you create the environment variable in your project settings you can give that variable a scope which is the environment that the variable should be defined in. For your develop branch, if there isn’t and environment defined in .gitlab-ci.yml you can set the variable to be scoped in All environments.

I setup for ‘dev’ environment, but the variable is not picking it up since there is no way to link develop with dev unless I setup that mapping via ‘environment’ field.

If you make your environment variable for dev scoped to “all” environments, then it will be picked up by any environment except your named environments.

However, you can also use environment:action here, for example:

build:
  stage: build
  image: node:12
  script:
    - echo "NX_PROJECT_ENV=$NX_PROJECT_ENV" > .env

build:dev:
  <<: *build
  variables:
    PROJECT_ENV: dev
  rules:
    - if: '$CI_COMMIT_BRANCH == "develop"'
  environment:
    name: dev
    action: prepare

build:production:
  <<: *build
  variables:
    PROJECT_ENV: staging
 rules:
    - if: '$CI_COMMIT_BRANCH == "release"'
  environment:
    name: staging
    action: prepare 

build:production:
  <<: *build
  variables:
    PROJECT_ENV: production
 rules:
    - if: '$CI_COMMIT_BRANCH == "release"'
  environment:
    name: production
    action: prepare 

If I was doing something like this, I would be inclined to make two small changes:

  1. Use YAML anchors for the rules and environment names
  2. Use $CI_ENVIRONMENT_NAME instead of PROJECT_ENV.
2 Likes

Thanks @snim2, I ended up using YAML anchors to achieve this.

1 Like