【问题标题】:gitlab yaml anchor reference in an if clauseif 子句中的 gitlab yaml 锚点引用
【发布时间】:2022-12-15 03:09:59
【问题描述】:

是否有可能,或者有没有办法,在 BASH if 子句中使用 yaml 锚点引用。 如果是这样,如何? 到目前为止,这是我正在尝试的。

create-cluster:
  needs: 
    - terra-bootstrap
  script:
    - export TF_VAR_state_bucket_prefix="${TF_VAR_vsad}/${TF_VAR_cluster_name}"
    - pushd terra-cluster
    - *init_with_gcs_state
    - |
      if [[ "${CLUSTER_EXISTS}" == 'false' ]]; then
       terraform apply -auto-approve
       *does_cluster_exist
      fi
    - popd
  stage: create-cluster
  tags:
    - gke

【问题讨论】:

    标签: yaml gitlab-pipelines yaml-anchors


    【解决方案1】:

    不,YAML 规范不允许您这样做。不能使用 YAML 锚点一个字符串(或任何其他标量)。

    GitLab CI YAML 的更好方法是将可重用的 bash 步骤定义为函数,然后根据需要在作业脚本逻辑中使用这些步骤。

    例如,您可以定义一个函数 does_cluster_exist 并使用 anchors/reference/etc 引用它。

    .helper_functions:
      script: |
         function cluster_exists() {
             cluster="$1"
             
             # ... complete the function logic
         }
    
         function another_function() {
             return 0
         }
    
    another_job:
      before_script:
        # ensure functions are defined
        - !reference [.helper_functions, script]
      script:
        # ...
        # use the functions in an `if` or wherever...
        - |
          if cluster_exists "$cluster"; then
             another_function
          else
             echo "fatal, cluster does not exist" > /dev/stderr
             exit 1
          fi
    

    【讨论】:

    • 使用通用代码的替代方法是什么?@sytech,你有想法吗?
    猜你喜欢
    • 2017-02-25
    • 2019-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-01
    • 2017-12-08
    • 1970-01-01
    • 2022-08-18
    相关资源
    最近更新 更多