Groovy script
Groovy script is a scripting language that is based on the Java programming language. It is designed to enhance and simplify Java code by providing dynamic typing, concise syntax, and powerful scripting capabilities. Groovy is often used as a scripting language for automation, configuration, and scripting tasks in various contexts, including Jenkins, where it is commonly used for writing scripts to interact with the Jenkins API and perform administrative tasks.
Jenkins
Jenkins is an open-source automation server that facilitates the continuous integration and continuous delivery (CI/CD) of software projects. It is a widely used tool in the software development industry to automate various stages of the software development lifecycle, including building, testing, and deploying applications.
Jenkins Pipeline
Jenkins Pipeline is a powerful feature in Jenkins that allows you to define and automate complex, multi-stage CI/CD workflows as code. It provides a way to create, manage, and visualize pipelines, enabling you to define your software delivery process in a more structured and reusable manner.
Usage of Groovy Script in Jenkins
Groovy script can be used in Jenkins file to build more complex pipelines. Jenkins file is written and submitted to the project source repository. When a commit arrives, Jenkins pipeline is triggered, and all the stages in pipeline are executed according to the algorithm written in Jenkins file.
Groovy script can be directly written in any script block.
pipeline { agent any
stages {
stage('Build') {
steps {
echo "This is Build step."
}
}
stage('Test') {
steps {
echo "This is Test step."
}
}
stage('Deploy') {
steps {
script{
echo "This is Deploy step."
def branchName = "${env.BRANCH_NAME}" if(branchName == "master"){
println("Deploying to Prod.")
}
else if(branchName == "test"){
println("Deploying to Test.") } } }
}
}
}
Groovy methods can be defined outside of the pipeline and called within a script block in pipeline.
pipeline { agent any
stages {
stage('Build') {
steps {
echo "This is Build step."
}
}
stage('Test') {
steps {
echo "This is Test step."
}
}
stage('Deploy') {
steps {
script{
echo "This is Deploy step." def changedFiles = [];
// Calling getChangedFiles method...
changedFiles = getChangedFiles(); if(changedFiles.size>0){
println(changedFiles)
}
else{
println("No changed file.")
}
def branchName = "${env.BRANCH_NAME}" // Calling deploy method...
deploy(branchName); } }
}
}
}def void deploy(String branchName){ if(branchName == "master"){
println("Deploying to Prod.")
}
else if(branchName == "test"){
println("Deploying to Test.") }
}def getChangedFiles(){ def changes = []
def changeLogSets = currentBuild.changeSets
def filePath = "" for (int i = 0; i < changeLogSets.size(); i++) {
def entries = changeLogSets[i].items for (int j = 0; j < entries.length; j++) {
def entry = entries[j]
def files = new ArrayList(entry.affectedFiles) for (int k = 0; k < files.size(); k++) { def file = files[k]
filePath = "${file.path}" if("${file.editType.name}"!="delete"){
changes.add(filePath); } } } } changes.unique();
changes.sort();
return changes;}
If you’re looking for a comprehensive guide on using Groovy scripts for Jenkins administration, here’s an overview of some common tasks and operations you can perform:
- Retrieve Jenkins Version:
import jenkins.model.Jenkins
def jenkins = Jenkins.getInstance()
def jenkinsVersion = Jenkins.VERSION
println "Jenkins Version: $jenkinsVersion"
- Retrieve Jenkins URL:
import jenkins.model.Jenkins
def jenkinsURL = Jenkins.instance.rootUrl
println "Jenkins URL: $jenkinsURL"
- Get All Jobs in Jenkins:
import jenkins.model.Jenkins
def jobs = Jenkins.instance.getAllItems()
jobs.each { job ->
println "Job Name: ${job.fullName}"
println "Job URL: ${job.absoluteUrl}"
println "Job Description: ${job.description}"
println "Job Last Build Number: ${job.lastBuild?.number}"
println "-------------------------------"
}
- Create a New Jenkins Job:
import jenkins.model.Jenkins
import hudson.model.FreeStyleProject
def jenkins = Jenkins.getInstance()
def newJobName = "NewJob"
def newJob = new FreeStyleProject(jenkins, newJobName)
newJob.save()
println "New job created: $newJobName"
- Delete a Jenkins Job:
import jenkins.model.Jenkins
def jenkins = Jenkins.getInstance()
def jobNameToDelete = "JobToDelete"
def jobToDelete = jenkins.getItemByFullName(jobNameToDelete)
if (jobToDelete) {
jobToDelete.delete()
println "Job deleted: $jobNameToDelete"
} else {
println "Job not found: $jobNameToDelete"
}
- Disable a Jenkins Job:
import jenkins.model.Jenkins
def jenkins = Jenkins.getInstance()
def jobNameToDisable = "JobToDisable"
def jobToDisable = jenkins.getItemByFullName(jobNameToDisable)
if (jobToDisable) {
jobToDisable.makeDisabled(true)
println "Job disabled: $jobNameToDisable"
} else {
println "Job not found: $jobNameToDisable"
}
- Enable a Jenkins Job:
import jenkins.model.Jenkins
def jenkins = Jenkins.getInstance()
def jobNameToEnable = "JobToEnable"
def jobToEnable = jenkins.getItemByFullName(jobNameToEnable)
if (jobToEnable) {
jobToEnable.makeDisabled(false)
println "Job enabled: $jobNameToEnable"
} else {
println "Job not found: $jobNameToEnable"
}
- Grant Jenkins Job Permissions:
import jenkins.model.Jenkins
import hudson.model.Item
import hudson.security.AuthorizationStrategy
def jenkins = Jenkins.getInstance()
def jobName = "JobName"
def username = "username"
def permission = Item.BUILD // Example permission, you can use other permissions as needed
def job = jenkins.getItemByFullName(jobName)
def acl = jenkins.getAuthorizationStrategy().getACL()
acl.add(jenkins.getAuthentication().createAccount(username), permission)
jenkins.setAuthorizationStrategy(new AuthorizationStrategy.Unsecured())
jenkins.save()
println "Permission granted to user $username for job $jobName"
These examples cover a range of tasks, from retrieving Jenkins information to creating, deleting, and managing jobs. Keep in mind that depending on your Jenkins configuration and security setup, you might need appropriate permissions to execute these operations
Hope you like this blog….
- Deployment of vault HA using MySQL - September 18, 2024
- Sending slack notification via pipeline job - August 25, 2024
- SonarQube integration with Jenkins - August 24, 2024