【问题标题】:Checking if variable is null in Gitlab pipeline检查 Gitlab 管道中的变量是否为空
【发布时间】:2022-12-16 06:14:54
【问题描述】:

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

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

检查管道结果,其中只有 VAR_EMPTY == "" 和 NO_VAR == null 评估为真的所有其他人都是错误的.

流水线结果(为方便起见截图,完整结果:https://gitlab.com/labaz/test-gitlab-pipeline-null-var/-/pipelines/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"'    

【问题讨论】:

    标签: gitlab


    【解决方案1】:

    您遇到的问题是 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"
    

    【讨论】:

    • 目前,我们有一个模板管道脚本 (.gitlab-ci.yml),项目可以设置它映射内部变量和外部变量(项目或组变量)。我们希望避免必须检查外部变量(耦合),因此在这种情况下,只在内部修复变量名称(以及随之而来的外部变量名称)听起来更好。无论如何,谢谢你的帮助。
    【解决方案2】:
    workflow:
      rules:
        - if: '$NO_VAR' # or '$NO_VAR != null' depending on what you want
          variables:
            VAR_NULL: "$NO_VAR"
        - when: always
    

    这将始终评估为真,因此作业将始终运行。 所以它不是根据变量的状态使作业“不运行”的方法

    【讨论】:

      猜你喜欢
      • 2016-03-26
      • 2012-02-05
      • 2022-10-21
      • 2022-01-21
      • 2011-03-20
      • 2021-05-12
      相关资源
      最近更新 更多