how to add a "needs" based on a condition
Asked Answered
T

2

9

Is there a way to add a need in order for a job to run? Or is there a specific way to add a condition if you're on a specific branch, please add this job as a dependency? So far I have a "need"s within my rules section. Review job only runs on feature branches. There is a similar question being asked.

test:sauce:
  ...
  script:
    - export MASTER_URL=https://masterurlexample.io
    - export TEST_PREVIEW_APP=$CI_COMMIT_REF_SLUG
    - cd $MAVEN_DIRECTORY
    - if [ "$CI_COMMIT_BRANCH" == "master" || "$EMULATE_BRANCH" == "master" ]; then
        export TEST_PREVIEW_APP=$MASTER_URL;
        needs:
      fi;
    - echo "Testing on $TEST_PREVIEW_APP"
    - echo "starting test"
    - sleep 30
    - mvn -U $MAVEN_CLI_OPTS ...
  rules:
    - if: "$CI_COMMIT_BRANCH" != "master"
      needs: [ "review "]
Teishateixeira answered 18/7, 2022 at 23:1 Comment(0)
P
4

On modern Gitlab, there's another workaround for this in the form of the needs:optional syntax

If the 'review' job only exists on the branch of interest, you can mark it as "optional" and gitlab will ignore the fact that it doesn't exist on pipelines on other branches.

test:sauce:
 # ...
 needs:
 - job: 'review'
   optional: true

If the 'review' job exists unconditionally, you can make a dummy job that only exists on the branch.

review_on_master:
  needs: ['review']
  variables:
    GIT_STRATEGY: none
  script: ['true']
  rules:
  - if: "$CI_COMMIT_BRANCH" != "master"
    when: never

test:sauce:
 # ...
 needs:
 - job: 'review_on_master'
   optional: true
Pentode answered 29/4 at 21:21 Comment(0)
S
1

I think is not possible.

A workaround could be make a template job (starting the name with .) cointaining your code and extends the job two time, one time for the case "$CI_COMMIT_BRANCH" != "master" with needs: [ "review "] and another time with - if: "$CI_COMMIT_BRANCH" == "master" without the needs section.

EDIT: I try to explain myself better, my idea is to use an hidden job like

.hidden_job:
  script:
    - YOUR CODE HERE

And after that extended this job into others with the right needs setted, like:

job1:
  extends: .hidden_job
  rules:
    - if: "$CI_COMMIT_BRANCH" != "master"
    needs: [ "review "]


job2:
  extends: .hidden_job
  rules:
    - if: "$CI_COMMIT_BRANCH" == "master"

In this way you can define multiple job with different rules and needs for satisfy your requirements without repeating your code everytime. (E.G. use a specific needs only on a specific branch, like job1)

Sternick answered 19/7, 2022 at 17:32 Comment(2)
What do you mean by extends the job?Teishateixeira
I edited my answer to better explain myselfSternick

© 2022 - 2024 — McMap. All rights reserved.