gitlabgitlab-cigitlab-api

Gitlab: trigger manual action via API


I have a GitLab-CI pipeline stage that looks like this:

test:
  stage: test
  script:
    - echo test
  when: manual

I need to trigger this action via a GitLab API request. I've tried these solutions but they do not seem to work.

curl --request POST \
  --form token=<trigger-token> \
  --form ref=<branch-name> \
https://gitlab.example.com/api/v4/projects/1/trigger/pipeline

curl --request POST \
  --header PRIVATE-TOKEN <private-token> \
https://gitlab.example.com/api/v4/projects/1/jobs/1/play

I don't receive any error message. However, if I pipe the curl-request output to jq, I get the following output:

[...]
      "started_at": null,
      "finished_at": null,
      "committed_at": null,
      "duration": null,
      "coverage": null,
      "detailed_status": {
        "icon": "status_manual",
        "text": "blocked",
        "label": "waiting for manual action",
        "group": "manual",
        "tooltip": "manual action"
[...]

These are the admin logs, but even if the Pipeline is authorized, the job is not triggered.

{"severity":"INFO","time":"2020-11-05T15:57:51.989Z","correlation_id":"z7ATZBEHCB2","message":"Pipeline authorized","project_id":148,"user_id":12}

Solution

  • The API call you’re using is to trigger the step, not to start it manually. If you change your job definition to accept triggers or manual actions, then your current API call would work. We can do this with the rules keyword:

    test:
      stage: test
      script:
        - echo test
      when: manual
      rules:
        - if: "$CI_PIPELINE_SOURCE == 'trigger'"
          when: always
    

    What this does is set the default to manual so it can still be started in the UI, but also check the $CI_PIPELINE_SOURCE predefined variable to see if the pipeline was triggered. If so, it will always run.

    You can see the docs for the rules keyword here: https://docs.gitlab.com/ee/ci/yaml/#rules and all of the predefined variables here: https://docs.gitlab.com/ee/ci/variables/predefined_variables.html