Simply  Seth
Simply Seth

Reputation: 3496

gitlab yaml anchor reference in an if clause

Is it possible, or is there a way, to use a yaml anchor reference in a BASH if clause. If so, how? This is what I'm attempting so far.

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

Upvotes: 4

Views: 2611

Answers (1)

sytech
sytech

Reputation: 40901

No, the YAML spec does not allow you to do this. YAML anchors cannot be used within a string (or any other scalar).

A better approach for GitLab CI YAML would be to define your reusable bash steps as functions then utilize those within your job script logic as-needed.

For example, you can define a function does_cluster_exist and reference it using 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

Upvotes: 6

Related Questions