检查 Gitlab 管道中的变量是否为 null

Luc*_*ano 10 gitlab gitlab-ci

当使用另一个 null 变量的内容声明它时,如何检查 Gitlab 管道中的 null 变量?VAR_NULL就像下面的变量当NO_VAR为 null 时:

variables:
  VAR_EMPTY: ""
  VAR_NULL: "${NO_VAR}"
Run Code Online (Sandbox Code Playgroud)

检查管道结果,其中仅VAR_EMPTY == ""评估NO_VAR == nulltrue,所有其他均为false

管道结果为了方便起见,截图,完整结果:https://gitlab.com/labaz/test-gitlab-pipeline-null-var/-/p ​​ipelines/ 493036820): 管道结果

完整的管道脚本https://gitlab.com/labaz/test-gitlab-pipeline-null-var/-/blob/main/.gitlab-ci.yml):

variables:
  VAR_EMPTY: ""
  VAR_NULL: "${NO_VAR}"

jobTest-Var_Empty-IsNull:       # This job runs in the build stage, which runs first.
  rules:
    - if: '$VAR_EMPTY == null'
  script:
    - 'echo "VAR_EMPTY IS null"'

jobTest-Var_Empty-IsEmpty:       # This job runs in the build stage, which runs first.
  rules:
    - if: '$VAR_EMPTY == ""'
  script:
    - 'echo "VAR_EMPTY IS \"\""'

jobTest-Var_Null-IsNull:       # This job runs in the build stage, which runs first.
  rules:
    - if: '$VAR_NULL == null'
  script:
    - 'echo "VAR_NULL IS null"'

jobTest-Var_Null-IsEmpty:       # This job runs in the build stage, which runs first.
  rules:
    - if: '$VAR_NULL == ""'
  script:
    - 'echo "VAR_NULL IS Empty"'

jobTest-No_Var-IsNull:       # This job runs in the build stage, which runs first.
  rules:
    - if: '$NO_VAR == null'
  script:
    - 'echo "NO_VAR IS null"'

jobTest_No_Var-IsEmpty:       # This job runs in the build stage, which runs first.
  rules:
    - if: '$NO_VAR == ""'
  script:
    - 'echo "NO_VAR IS Empty"'    
Run Code Online (Sandbox Code Playgroud)

syt*_*ech 12

您遇到的问题是这VAR_NULL: "${NO_VAR}"不是空变量。它实际上是一样的VAR_EMPTY: ""——你用空值声明变量(因此它不为空)。

测试变量是否是用另一个空变量创建的唯一方法是测试原始变量本身。也就是说,测试NO_VAR,而不是VAR_NULL

另一种策略是使用rules:variables:以便有条件地声明VAR_NULL

workflow:
  rules:
    - if: '$NO_VAR' # or '$NO_VAR != null' depending on what you want
      variables:
        VAR_NULL: "$NO_VAR"
    - when: always

jobTest-Var_Null-IsNull:
  rules:
    - if: '$VAR_NULL == null'
  script:
    - echo "VAR_NULL is null"
Run Code Online (Sandbox Code Playgroud)