Reputation: 21
I have several Jenkins Job running which Deploy's code to application server. These jobs run automatically whenever there is Commit in Github repository configured through Jenkins Plugin in Github and webhook. Jenkins is running on a Windows system.
We have several applications in the repository, represented by a directory containing the code, each of these applications have a corresponding Jenkins Job which deploy's the code to server when the Job is run. Since all the applications are in the same repository, so change in any one of the application creates a Push event and thus trigers all the Jobs.
Suppose there are three Applications App1, App2 and App3 and their corresponding Jobs are J1, J2, J3 and there is a change in App1 and a commit is made in Github repository it causes all the Jobs J1,J2,J3 to trigger and Deploys App1, App2, App3 in server.
It causes unnecessary confusion since App2, App3 do not have any changes in repository but still gets deployed to server. Is there any way that i can trigger specific Jenkins job build based on Directory level Changes/Commits in the Github repository. Can we use any git hooks somehow to achieve this?
Upvotes: 2
Views: 4050
Reputation: 1
I have been spend 4 days to resolve this issue. this is mine that actually works
pipeline {
agent any
environment {
// custom your own environment
}
stages {
stage("Clone Repository") {
steps {
script {
echo "Clone ${DIRECTORY} repository..."
checkout([$class: 'GitSCM', branches: [[name: "${BRANCH}"]],
doGenerateSubmoduleConfigurations: false,
extensions: [[$class: 'SparseCheckoutPaths', sparseCheckoutPaths: [[path: env.DIRECTORY]]]],
submoduleCfg: [],
userRemoteConfigs: [[credentialsId: "${GIT_CREDENTIALS}", url: "${GIT_REPO}"]]])
}
}
}
stage("Check Changes") {
steps {
script {
echo "Check changes ${DIRECTORY}..."
def changes = checkForChanges(env.DIRECTORY)
if (changes) {
echo "Changes detected in ${DIRECTORY}."
env.BUILD_IMAGE_CHANGED = "true"
} else {
currentBuild.result = 'NOT_BUILT'
echo "No changes detected in ${DIRECTORY}. Skipping build."
env.BUILD_IMAGE_CHANGED = "false"
}
}
}
}
stage("Build Image") {
when {
expression { return env.BUILD_IMAGE_CHANGED == "true" }
}
steps {
script {
echo "Building ${DIRECTORY} image..."
sh 'docker build -t $IMAGE -f ${DIRECTORY}/Dockerfile .'
}
}
}
}
}
def checkForChanges(dir) {
def diff = sh(script: "git diff HEAD HEAD~ --name-only | grep ${dir}", returnStatus: true)
return diff == 0
}
Upvotes: 0
Reputation: 2018
For that to happen, You can sparse checkout to a specific directory in the git so that every jenkins job will be mutual to each other.
jenkins job configure -> Source Code Management -> Git -> Additional Behaviours -> Add -> Sparse Checkout paths
This will simply sparse checkout to a sub directory and checks if there are any commits on that directory only. Hope this helps.
Upvotes: 3