Simple Jenkins pipeline for running and automating Gradle tasks
Jenkins is a great tool for automating running different Gradle tasks. In this post, you'll find a very simple starting point for creating a Jenkins pipeline that can run different Gradle tasks.
Table of contents
Jenkins is a popular and widely-used open-source tool for Continuous Integration and Continuous Delivery/Deployment (CI/CD) automation. Jenkins is easy to install and configure, and comes with a web-based graphical user interface (GUI) that makes it easy to manage and use.
Create a new Jenkins job
Before you can create a new pipeline for Jenkins, you will need to have a job for it. To create a Jenkins pipeline job, you can follow these steps:
-
Log in to your Jenkins server and navigate to the Jenkins dashboard.
-
Click on “New Item” from the left-hand menu.
-
Enter a name for your pipeline job and select “Pipeline” from the list of job types.
-
Click “OK” to create your pipeline job.
Install necessary plugins
To run our example pipeline from a Jenkinsfile, you will need a couple of Jenkins plugins. Jenkins plugins can be installed by navigating from Jenkins Dashboard to -> “Manage Jenkins” -> “Manage plugins”.
- Pipeline: Declarative will allow us to run Jenkins pipelines from Jenkinsfile groovy-scripts.
- Pipeline: Stage View will generate a nice-looking UI with each build step and stage included.
- JUnit allows us to access JUnit test reports from Jenkins UI.
Configuring the pipeline
You can add our example pipeline script directly from your job configuration page to a textarea, or you can add a new script file directly to your source code repository. Jenkins pipelines are usually named as Jenkinsfile
to the root of your repository without any file extensions.
pipeline {
agent any
stages {
stage('Clean') {
steps {
sh './gradlew clean'
}
}
stage('Test') {
steps {
sh './gradlew test'
}
post {
always {
junit '**/build/test-results/test/TEST-*.xml'
}
}
}
stage('Build') {
steps {
sh './gradlew build -x test'
}
}
stage('Deploy') {
steps {
sh './gradlew deploy'
}
}
}
post {
failure {
echo 'Pipeline failed!'
}
}
}
This pipeline script includes the following stages with their corresponding build steps inside:
- Clean
You want to make sure that you are working with a clean build before running new builds on top of existing ones.
- Test
Next, we’ll run our tests, such as unit tests and integration tests. Whether our tests are failing or not, we’ll always generate a complete test report using the JUnit Jenkins plugin.
- Build
If none of the tests were broken, we are ready to build our application.
- Deploy
Once our build is successful, we’ll use the generated artifacts to deploy to our specified environment.
- Post-build actions
In post-build actions, we could do things like automated emails or Slack messages to notify of succeeding or failing pipeline runs.