This guide dives deeper into Groovy scripting for Jenkins pipelines, exploring conditional statements, looping, functions, and data structures. We’ll provide examples and explain how these techniques enhance pipeline control and data management.
Conditional Statements:
if
andelse
: Control the pipeline flow based on conditions.
node {
stage('Build') {
sh 'mvn clean compile'
if (sh(returnStatus: true, script: 'mvn test').exitCode == 0) {
echo 'Tests passed, proceeding...'
} else {
echo 'Tests failed, notifying developers...'
// Send notification (example omitted)
// Optionally, retry the build
}
}
}
Explanation:
- The
if
statement checks if themvn test
command exits with code 0 (success). - If successful, the pipeline continues. Else, it sends a notification and could potentially retry the build (not shown).
switch
: Make decisions based on multiple conditions.
stage('Environment') {
def envName = env.ENVIRONMENT // Get environment from Jenkins parameters
switch (envName) {
case 'dev':
echo 'Deploying to development environment...'
// Deploy to dev server (example omitted)
break
case 'test':
echo 'Deploying to testing environment...'
// Deploy to test server (example omitted)
break
default:
echo "Invalid environment: ${envName}"
error 'Exiting pipeline...'
}
}
Explanation:
- The
switch
statement evaluates theenvName
variable and executes the corresponding code block for “dev” or “test” environments.
Looping:
for
loop: Iterate over a list of items.
stage('Unit Tests') {
def testFiles = ['test/unit/MyClassTest.groovy', 'test/unit/AnotherTest.groovy']
for (file in testFiles) {
sh "groovy ${file}" // Execute each unit test file
}
}
Explanation:
- The
for
loop iterates through thetestFiles
list, executing the Groovy script for each unit test file.
Working with Functions:
Create reusable functions for code modularity.
def notify(message) {
echo "Sending notification: ${message}"
// Implement notification logic (e.g., email, Slack)
}
stage('Build') {
sh 'mvn clean compile'
if (sh(returnStatus: true, script: 'mvn test').exitCode != 0) {
notify('Build failed, unit tests failed!')
}
}
Explanation:
- The
notify
function takes a message and sends a notification (implementation details omitted). - The
Build
stage utilizes thenotify
function for a cleaner script.
Data Structures:
- Lists: Store ordered collections of items.
def buildArtifacts = ['build.jar', 'reports.zip']
stage('Archive Artifacts') {
archiveArtifacts artifacts: buildArtifacts
}
Explanation:
- The
buildArtifacts
list defines files to be archived by Jenkins. - Maps: Store key-value pairs of data.
def config = [
'server' : 'server1.example.com',
'port' : 8080
]
stage('Deploy') {
sh "scp build.jar ${config['server']}:${config['port']}"
}
Explanation:
- The
config
map stores server details used in thescp
command for deployment.
Sample Output:
The output will vary depending on your specific pipeline execution. Here’s an example with successful tests and notification function (implementation details omitted):
Running on Jenkins in container ...
Stage 'Build'
mvn clean compile
Stage 'Unit Tests'
Sending notification: Build failed, unit tests failed!
[Pipeline] End of Pipeline