0
0
JenkinsHow-ToBeginner · 3 min read

How to Use Groovy Script in Jenkins for Automation

You can use Groovy scripts in Jenkins by adding them in the Pipeline script section or running them via the Script Console. Groovy lets you automate Jenkins tasks, configure jobs, and create complex pipelines with simple code.
📐

Syntax

Groovy scripts in Jenkins are usually written inside a pipeline block or run as standalone scripts in the Script Console. The basic syntax includes defining stages and steps using Groovy code.

  • pipeline: Defines the Jenkins pipeline.
  • agent: Specifies where the pipeline runs.
  • stages: Contains different build stages.
  • steps: Commands executed in each stage.
groovy
pipeline {
    agent any
    stages {
        stage('Example') {
            steps {
                echo 'Hello from Groovy script in Jenkins'
            }
        }
    }
}
💻

Example

This example shows a simple Jenkins pipeline using Groovy script that prints a message to the console. It demonstrates how to define a pipeline, a stage, and a step with Groovy syntax.

groovy
pipeline {
    agent any
    stages {
        stage('Greeting') {
            steps {
                echo 'Hello, Jenkins with Groovy!'
            }
        }
    }
}
Output
[Pipeline] echo Hello, Jenkins with Groovy! [Pipeline] End of Pipeline
⚠️

Common Pitfalls

Common mistakes when using Groovy scripts in Jenkins include:

  • Not using pipeline syntax in declarative pipelines.
  • Trying to run Groovy scripts with Jenkins-specific commands outside Jenkins environment.
  • Forgetting to wrap shell commands inside sh or bat steps.
  • Using incorrect indentation or missing braces causing syntax errors.
groovy
/* Wrong: Missing pipeline block */
echo 'This will fail'

/* Right: Proper pipeline syntax */
pipeline {
    agent any
    stages {
        stage('Correct') {
            steps {
                echo 'This works'
            }
        }
    }
}
📊

Quick Reference

ConceptDescriptionExample
pipelineDefines the Jenkins pipelinepipeline { ... }
agentSpecifies where to run the pipelineagent any
stageDefines a build stagestage('Build') { ... }
stepsCommands to run in a stagesteps { echo 'Hi' }
echoPrints message to consoleecho 'Hello'
shRuns shell commandssh 'ls -la'

Key Takeaways

Use Groovy scripts inside Jenkins Pipeline blocks to automate builds.
Always wrap commands inside stages and steps for proper execution.
Run Groovy scripts safely in Jenkins Script Console for admin tasks.
Watch out for syntax errors like missing braces or wrong indentation.
Use the Quick Reference table to remember common pipeline keywords.