13

I want to use arrays in variables of my gitlab ci/cd yml file, something like that:

variables:
    myarrray: ['abc', 'dcef' ]
....
script: |
    echo myarray[0]  myarray[1]

But Lint tells me that file is incorrect:

variables config should be a hash of key value pairs, value can be a hash

I've tried the next:

variables:
    arr[0]: 'abc'
    arr[1]: 'cde'
....
script: |
    echo $arr[0] $arr[1]

But build failed and prints out bash error:

bash: line 128: export: `arr[0]': not a valid identifier

Is there any way to use array variable in .gitlab-ci.yml file?

Tadeusz
  • 6,453
  • 9
  • 40
  • 58

3 Answers3

20

According to the docs, this is what you should be doing:

It is not possible to create a CI/CD variable that is an array of values, but you can use shell scripting techniques for similar behavior.

For example, you can store multiple variables separated by a space in a variable, then loop through the values with a script:

job1:
  variables:
    FOLDERS: src test docs
  script:
    - |
      for FOLDER in $FOLDERS
        do
          echo "The path is root/${FOLDER}"
        done
Bernardo Duarte
  • 4,074
  • 4
  • 19
  • 34
  • 1
    To extend on this further, environment variables, in general, [cannot be arrays](https://unix.stackexchange.com/a/393096/453397). So, to be clear: this is more a limitation of bash/environment variables than it is of GitLab CI. – sytech Nov 17 '21 at 20:01
  • In Windows cmd they can be... set arr[1]=a and then set arr[2]=b are valid and works fine – Tadeusz Nov 18 '21 at 06:59
  • 1
    @Vasya When you issue `set arr[1]=a` and then `arr[2]=b` commands in Windows terminal it wont create an array, it will create two environment variables called `arr[1]` and `arr[2]` – Bernardo Duarte Nov 18 '21 at 12:44
1

Another approach you could follow is two use a matrix of jobs that will create a job per array entry.

deploystacks:
  stage: deploy
  parallel:
    matrix:
      - PROVIDER: aws
        STACK: [monitoring, app1]
      - PROVIDER: gcp
        STACK: [data]
  tags:
    - ${PROVIDER}-${STACK}

Here is the Gitlab docs regarding matrix https://docs.gitlab.com/ee/ci/jobs/job_control.html#run-a-one-dimensional-matrix-of-parallel-jobs

Eligio Mariño
  • 318
  • 4
  • 13
0

After some investigations I found some surrogate solution. Perhaps It may be useful for somebody:

variables:
    # Name of using set
    targetType: 'test'

    # Variables set test
    X_test: 'TestValue'

    # Variables set dev
    X_dev: 'DevValue'

    # Name of variable from effective set
    X_curName: 'X_$targetType'

.....

script: |
    echo Variable X_ is ${!X_curName} # prints TestValue
Tadeusz
  • 6,453
  • 9
  • 40
  • 58