Job: trigger if?

I would like a trigger job to run or not depending on some variable that I set before. Is that possible?

In other words, I want something like this:


job1:
  stage: stage1
  script:
    - (some stuff)
    - TRIGGER_NEXT=(depends on above)
    - echo "TRIGGER_NEXT=$TRIGGER_NEXT" >> vars.env
  artifacts:
    reports:
      dotenv: vars.env

job2:
  stage: stage2
  rules:
    - if: $TRIGGER_NEXT == "true"
  trigger:
    project: 'my-other-project'
    strategy: depend

Sadly this doesn’t work, because (afaik) the rules in job2 are evaluated before job1 runs.

My current “solution” is to resort to an API call instead of using trigger:


job1+2:
  stage: stage1+2
  script:
    - (some stuff)
    - TRIGGER_NEXT=(depends on above)
    - >
      if [[ "${TRIGGER_NEXT}" == 'true' ]] ; then
        curl --fail --request POST --form token="${CI_JOB_TOKEN}" "${CI_API_V4_URL}/projects/${OTHER_PROJECT_ID}/trigger/pipeline"
      fi

This works fine, but I am not completely satisfied because I want the strategy: depend (i.e. job is marked as successful only after downstream pipeline succeeds).

I can’t think of a way (even hacky) to do what I want with the current possibilities of Gitlab, but maybe I’m not thinking of something?

I’m no expert in this area, but I believe you’re right about the rules being evaluated at the start.

Have you considered using a dynamic child pipeline?

As part of job1, or a separate job that reads the output of job1, you can generate the configuration for the dynamic pipeline based on TRIGGER_NEXT. For the negative path, write an empty configuration so no pipeline will be created.

Hi @thiagocsf, thank you for your answer. A dynamic child pipeline is a good idea, but in this case I actually want to trigger (or not) another project’s pipeline (“multi-project pipeline”).

I suppose the child pipeline’s file could say either “do nothing”, or “trigger the other project’s pipeline downstream”. That would work, but it adds another level of nesting which I’d rather not have.

1 Like

Ah, fair enough. In this case I think your current solution is better (simpler).