How to use if-else condition on gitlabci

Vikas Rathore picture Vikas Rathore · Feb 19, 2019 · Viewed 45.2k times · Source

How to use if else condition inside the gitlab-CI.

I have below code:

deploy-dev:
  image: testimage
  environment: dev
  tags:
    - kubectl
  script:
   - kubectl apply -f demo1 --record=true
   - kubectl apply -f demo2 --record=true

Now I want to add a condition something like this

script:
    - (if [ "$flag" == "true" ]; then kubectl apply -f demo1 --record=true; else kubectl apply -f demo2 --record=true);

Could someone provide the correct syntax for the same? Is there any documentation for the conditions (if-else, for loop) in gitlabci?

Answer

Xavier D picture Xavier D · Apr 1, 2019

Hereunder three syntax options for that kind of statement.

Using shell variable

deploy-dev:
image: testimage
environment: dev
tags:
 - kubectl
script:
 - if [ "$flag" == "true" ]; then MODULE="demo1"; else MODULE="demo2"; fi
 - kubectl apply -f ${MODULE} --record=true

Using yaml multiline block

deploy-dev:
image: testimage
environment: dev
tags:
  - kubectl
script:
  - >
    if [ "$flag" == "true" ]; then
      kubectl apply -f demo1 --record=true
    else
      kubectl apply -f demo2 --record=true
    fi

Using gitlab templates and variables

demo1-deploy-dev:
extends: .deploy-dev
only:
  variables: [ $flag == "true" ]
variables:
MODULE: demo1

demo2-deploy-dev:
extends: .deploy-dev
only:
  variables: [ $flag == "false" ]
variables:
  MODULE: demo2

.deploy-dev:
image: testimage
environment: dev
tags:
  - kubectl
script:
  - kubectl apply -f ${MODULE} --record=true