Question

How can I get the ID of a parent pipeline that was triggered in GitLab?

Answer and Explanation

To get the ID of a parent pipeline that triggered a child pipeline in GitLab, you can use predefined CI/CD variables. GitLab provides several variables that contain information about the current pipeline and its relationships.

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

1. Using the `CI_PARENT_PIPELINE_ID` Variable:

- GitLab automatically sets the `CI_PARENT_PIPELINE_ID` variable in child pipelines. This variable contains the ID of the pipeline that triggered the current pipeline. If the current pipeline is not a child pipeline, this variable will be empty.

2. Accessing the Variable in Your GitLab CI/CD Configuration:

- You can access this variable in your `.gitlab-ci.yml` file using the standard variable syntax, which is $CI_PARENT_PIPELINE_ID.

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

job_example:
  stage: test
  script:
    - echo "Parent Pipeline ID: $CI_PARENT_PIPELINE_ID"
    - |
      if [ -n "$CI_PARENT_PIPELINE_ID" ]; then
        echo "This is a child pipeline."
      else
        echo "This is not a child pipeline."
      fi

4. Explanation:

- The example above defines a job named job_example that will be executed in the test stage.

- The script first echoes the value of the CI_PARENT_PIPELINE_ID variable. If the pipeline is a child pipeline, this will output the ID of the parent pipeline.

- The script then checks if the CI_PARENT_PIPELINE_ID variable is not empty. If it's not empty, it means the current pipeline is a child pipeline, and it outputs a corresponding message.

5. Important Considerations:

- The `CI_PARENT_PIPELINE_ID` variable is only available in child pipelines. If your pipeline is not triggered by another pipeline, this variable will be empty.

- You can use this ID to interact with the parent pipeline via the GitLab API if needed.

By using the CI_PARENT_PIPELINE_ID variable, you can easily access the ID of the parent pipeline that triggered your current pipeline in GitLab CI/CD.

More questions