Conditional jobs with variables using only/except

#1

I’m having trouble with the following CI config for an Ansible project. I’m trying to set it up so that if I pass just the PLAY variable during the pipeline job, then only the Multiple Targets job will run, but if I pass both the PLAY and the TARGET variables, the job will only run on the Single Target job.

What’s happening is both jobs are running when I only pass the PLAY variable. My understanding was that if the variable exists or doesn’t exist, this should work but I guess I’m misunderstanding how it’s supposed to work.

Run Playbook on Multiple Targets:
  stage: play
  script: 
    - docker build --build-arg SSH_KEY="$SSH_KEY" --build-arg SSH_USER="$SSH_USER" -t $IMAGE .
    - docker run --rm $IMAGE -v ./playbooks/$PLAY.yml | sed 's/\\n/\n/g'
    - docker rmi $IMAGE
  only:
    variables:
      - $PLAY
  except:
    variables:
      - $TARGET

Run Playbook on Single Target:
  stage: play
  script: 
    - docker build --build-arg SSH_KEY="$SSH_KEY" --build-arg SSH_USER="$SSH_USER" -t $IMAGE .
    - docker run --rm $IMAGE -v ./playbooks/$PLAY.yml -e working_host=$TARGET | sed 's/\\n/\n/g'
    - docker rmi $IMAGE
  only:
    variables:
      - $PLAY
      - $TARGET
#2

Hello @speedpacer,

Please check this link:
https://docs.gitlab.com/ee/ci/variables/#supported-syntax

Here it shows you how to evaluate the variables for only/except

#3

Thanks, @ariel.barria. I’ve been all through this document but it’s missing some crucial information that was causing my confusion. I realized after multiple tests what was happening.

In case anyone else stumbles on this, if you’re testing multiple variables for values in this fashion, be aware that they are OR conditions rather than AND conditions. So in my Single Target job where I was expecting that both PLAY “and” TARGET variables had values, GitLab was checking to see whether PLAY “or” TARGET had values. Simply removing the PLAY condition solved my problem.

1 Like