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
?
Answering my own question as I spent a while on this problem a couple weeks back and struggled to find anything.
If we take a look at what $[[ inputs.tags ]]
actually prints out to console it would look something like: [ed64f4cc, latest]
, but when we loop through using for tag in "${tags[@]}"
it seems to include the [
and ]
as part of each entry in the so called array. I think it’s not an array in the conventional sense that bash likes it in and it’s actually converted to a String and the for loop is treating the ,
as the delimiter and sees the [
and ]
as being part of each value in that string.
What I have found that works for me is removing the [
and ]
beforehand like: tags=$(echo "$[[ inputs.tags ]]" | tr -d '[]."')
which allows me to loop through using for tag in ${tags}
Full example:
spec:
inputs:
tags:
type: array
default:
- "${CI_COMMIT_SHA}"
- "latest"
---
print-tags:
image: alpine:latest
stage: build
script: |
tags=$(echo "$[[ inputs.tags ]]" | tr -d '[]."')
for tag in "${tags}"
do
echo $tag
done
Which then gives me the output of:
ed64f4cc
latest