Search code examples
bashyamlgitlab-cidotenv

gitlab-ci : preload variables from file


I have a simple stage something like this:

build-hw:
  stage: build
  when: on_success
  timeout: 10 hours
  before_script:
    source /usr/local/bin/setup_env.sh
  script:
    - make build
    - make export_hw sw/$SW_PRJ/xsa
  artifacts:
    name: "$CI_JOB_NAME-$CI_COMMIT_REF_NAME-$CI_COMMIT_SHORT_SHA"
    expire_in: 1 hour
    paths:
      - $HW_PRJ/$HW_PRJ.runs/*.log
      - $HW_PRJ/$HW_PRJ.runs/impl_1/top.bit
      - $HW_PRJ/$HW_PRJ.runs/impl_1/top.ltx
      - sw/$SW_PRJ/xsa/top.xsa

And a few variables set in the .gitlab-ci file

variables:
      HW_PRJ: "pl-build"
      SW_PRJ: "ps-build"

What I've already done:

  1. created ".env" and put these variables there
  2. edit before_script with another line: set -o allexport; source .env; set +o allexport`

but it's applying the variables only inside script block not in the paths

Is there any solution? Thanks in advance!


Solution

  • GitLab has a mechanism in place for this, and you shouldn't have to do much. You just have to write the vars to a file and declare it as an artifact with a dotenv ending, and then (depending on how you set it up) probably list dependencies.

    $: cat .gitlab-ci.yml
    stages:
      - build
    
    save-env:
      stage: ".pre"
      script: |
        when=$(date +%s)
        printf "%s\n" "thing1='foo'" "thing2='$when'" > sav.env
      tags:
        - VM
      artifacts:
        reports:
          dotenv: sav.env
    
    show-vars:
      stage: build
      script: echo "got [$thing1], [$thing2]"
      tags:
        - VM
      dependencies:
        - save-env
    

    The last few lines of the show-vars log:

    Executing "step_script" stage of the job script
    $ echo "got [$thing1], [$thing2]"
    got ['foo'], ['1711048904']
    Cleaning up project directory and file based variables
    Job succeeded
    

    If what you mean is that you want your exported variables from the script to be available in your .gitlab-ci YAML file's subsequent non-script directives, then I think what you need is a Trigger - see this reference.