Pass an environment variable to another job

I want to pass variable from one stage to another moreover I want to use that variable in definition of stage’s docker image that need to be used.

I want to do something like that:

first-stage:
  stage: .pre
  script:
	- echo "MY_TAG=dynamic_image_name_123" > build.env
  artifacts:
    reports:
      dotenv: build.env

second-stage:
  stage: build
  image: ${MY_TAG}
  needs:
    - first-stage
  script:
    - echo ${TAG_NAME}

According to this it’s possible:

I can pass that variable via build.env but it’ll be only viseable under script: of next stages.
But this sentence below from the documentation suggests me that something like that won’t be possible image: ${MY_TAG} cuz this variable won’t be available in there:

"These variables cannot be used as CI/CD variables to configure a pipeline, but they can be used in job scripts."

However it actually works :see_no_evil: so here is my question, it works properly and I misunderstood this sentence from documentation ?
My maybe it works for now by accident and I shouldn’t use it like that, cuz it may stop working in the future ?

2 Likes

For using variables in the image property, it is required to define them as documented #define-a-cicd-variable-in-the-gitlab-ciyml-file

Maybe, you can use the Gitlab default values to compose your image tag before hand (e.g. $CI_COMMIT_REF_SLUG-$CI_COMMIT_SHORT_SHA)

But I can’t use default values I need to use a custom one.

Setting it like this works:

first-stage:
  stage: .pre
  script:
	- echo "MY_TAG=dynamic_image_name_123" > build.env
  artifacts:
    reports:
      dotenv: build.env

I can use MY_TAG to define image name, but the problem is that according to the docs it shouldn’t work.