Question

How can I get the ID of the parent pipeline when triggering a pipeline in GitLab?

Answer and Explanation

When triggering a pipeline in GitLab, accessing the parent pipeline's ID can be achieved through predefined CI/CD variables. GitLab provides several variables that contain information about the current pipeline and its relationships.

Here's how you can get the parent pipeline ID:

1. Using the `CI_PIPELINE_SOURCE` Variable:

- The `CI_PIPELINE_SOURCE` variable indicates how the pipeline was triggered. If the pipeline was triggered by another pipeline, this variable will be set to pipeline.

2. Using the `CI_PARENT_PIPELINE_ID` Variable:

- The `CI_PARENT_PIPELINE_ID` variable contains the ID of the parent pipeline that triggered the current pipeline. This variable is available when the `CI_PIPELINE_SOURCE` is pipeline.

3. Example Usage in `.gitlab-ci.yml`:

job_example:
  stage: test
  script:
    - |
      if [[ "$CI_PIPELINE_SOURCE" == "pipeline" ]]; then
        echo "Parent Pipeline ID: $CI_PARENT_PIPELINE_ID"
      else
        echo "This pipeline was not triggered by another pipeline."
      fi

4. Explanation:

- The script checks if the pipeline was triggered by another pipeline using the `CI_PIPELINE_SOURCE` variable.

- If it was, it prints the parent pipeline ID using the `CI_PARENT_PIPELINE_ID` variable.

5. Important Considerations:

- The `CI_PARENT_PIPELINE_ID` variable will only be available if the current pipeline was triggered by another pipeline. If the pipeline was triggered by a commit, merge request, or schedule, this variable will not be set.

- Ensure that your GitLab version supports these variables. They are generally available in recent versions of GitLab.

By using these variables, you can effectively retrieve the parent pipeline ID when triggering pipelines in GitLab, enabling you to create more complex and interconnected CI/CD workflows.

More questions