I've created Jenkins Pipeline Job, activated "Build when a change is pushed to BitBucket" trigger. I've also specified branches to build. But pipeline is triggered by all branch changes. Also I've created Freestyle job with similar configuration and trigger works correctly. General Webhook didn't help, it triggered all jobs in Jenkins.
2 Answers
While I don't know Bitbucket-specific solution, when it comes to triggering Jenkins builds, I prefer using a simple post-receive Git hook.
In Jenkins select Trigger this build remotely
(or something similar, it's usually the very first option in Build triggers
section), then set up the post-recevie hook to something like:
#!/bin/bash
username=user
token=1234567890abcdefgh
echo "Executing hook"
while read oldrev newrev refname
do
branch_received=$(git rev-parse --symbolic --abbrev-ref $refname)
echo " /==============================="
echo " | PUSH RECEIVED"
echo " | Old revision: $oldrev"
echo " | New revision: $newrev"
echo " | Reference : $refname"
echo " | Branch name : $branch_received"
echo " \=============================="
curl -X POST -d "BRANCH=$branch_received" http://$username:$token@jenkins/job/job_name/buildWithParameters?token=$token
res=$?
if test "$res" != "0"; then
echo "The curl command failed with: $res"
fi
done
exit 0
Of course, the above runs for every branch and passes the branch name as a parameter to the job. In your case, since you have different job for every branch, you would call different URL depending on what branch was pushed and probably use build
rather than buildWithParameters
endpoint.
I recommend using the Bitbucket Branch Source Plugin which gives much better control over push build triggers than the default Pipeline job type.
The problem with your current setup is that the "branch to build" setting only configures the branch of the repository that Jenkins checks out, not necessarily which branches will trigger a build.
-
Do you propose using 'Bitbucket Team/Project' type of project? I only needed one one job for single branch at a tme. May 8, 2019 at 2:44