DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Streamlining Your Workflow With the Jenkins HTTP Request Plugin: A Guide to Replacing CURL in Scripts
  • Mastering Shift-Left: The Ultimate Guide to Input Validation in Jenkins Pipelines
  • Jenkins Pipelines With Centralized Error Codes and Fail-Fast
  • CI/CD Pipelines for Kubernetes Using GitLab CI

Trending

  • Moving 900+ GB of Prometheus Without a Cutover Weekend
  • Why Vulnerability Management Fails Without Reliable Asset Data
  • When RabbitMQ Accepts a Message but Does Not Route It to a Queue
  • To Switch, or Not to Switch the AI Model

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Testing, Deployment, and Maintenance
  3. DevOps and CI/CD
  4. Jenkins Pipeline Groovy Script - Part 1: Creating Gitlab Group

Jenkins Pipeline Groovy Script - Part 1: Creating Gitlab Group

Discussing the simple groovy functionality along with Jenkinsfile pipeline script on how to automatically create new gitlab group or subgroup under parent group.

By 
Kalaiyarasi Durairaj
·
Jul. 28, 20 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
25.5K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

In this article, I am discussing a simple groovy functionality along with Jenkinsfile pipeline script on how to automatically create a new GitLab group or subgroup under the parent group.  In DevOps Continuous Integration(CI) and Continuous Delivery(CD), managing projects in git level is very much important and useful for version control.  These projects are organized under a specific groups to have a disciplined structure in order to handle the application deployment well via DevOps.

What Is Jenkins Groovy?

Groovy is  an object-oriented programming language like Java and has Domain Specific Language(DSL) features. Jenkins provides pipeline capabilities along with groovy DSL features for Continuous Integration(CI). So how to use Jenkins pipeline groovy script, use load keyword in Jenkinsfile to create constructor for groovy class. Using constructor or class object of that Groovy class, functions can be inherited and values are returned. In order to use Jenkins Pipeling Groovy script, in Jenkins CI server Pipeline Groovy Plugin should be installed as prerequisite.

Below is an example Jenkins pipeline script to call groovy class functions.

pipeline{
    node('slave') {
        classObject = load 'example.groovy'
        clssObject.function()
    }
}

Gitlab Restful API

Let's see what is Gitlab group and its purpose. Gitlab groups are predominantly used as a common place where all project related information is stored under specific group or subgroups.  A group may have multiple subgroups under parent group, but can have only one immediate parent group. It is depicted as below

  • Parent Group
    • subgroup 1 
    • subgroup 2
      • subgroup 2.1
      • subgroup 2.2

Gitlab offers its functionality as Restful API, that can be leveraged via curl command. In this post  Gitlab Restful APIs for group has been used along with groovy script to create group.

Create Gitlab Group Using Groovy

So how to create gitab group by consuming Gitlab Restful API in Groovy script. Let's create groovy class as below with name gitlabGroup.groovy.

What is this groovy class does:

  1.  Checks for parent group is present or not under which subgroup will be created
  2.  Search for subgroup existence, if not creates subgroup

Thus to create new group, parent group is mandatory under which new given group will be created as subgroup.

Groovy
 




x
74


 
1
import groovy.transform.Field
2
@Field grpfullpath
3
@Field groupName
4
@Field gitlabUrl
5
@Field gitlabToken
6

          
7
@NonCPS
8
def jsonParseData(jsonObj) {
9
    def slurObj=new groovy.json.JsonSlurper().parseText(jsonObj)
10
    return slurObj
11
}
12
// create gitlab group if not present already
13
def createGitLabGroup(gitlabToken, gitlabUrl, parentGroupId, groupName){
14
 stage('Create GitLab group'){
15
   script{
16
     def parentGroupId
17
     def groupName
18
     grpId=getSubGroupDetails(parentGroupId, groupName)
19
     if (grpId.equals(null)){     
20
     def subgrpCreate= sh script: """curl -X POST -H "PRIVATE-TOKEN: ${gitlabToken}" -H 'Content-Type: application/json' \
21
                 ${gitlabUrl}/groups \
22
                -d '{ "web_url":"${gitlabUrl}${grpfullpath}",
23
                      "name":"${groupName}", 
24
                      "path":"${groupName}", 
25
                      "description":"${groupName}", 
26
                      "visibility":"private", 
27
                      "request_access_enabled":"false",
28
                      "parent_id":${parentGroupId}}'""", returnStdout: true
29
      return jsonParseData(subgrpCreate).id
30
     }
31
     else{
32
        return grpId
33
     }
34
   }
35
  }
36
}
37
// get parent gitlab group information under subgroup will be created
38
def getParentGroupObject(){
39
  stage('Get Parent Details'){
40
        script{
41
          def groupdDetails=sh script: """curl --request GET --header "PRIVATE-TOKEN: ${gitlabToken}" ${gitlabUrl}groups/${gitlabGroupId}""", returnStdout: true
42
          return jsonParseData(groupdDetails)
43
        }
44
   }
45
}
46
// search gitlab group already exist or not
47
def getGitGroupObject(gitParentId){
48
 stage('Git Group Object'){
49
    script{
50
        def grpObj=sh script: """curl --request GET --header "PRIVATE-TOKEN: ${gitlabToken}" ${gitlabUrl}groups/${parentGroupId}/subgroups?search=${groupName}""", returnStdout: true
51
        return jsonParseData(grpObj)
52
        }
53
   }
54
 }
55

          
56
def getSubGroupDetails(parentGroupId, groupName){
57
    if (getParentGroupObject()==~/(.*)404(.*)/){
58
        println("group not found")
59
    }
60
    else{
61
        grpfullpath=getParentGroupObject().full_path+"/"+groupName
62
        def gitgrpdetails=getGitGroupObject(parentGroupId)
63
        def grpId=0
64
         for (i=0; i<gitgrpdetails.size(); i++){
65
          if ((gitgrpdetails.full_path[i]).equals(grpfullpath)){              
66
                   grpId=gitgrpdetails.id[i]
67
                   return grpId
68
          }
69
       }
70
    }
71
}
72

          
73
return this
74

          


Once after creating the above groovy class, use load constructor in Jenkins Pipeline script to call createGitlabGroup() by providing Gitlab  information such as gitlab token,  gitlab URL , parent group(Id) and group name as input arguments.

 pipeline{
    node('slave') {
        gitlabObj = load 'gitlabGroup.groovy'
        gitlabObj.createGitlabGroup(gitlabToken, gitlabURL, parentGroupId, groupName)
    }

Summary

Groovy provides more flexible and customized functionality that can be used widely for automation along with Jenkins CI server pipeline script. In Part 1,  we have seen how groovy script has been used to create Gitlab group automatically using Jenkinsfile. In Part 2, I will be explaining about how to add list of users to Gitlab group and grant them permission.  

Groovy (programming language) GitLab Jenkins (software) Pipeline (software)

Opinions expressed by DZone contributors are their own.

Related

  • Streamlining Your Workflow With the Jenkins HTTP Request Plugin: A Guide to Replacing CURL in Scripts
  • Mastering Shift-Left: The Ultimate Guide to Input Validation in Jenkins Pipelines
  • Jenkins Pipelines With Centralized Error Codes and Fail-Fast
  • CI/CD Pipelines for Kubernetes Using GitLab CI

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook