Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through Gitlab-ci inputs array type

With introduction of the array type for Gitlab-ci inputs I have wanted to do things such as looping through the contents of that array, however what I have found is that even though it's set as a type of array, bash does not see it as a conventional array in bash.

For example if we have something like this:

spec:
  inputs:
    tags:
      type: array
      default:
         - "${CI_COMMIT_SHA}"
         - "latest"

---

print-tags:
   image: alpine:latest
   stage: build
   script: |
       tags=$[[ inputs.tags]]
       for tag in "${tags[@]}"    
       do
          echo $tag
       done

It will produce an error like: /busybox/sh: eval: line 186: latest]: not found.

So how can we loop through inputs declared with the type of array?

like image 835
Popeye Avatar asked Sep 08 '26 11:09

Popeye


1 Answers

In our environment, the rendered input also appeared as ["foo", "bar", "baz"], which is actually the JSON representation of the input array. Attempting to iterate over this input with a for loop does not work because it is a single JSON-formatted string rather than a Bash array.

The suggested approach to use tr to remove special characters like " and , wasn't a suitable approach for us, as it could inadvertently remove characters we wanted to keep in the input. Instead, we opted to use jq to parse the JSON string, allowing us to process each element in the array individually, preserving any contained commas, quotes etc.:

echo '$[[ inputs.set_env_vars ]]' | jq -r '.[]' | while read -r entry; do
  # do something with $entry
done
like image 126
martin Avatar answered Sep 11 '26 22:09

martin