From inside a Jenkins pipeline, I want to create a merge request on gitlab

def toJson = {
    input ->
def body = [
    private_token: "...",
    source_branch: "...",
    target_branch: "...",
    title: "..."
httpRequest httpMode: 'POST', requestBody: toJson(body), contentType: 'APPLICATION_JSON', url: 'https://my.gitlab.domain/api/v4/projects/1234/merge_requests'

My problem is with the private_token, I don't want to put it in clear in the Jenkinsfile.

I didn't found a way to get it from Jenkins credentials, is there one ?

3 Answers 3


Try something similar to the following:

environment {
  GITLAB_API_TOKEN = credentials('gitlab_api_token').   


  $class: 'com.dabsquared.gitlabjenkins.connection.GitLabApiTokenImpl',
  credentialsId: 'gitlab_api_token',
  variable: 'GITLAB_API_TOKEN'

See https://jenkins.io/doc/pipeline/steps/credentials-binding/ and https://github.com/jenkinsci/gitlab-plugin/issues/536 for more information.


You can do this using the Credential Binding Plugin. Open an existing pipeline job, scroll down to the text area where you enter the pipeline code, and click the Pipeline Syntax link to open the Snippet Generator.

From the Sample Step drop-down, select withCredentials: Bind credentials to variables. Under the Bindings section, select the "Add" button next to Credentials. Add a new credential of kind "Secret text". Enter the API token, give it an easy to remember ID (this is how we reference this secret) and a description.

When the token is added, select it from the Credentials drop-down selection. Enter the variable you want to use to reference the API key. Using your example, I named it private_token. When finished, click the Generate Pipeline Script button to generate a sample withCredentials() function. Using this function, any reference to the API key will be hidden from the user when called as private_token

withCredentials([string(credentialsId: 'Gitlab-API-Key', variable: 'private_token')]) 
    echo("My private token is: ${private_token}")

Screenshot for reference

  • 1
    That is exactly the approach that led me here. Doing that gives: Credentials '366df523-22fd-4b84-9a29-da4b6506fde4' is of type 'GitLab API token' where 'org.jenkinsci.plugins.plaincredentials.StringCredentials' was expected Jan 21, 2022 at 10:31

What worked for me was

  • Create access token in gitlab
  • Create credential in Jenkins as username, password. Use a dummy username & token as the password

Use the below code block

withCredentials([gitUsernamePassword(credentialsId: 'your-jenkins-token-name', 
gitToolName: 'Default')]) {  ... }

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.