首页 > 解决方案 > 如何构建基于先前在同一管道中定义的 dotenv 变量的规则

问题描述

我正在管道中的作业中设置一个变量,并在工件/dotenv 中使用它。将变量用作规则中的条件似乎不起作用。如何设置环境变量并在另一个 Job 的规则中使用它?

非常感谢您的想法!

include:
  - local: '/gitlab/cicd/.gitlab-ci_test.yml'

stages:
  - build
  - test
  
    
build_rule:
  stage: build
  rules:
    - if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_MESSAGE =~ /R::/m
  script:
    - echo "Hello World"
    - |
      echo "RUNTESTS=1" > gitlabcicd.env
  artifacts:
    reports:
      dotenv: gitlabcicd.env
test_always:
  stage: test
  script: 
    - echo "TestEnv" $RUNTESTS 
    # prints TestEnv 1
   
test_sometimes:
  stage: test
  rules:
    - if: $RUNTESTS
    # $RUNTESTS == "1" doesnt work either
  script:
    - echo "Runs only if variable was set"
    # doesnt run, even if it prints above

标签: gitlabgitlab-ci

解决方案


需要在每个作业上加载 .env 文件

"Set variables":
  stage: preparation
  script:
    - echo version=1.1 > varfile
    - echo foo=bar >> varfile
  artifacts:
    paths:
      - varfile

Dothings:
  stage: run
  script:
    - load varfile
    - echo ${foo}

推荐阅读