fobus
fobus

Reputation: 2058

Gitlab-CI run Stage conditionally

As you see below I have two stages.

1- Build

2- Deploy

And I have 3 kind of branches

1- master

2- test

3- Other branches which created by developers. (Development)

I want to run build for all branches but I have a condition for deploy

1- If branch is test run deploy.

2- If branch is other branches don't run deploy.

3- if branch is master run deploy only manual.

But this three condition doesn't works properly with my gitlab-ci.yml

stages:
  - build
  - deploy
default:
  image: node:latest

  before_script:
    - |
      if [ "$CI_BUILD_REF_NAME" == "master" ]; then
          ENV="prod"
      elif [ "$CI_BUILD_REF_NAME" == "test" ]; then
          ENV="test"
      else
          ENV="dev"
      fi
    - npm install

build:
  stage: build
  script:
    - cp ./src/env-${ENV}.js ./src/env.js
    - npm run build-compressed

deploy:
  stage: deploy
  rules: //this section doesn't work properly
    - if: '$ENV == "test"'
      when: always
    - if: '$ENV == "prod"'
      when: manual
    - when: never
  script:
    - cp ./src/env-${ENV}.js ./src/env.js
    - npm run build-compressed
    - npm run publish:${ENV}

Upvotes: 1

Views: 6479

Answers (1)

Simon Schrottner
Simon Schrottner

Reputation: 4744

I recommend doing such a differentiation via Rules. As you can easily override variables with rules, see GitLab CI Doc.

Below you can find a short example

rules
- if: $CI_COMMIT_BRANCH =~ /test/
  variables:                              # Override ENV defined
    ENV: "test"  # at the job level.
- if: $CI_COMMIT_BRANCH =~ /master/
  variables:                              # Override ENV defined
    ENV: "prod"  # at the job level.
- variables: # not 100% sure about this one, as when can stand without a if clause, i assume variables can too :D
    ENV: "dev" 

Furthermore i would also do the rule check based on the branch within the deploy stage. - as it is easier to verify the branch, than to ensure at a later stage, that the Env variable is still set properly.

Also important to notice is the order of evaluation. Just because there is a before_script in the default section, does not mean it is evaluated just once for the whole. The before_script is evaluated once per Job.

Additionally the rules are evaluated, before the JOB runs, as it needs to determine if the job should be executed or not. This means you are not able to reference the variable from the before_script.

If you want to pass on the variable from the first job to the second job, you need to persist it in a dotenv-artifact - this way, the variables are available before the second stage start. (I am still not sure if you can use them for evaluation in rules, that is something you need to check)

I hope my additional clarifications, based on your comments, help you to find the best way.

Upvotes: 2

Related Questions