Search code examples
gitlab-cipipeline

Running a gitlab-ci job when a file exists


I'm trying to configure gitlab-ci to run two jobs depending on the presence of a Dockerfile using the exists directive.

I want job01 to be executed by tag, but only if there is no Dockerfile, and job02 to be executed by tag if there is a Dockerfile in the project. So, depending on whether the project has a Dockerfile, one of the jobs job01 or job02 should run, but not both together.

Right now I am only able to run job01 if there is no Dockerfile, but if there is one, then both jobs run at once.

job01:
  script:
    - echo "Dockerfile is not exists"
  rules:
    - if: '$CI_COMMIT_TAG'
    - if: '$CI_COMMIT_TAG'
      exists:
      - Dockerfile
      when: never

job02:
  script:
    - echo "Dockerfile is exists"
  rules:
    - if: '$CI_COMMIT_TAG'
      exists:
      - Dockerfile

Maybe someone can tell me how to implement this, unfortunately there is no not-exists directive in gitlab-ci?


Solution

  • Gitlab rules are read from top to bottom. It will take the first matching rule and ignore all other rules. So in your case ordering the rules like you did will always run the first job if a tag exists, because the first rule always matches. Try to switch the two rules to get

    job01:
      script:
        - echo "Dockerfile is not exists"
      rules:
        - if: '$CI_COMMIT_TAG'
          exists:
          - Dockerfile
          when: never
        - if: '$CI_COMMIT_TAG'