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 ?


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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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