Conditional logic inside script tag in gitlabci yaml based on pipeline variables

Viewed 349

I have a pipeline which will be having suite coming in as pipeline argument.

For example it will be as

SUITE = TEST1 or TEST2 or TEST3

These 3 values can come in from pipeline argument variables

I have written yaml file as :

- if ["$SUITE" == "TEST1"]; then
    -   mvn clean verify -s settings.xml -DfailIfNoTests=false -P 'test.db.it'
- if ["$SUITE" == "TEST2"]; then
    -   mvn clean verify -s settings.xml -DfailIfNoTests=false -P 'test.db.it2'
- else
    -   mvn clean verify -s settings.xml -DfailIfNoTests=false -P 'test.db.it3'   
- fi

However this is not workin and i am getting following error in pipeline logs

/scripts-26729843-1777860709/step_script: eval: line 209: syntax error: unexpected end of file

Please suggest what i am missing here the intention here is to get a pipeline argument and then use it inside script tag for gitlab ci .yaml

1 Answers

The problem you're experiencing is that GitLab will evaluate yaml array item independently, resulting in the syntax error.

If you want to write multiline statements, you should use multiline yaml syntax.

my_job:
  script: |
    if [[ "$FOO" == "bar" ]]; then
      echo "yup"
    fi
  variables:
    FOO: "bar"

Alternatively, you can put your entire statement on a single array item.

- if [[ "$FOO" == "bar" ]]; then echo "yup"; else echo "nope"; fi

You can also mix the multiline syntax just for a single array item if you want.

my_job:
  script:
    - export FOO=bar
    - | 
      if [[ "$FOO" == "bar" ]]; then
       echo "yup"
      fi
    - echo "and so on"

I tend to prefer the 'all-in-one-line' approach because the behavior in GitLab is that the job trace will collapse (not show) the full text of the command being executed when it is multiple lines. This can make it hard to debug job behavior for users. As far as I know, there's no way to change this.

Collapsed multiline job trace

Finally, one last alternative would be to commit a shell script to the repository and just use script: "path/to/myjobscript" I find this preferable for scripts of any significant length because you can run CI checks on them, such as shellcheck.

Related