Search code examples
gitlab-cigitlab-api

How to call the GitLab API "/projects/:id/trigger/pipeline" and specify the GitLab CI build file?


GitLab allows a job in the .gitlab-ci.yml file to trigger a child pipeline and to specify the build configuration file. For example:

trigger_job:   trigger:
    include:
      - local: path/to/child-pipeline.yml
    strategy: depend

I want to do something similar via the /projects/:id/trigger/pipeline API using curl from the parent GitLab pipeline. I can pass in token=$CI_JOB_TOKEN and ref=$CI_COMMIT_REF_NAME but I don't see a way to pass in the build configuration file. I tried passing in the variable variable[CI_CONFIG_PATH]=child-pipeline.yml but it seems the variable is ignored. Is there a means to specify the build configuration file when using this API?

If you are wondering why I want to call the API, it is because the parent pipeline can only determine at runtime (not when I author the build file) what child pipelines need to run. As an alternative, I could have a job in the parent pipeline generate a build configuration file at runtime and tag it as an artifact. Then have a second job trigger the child pipeline, pointing to the generated build configuration. But it seems more straightforward to have a script that determines what child pipelines need to run, and then trigger them via the API.


Solution

  • I don't think you can change the CI configuration used for the triggered project (at least not just for the trigger), but you can specify variables and configure the project to behave differently depending on the presence or absence of those variables.

    You could consider using include:rules: and condition which configuration(s) are included based on present variables.

    For example, perhaps your .gitlab-ci.yml in the target project looks something like this:

    include:
      - local: path/to/child-pipeline.yml
        rules:
          - if: $MY_SPECIAL_VARIABLE == "1"
      - local: normal_pipeline.yml
        rules:
          - if: $MY_SPECIAL_VARIABLE == null
    

    where "normal_pipeline.yml" is just the regular pipeline definition you want to run when not triggered by your parent pipeline. You could expand this concept to include rule logic for every configuration file you might want to trigger this way.

    If you don't want to change your project CI file in this way, then dynamic child pipelines probably make the most sense. Determining configuration at runtime is precisely the use case for that feature.