Search code examples
gitlab-cigitlab-ci-runnercicd

How to export a variable to all of the stages in CICD?


I have some stages and I need to create a name for a folder in one stage and use it in another stage. like the code below :

  ...
  before_script:
    - cd publish
    - export TZ=Europe/Madrid
    - ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
    - export BACKUP_FOLDER_NAME=$(date +%Y%m%d.%H%M)
  ...

and now I want to create a folder in another stage and name it the date in BACKUP_FOLDER_NAME. How to do that?


Solution

  • You can use dotenv report artifacts to pass variables to subsequent stages/jobs via artifacts

    set-variables:
      stage: .pre # always the first stage in a pipeline
      script:
        # ... set your variables
        # create the dotenv file
        - echo "BACKUP_FOLDER_NAME=${BACKUP_FOLDER_NAME}" > vars.env
      artifacts:
        reports:
          dotenv: "vars.env"
    
    build:
      stage: build
      script:
        # this variable was set automatically by the artifact
        - echo "$BACKUP_FOLDER_NAME"
    # ...
    

    However, if you just want a common time for all jobs in a pipeline to use, you can use the predefined variable $CI_PIPELINE_CREATED_AT which is an ISO8601 timestamp of the pipeline creation time (e.g., 2023-07-17T17:11:20Z).

    before_script:
      # in case your image doesn't have tzdata configured use this step:
      - DEBIAN_FRONTEND=noninteractive apt update && apt install -y tzdata
      # use $CI_PIPELINE_CREATED_AT to form the backup folder name:
      - BACKUP_FOLDER_NAME=$(TZ='Europe/Madrid' date -d "$CI_PIPELINE_CREATED_AT" +%Y%m%d.%H%M)
      - echo "backup folder is ${BACKUP_FOLDER_NAME}"
    

    In this case, you won't have to pass any variables between jobs because CI_PIPELINE_CREATED_AT is the same value for all jobs in the same pipeline.