2

i found the answer: How to get Gitlab merge request description in Gitlab CI?

But there is no answer to the request:

$CI_API_V4_URL/projects/$CI_PROJECT_ID/merge_requests/$CI_MERGE_REQUEST_IID

i added a header:

PRIVATE-TOKEN: $TOKEN

Where $TOKEN - CI_BUILD_TOKEN or CI_JOB_TOKEN, but answer:

HTTPCode: 401

UPD. I created script:

#!/usr/bin.env bash
# -*- coding: utf-8 -*- 

urlBase="${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/merge_requests/${CI_MERGE_REQUEST_IID}
echo "[--] urlBase: ${urlBase}"
echo "[--] key + build"
curl "${urlBase}?private_token=${CI_BUILD_TOKEN}"
echo "[--] key + job"
curl "${urlBase}?private_token=${CI_JOB_TOKEN}"
echo "[--] header + build"
curl --header "PRIVATE-TOKEN: ${CI_BUILD_TOKEN}" "${urlBase}"
echo "[--] header + job"
curl --header "PRIVATE-TOKEN: ${CI_JOB_TOKEN}" "${urlBase}"
echo "[--] header2 + build"
curl --header "Authorization: Bearer ${CI_BUILD_TOKEN}" "${urlBase}"
echo "[--] header2 + job"
curl --header "Authorization: Bearer ${CI_JOB_TOKEN}" "${urlBase}"

but output:

{"message":"401 Unauthorized"}
0

1 Answer 1

7

Assuming you're calling the GitLab API using cURL, you need to pass the API token explicitly. Read the GitLab Documentation carefully, since there are quite a few gotchas.

Credentials in cURL Command

Here are some common ways for passing credentials in a cURL command:

As a parameter:

curl "$CI_API_V4_URL/projects/$CI_PROJECT_ID/merge_requests/$CI_MERGE_REQUEST_IID?private_token=<your_access_token>"

As a header:

curl --header "PRIVATE-TOKEN: <your_access_token>" "$CI_API_V4_URL/projects/$CI_PROJECT_ID/merge_requests/$CI_MERGE_REQUEST_IID"

CI Job Token

The GitLab documentation specifies which API calls can be made with $CI_JOB_TOKEN:

With a few API endpoints you can use a GitLab CI/CD job token to authenticate with the API: Packages, Artifacts, Pipeline Triggers, Release Creation, Terraform Plan.

Note that Merge Request is not in that list, so that won't work.

CI Build Token

According to this issue, $CI_BUILD_TOKEN was deprecated in GitLab 9.x and was renamed to $CI_JOB_TOKEN, so that won't work either.

Personal Access Token

You can authenticate to a GitLab API using Personal Access Tokens, or PATs. First, create your PAT using these instructions. Make sure you select api as the scope. Then, add the token to a GitLab variable following these instructions. Make sure you enable "Mask Variable" so that your token is not exposed in logs. Now, in gitlab-ci.yml, the variable you created will be available as an environment variable.

Sign up to request clarification or add additional context in comments.

1 Comment

Personal Access Token! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.