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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Jenkins Pipeline Groovy script - Part 2 Add a User to a Gitlab Group
  • 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

Trending

  • Unlocking Data with Language: Real-World Applications of Text-to-SQL Interfaces
  • How Clojure Shapes Teams and Products
  • Java's Quiet Revolution: Thriving in the Serverless Kubernetes Era
  • Scalability 101: How to Build, Measure, and Improve 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 user avatar
Kalaiyarasi Durairaj
·
Jul. 28, 20 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
25.0K Views

Join the DZone community and get the full member experience.

Join For Free

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

  • Jenkins Pipeline Groovy script - Part 2 Add a User to a Gitlab Group
  • 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

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!