In my gitlab ci cd pipeline, i have two jobs :
- build : this job will be triggered after creating a pull request from the branch develop to a release branch. I will generate my project distribution (vuejs project), generate the version which is an environment variable (the version will be retrieved from the target branch name. if the target is release/1.0.0 then the version will be 1.0.0)
 - publish : this job will get the artifact and create a docker image based on it. the version created in the last job will be the image tag.
 
build:
  image: node:15.5.1-alpine3.10
  stage: build
  before_script:
    # retrieve the new version from the branch name
    - version="$(echo $CI_MERGE_REQUEST_TARGET_BRANCH_NAME | cut -d '/' -f 2)"
    - echo "The new version to release is $version"
  script:
    - npm install -g @vue/cli
    - npm install
    - npm run build
    # write the version to the build.env so it can be used in the next jobs
    - echo "BUILD_VERSION=$version" >> build.env
    - cat build.env
  artifacts:
    when: on_success
    paths:
      - dist
    reports:
      dotenv: build.env
  # Run this job only when merge request on release and master branches
  rules:
    - if: ($CI_MERGE_REQUEST_TARGET_BRANCH_NAME =~ /^release\/\d+\.\d+\.\d+$/) && ($CI_PIPELINE_SOURCE == "merge_request_event")
As we can see below the version BUILD_VERSION env variable has been generated.

publish:quality:
  stage: publish
  image: docker:19.03.12
  services:
    - docker:19.03.12-dind
  variables:
    CI_REGISTRY_IMAGE: 'mouhamedali/co-training-gui'
  before_script:
    - echo " The build version is $BUILD_VERSION"
    - docker login --username mouhamedali --password-stdin < $GITLAB_DOCKER_HUB_TOKEN
  script:
    - docker pull $CI_REGISTRY_IMAGE || true
    - echo "Building the docker image $CI_REGISTRY_IMAGE:$BUILD_VERSION"
    - docker build --cache-from "$CI_REGISTRY_IMAGE" -t "$CI_REGISTRY_IMAGE:$BUILD_VERSION" .
    - docker push $CI_REGISTRY_IMAGE:$BUILD_VERSION
  dependencies:
    # get artifacts only from the build job
    - build
  only:
    - /^release\/\d+\.\d+\.\d+$/
but in the next job which is publish, the BUILD_VERSION is empty.

If i change the rule of the build job to be triggered after merging develop into release, it works fine and the version is present but absent if i change the rule to merge_requests so i don't why it does not work in the second case.
ci-cd file : https://gitlab.com/co-training/co-training-gui/-/blob/develop/.gitlab-ci.yml