Search code examples
jenkinsgroovygitlabgitlab-api

Jenkins credentials - Gitlab API token


I've been searching the whole web for a snippet on how to create GitLab API credential with groovy. and creating Gitlab connection using that API credential for 'Build merge request' purposes, It would be really helpful. Thanks in advance

UPDATE: I found a solution anyway. I created the GitlabAPI creds manually and took its XML and parsed it with jinja2 to make it dynamic. then I've passed it to the Jenkins CLI create creds by xml

cat /tmp/gitlab-credential.xml | \
java -jar {{ cli_jar_location }} \
-s http://{{ jenkins_hostname }}:{{ http_port }} \
create-credentials-by-xml  "SystemCredentialsProvider::SystemContextResolver::jenkins" "(global)"

Solution

  • I encountered similar need to create the gitlab api credential via groovy. Below is the solution I managed to figure out, adapted from https://gist.github.com/iocanel/9de5c976cc0bd5011653

    import jenkins.model.*
    import com.cloudbees.plugins.credentials.*
    import com.cloudbees.plugins.credentials.common.*
    import com.cloudbees.plugins.credentials.domains.*
    import com.cloudbees.plugins.credentials.impl.*
    import com.dabsquared.gitlabjenkins.connection.*
    import hudson.util.Secret
    
    domain = Domain.global()
    store = Jenkins.instance.getExtensionList('com.cloudbees.plugins.credentials.SystemCredentialsProvider')[0].getStore()
    
    token = new Secret("my-token")
    
    gitlabToken = new GitLabApiTokenImpl(
      CredentialsScope.GLOBAL,
      "gitlab-token",
      "token for gitlab",
      token
    )
    
    store.addCredentials(domain, gitlabToken)