Create a new Jenkins pipeline and enable the option "GitHub hook trigger for GITScm polling"
In the pipeline definition, set the SCM as Git and paste the repository URL. The branch should be set as "main"
The path to the script for Jenkinsfile must be set to spring-boot-app/JenkinsFile as this is the place where the Jenkinsfile is stored. Then click on Save to create the pipeline.
JenkinsFile for the CI pipeline
The Jenkinsfile to create the CI pipeline looks like this:
pipeline {
agent {
// Setup a Docker agent to run the Jenkins job
docker {
image 'abhishekf5/maven-abhishek-docker-agent:v1'
args '--user root -v /var/run/docker.sock:/var/run/docker.sock' // mount Docker socket to access the host's Docker daemon
}
}
stages {
stage('Checkout') {
steps {
echo "Cloning the code"
git url:"https://github.com/devops-maestro17/java-cicd-pipeline.git", branch: "main"
}
}
stage('Build and Test') {
steps {
sh 'ls -ltr'
// build the project and create a JAR file
sh 'cd spring-boot-app && mvn clean package'
}
}
stage('Static Code Analysis') {
environment {
SONAR_URL = //URL for SonarQube server
}
steps {
withCredentials([string(credentialsId: 'sonarqube', variable: 'SONAR_AUTH_TOKEN')]) {
sh 'cd spring-boot-app && mvn sonar:sonar -Dsonar.login=$SONAR_AUTH_TOKEN -Dsonar.host.url=${SONAR_URL}'
}
}
}
stage('Build and Push Docker Image') {
environment {
DOCKER_IMAGE = "containerizeops/java-app-cicd:${BUILD_NUMBER}"
REGISTRY_CREDENTIALS = credentials('docker-cred')
}
steps {
script {
sh 'cd spring-boot-app && docker build -t ${DOCKER_IMAGE} .'
def dockerImage = docker.image("${DOCKER_IMAGE}")
docker.withRegistry('https://index.docker.io/v1/', "docker-cred") {
dockerImage.push()
}
}
}
}
stage('Update Deployment File') {
environment {
GIT_REPO_NAME = "java-cicd-pipeline"
GIT_USER_NAME = "devops-maestro17"
}
steps {
withCredentials([string(credentialsId: 'github', variable: 'GITHUB_TOKEN')]) {
sh '''
git config user.email "rajdeep_deogharia@outlook.com"
git config user.name "devops-maestro17"
BUILD_NUMBER=${BUILD_NUMBER}
sed -i "s/replaceImageTag/${BUILD_NUMBER}/g" spring-boot-app-manifests/deployment.yml
git add spring-boot-app-manifests/deployment.yml
git commit -m "Update deployment image to version ${BUILD_NUMBER}"
git push https://${GITHUB_TOKEN}@github.com/${GIT_USER_NAME}/${GIT_REPO_NAME} HEAD:main
'''
}
}
}
}
}