HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Trigger a cross project GitLab trigger

Submitted by: @import:stackexchange-devops··
0
Viewed 0 times
crossgitlabprojecttrigger

Problem

I am trying to call a trigger on one GitLab project using a job on another.

Let’s call one A, and the other B. I want a job in A to trigger a job in B.

In A, this is what my .gitlab-ci.yml looks like:

deploy:staging:
  image: alpine
  variables:
    GIT_STRATEGY: none
  script:
    - apk add --no-cache curl
    - curl -X POST -F "token=$CI_JOB_TOKEN" -F "ref=$CI_COMMIT_REF_NAME" https://gitlab.com/api/v4/projects/1234/trigger/pipeline


In B, this is what my .gitlab-ci.yml looks like:

image: google/cloud-sdk

deploy:staging:
  only:
    - triggers
  script:
    - echo "$CI_ENVIRONMENT_SLUG"


However, when A runs, I get the following result from curl:

{"message":{"base":["Reference not found"]}}


When I hardcode the ref to master, I get this message:

{"message":{"base":["No stages / jobs for this pipeline."]}}


How can A be configured, so that the deploy:staging job in B is triggered on master?

Thinking ahead, I would like to add more deployment targets, so it should only trigger the deploy:staging job.

Solution

In your job, I noticed the below curl command, where two things need to be corrected:

-
token=$CI_JOB_TOKEN - this TOKEN should be generated in project B under Settings -> CI/CD -> Pipeline triggers (Add triggers)

-
"ref=$CI_COMMIT_REF_NAME" - this is pointing to a branch with name $CI_COMMIT_REF_NAME on project B and this will only execute if it find a project with that branch name, so if you are trying to trigger it on master branch or any specific branch, you should replace it with something like -F "ref=master" in your curl command

- curl -X POST -F "token=$CI_JOB_TOKEN" -F "ref=$CI_COMMIT_REF_NAME" https://gitlab.com/api/v4/projects/1234/trigger/pipeline


I use the same trigger with few variables to execute one of my job in another project

- "curl -k -X POST -F token=$PROJECT_B_TOKEN -F ref=master -F variables[PROJECT_NAME]=$CI_PROJECT_NAME -F variables[TAG]=$CI_BUILD_REF_NAME -F variables[SOME_VARIABLE_IDENTIFIER]=DevOps -F variables[USER]=$GITLAB_USER_LOGIN https://gitlab.mycompany.com/api/v4/projects/1234/trigger/pipeline"


The person who created in token in project B, needs to be owner in project A to execute this trigger, else it fails with a 404 message.

Code Snippets

- curl -X POST -F "token=$CI_JOB_TOKEN" -F "ref=$CI_COMMIT_REF_NAME" https://gitlab.com/api/v4/projects/1234/trigger/pipeline
- "curl -k -X POST -F token=$PROJECT_B_TOKEN -F ref=master -F variables[PROJECT_NAME]=$CI_PROJECT_NAME -F variables[TAG]=$CI_BUILD_REF_NAME -F variables[SOME_VARIABLE_IDENTIFIER]=DevOps -F variables[USER]=$GITLAB_USER_LOGIN https://gitlab.mycompany.com/api/v4/projects/1234/trigger/pipeline"

Context

StackExchange DevOps Q#5014, answer score: 2

Revisions (0)

No revisions yet.