Feedback

Chat Icon

Cloud Native CI/CD with GitLab

From Commit to Production Ready

Practical Patterns for Complex Pipeline Conditions
61%

Gotchas with Complex Conditions

We want to run a job only when there's a merge request and at least one file in specific folders has been modified. We have 4 folders to check:

  • FOLDER_A: Check if any file in the folder has been modified.
  • FOLDER_B: Check if any file in the folder and its subdirectories has been modified.
  • FOLDER_C: Check if any JSON file in the folder has been modified.
  • FOLDER_D: Check if any JSON file in the folder and its subdirectories has been modified.

This is how you can achieve this:

job:
  variables:
    FOLDER_A: "my-folder-A"
    FOLDER_B: "my-folder-B"
    FOLDER_C: "my-folder-C"
    FOLDER_D: "my-folder-D"
  script: "echo 'building and pushing the image'"
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
      changes:
        paths:
          # Check if any file in the folder has been modified
          - $FOLDER/*
          # Check if any file in the folder and its subdirectories has been modified
          - $FOLDER_B/**/*
          # Check if any JSON file in the folder has been modified
          - $FOLDER_C/*.json
          # Check if any JSON file in the folder and its subdirectories has been modified
          - $FOLDER_D/**/*.json

However, what if you want to run the job when all the conditions are met? Here is where you may find difficulties. You may find different solutions to this problem.

Here is a solution that may look simpler and correct but in reality it's a wrong approach:

job:
  variables:
    FOLDER_A: "my-folder-A"
    FOLDER_B: "my-folder-B"
    FOLDER_C: "my-folder-C"
    FOLDER_D: "my-folder-D"
    ALL_CONDITIONS_MET: "false"
  script:
    - if [ "$ALL_CONDITIONS_MET" = "true" ]; then echo "Building and pushing the image"; else echo "Conditions not met. Skipping job."; exit 0; fi
  rules:
    # Rule 1: Check if any file in FOLDER_A is changed
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
      changes:
        paths:
          - $FOLDER_A/*
      variables:
        COND_A: "true"

    # Rule 2: Check if any file in FOLDER_B is changed
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
      changes:
        paths:
          - $FOLDER_B/**/*
      variables:
        COND_B

Cloud Native CI/CD with GitLab

From Commit to Production Ready

Enroll now to unlock all content and receive all future updates for free.