Search code examples
gitlabgitlab-cigitlab-ci-runner

Use $CI_JOB_ID as a constant across multiple stages of Gitlab pipeline


I have the following

stages:
    - stage1
    - stage2
variables:
        MY_ENV_VAR: env_$CI_JOB_ID
stage1_build:
    stage: stage1
    script:
        - echo $MY_ENV_VAR
stage2_build:
    stage: stage2
    script:
        - echo $MY_ENV_VAR

I get different values for $MY_ENV_VAR in the two stages (which means $CI_JOB_ID changes on every stage).

What I want is set $MY_ENV_VAR once with one value of $CI_JOB_ID and make it a constant, so that the same value of $MY_ENV_VAR is used across all stages.


Solution

  • Use $CI_PIPELINE_ID instaed, which will be constant across all jobs in the pipeline.

    variables:
      MY_ENV_VAR: env_$CI_PIPELINE_ID
    

    See predefined environment variables for additional reference.

    If you really want an environment variable to be created in one job and persist for the rest of the pipeline, you can pass variables between jobs using artifacts:reports:dotenv.

    stages:
        - stage1
        - stage2
    
    set_env:
      stage: .pre
      script:
        echo "MY_ENV_VAR=env_$CI_JOB_ID" > .myenv
      artifacts:
        reports:
          dotenv: .myenv
    
    stage1_build:
        stage: stage1
        script:
            - echo $MY_ENV_VAR
    stage2_build:
        stage: stage2
        script:
            - echo $MY_ENV_VAR