Feedback

Chat Icon

Cloud Native CI/CD with GitLab

From Commit to Production Ready

Conditional Jobs and Pipelines
64%

Advanced Strategies for More Complex Conditions

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

  • FOLDER_TO_CHECK_A: Check if any file in the folder has been modified.
  • FOLDER_TO_CHECK_B: Check if any file in the folder and its subdirectories has been modified.
  • FOLDER_TO_CHECK_C: Check if any JSON file in the folder has been modified.
  • FOLDER_TO_CHECK_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_TO_CHECK_A: "my-folder-A"
    FOLDER_TO_CHECK_B: "my-folder-B"
    FOLDER_TO_CHECK_C: "my-folder-C"
    FOLDER_TO_CHECK_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_TO_CHECK/*
          # Check if any file in the folder and its subdirectories has been modified
          - $FOLDER_TO_CHECK_B/**/*
          # Check if any JSON file in the folder has been modified
          - $FOLDER_TO_CHECK_C/*.json
          # Check if any JSON file in the folder and its subdirectories has been modified
          - $FOLDER_TO_CHECK_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. The common point is to set a variable to true when all the conditions are met and use this variable in the if clause. Here is an example:

job:
  variables:
    FOLDER_TO_CHECK_A: "my-folder-A"
    FOLDER_TO_CHECK_B: "my-folder-B"
    FOLDER_TO_CHECK_C: "my-folder-C"
    FOLDER_TO_CHECK_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_TO_CHECK_A is changed
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
      changes:
        paths:
          - $FOLDER_TO_CHECK_A/*
      variables:
        COND_A: "true"

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

Cloud Native CI/CD with GitLab

From Commit to Production Ready

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