2

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
Simply Seth
  • 3,246
  • 17
  • 51
  • 77

1 Answers1

3

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
sytech
  • 29,298
  • 3
  • 45
  • 86
  • What is alternative of using common code ?, do you have idea @sytech? – Dinesh Kachhot Aug 16 '22 at 15:17
  • 1
    @DineshKachhot generally, you would reuse code using `!reference`, anchors, or similar. Instead of interpolating strings of pieces of bash scripts, you could write bash functions and include those instead. I edited to provide an example. – sytech Dec 14 '22 at 19:04