Triggers, webhooks and multibranch

Polling, a push hook with an API token, and one job per branch.

Intermediate14 min · lesson 7 of 15
Lesson files
The scripts, test data and local test servers this lesson uses, exactly as they ran on the lab machine (19 files, 7 KB): triggers.tar.gz. The lab VM shares no folders with your computer, so fetch them inside the VM: cd ~/lab && curl -fsSLO https://secopslog.com/lab-files/ci-jenkins/triggers.tar.gz && tar -xzf triggers.tar.gz, which creates ~/lab/triggers/. SHA-256: ffd39da4bc093ffaad30d14833b7b774617e62eddbd272572a6e31f0ef2c73d0

CI that someone has to remember to start isn't CI. Builds should start from the push itself. But if ten teams poll a Git server every minute, that's a lot of useless traffic, and if a webhook endpoint accepts anonymous calls, anyone can start your builds. This lesson runs the three common ways to start a build, in order from simplest to most useful: polling, a push hook, and one job per branch.

Polling

A trigger declared in a Jenkinsfile needs one build to run before it takes effect, for the same reason as parameters: Jenkins has to read the file to learn about it. This job polls every minute, which is fine for a lab and too often for production:

app/Jenkinsfile
pipeline {
agent { label 'linux' }
triggers { pollSCM('* * * * *') }
stages {
stage('Test') { steps { echo 'polled build' } }
}
}
ubuntu@secopslog-cicd:~/lab/triggers · Jenkins 2.580.2
$ ./up.sh
agent lab-agent: online Jenkins 2.580.2 is up on http://127.0.0.1:8080
$ ./seed.sh app app/ && ./newjob.sh polled app
pushed app: 0338637 first commit job polled reads Jenkinsfile from git://git/app.git
$ ./run-job.sh polled | tail -1
build #1 result: SUCCESS
$ echo change >> app/README && ./commit.sh app/ "add readme"
pushed: 88b38a0 add readme
$ for i in $(seq 100); do n=$(./jk.sh /job/polled/lastBuild/api/json | jq .number); [ "$n" -ge 2 ] && break; sleep 2; done; ./jk.sh /job/polled/lastBuild/api/json | jq -r "\"#\(.number) \(.actions[0].causes[0].shortDescription)\""
#2 Started by an SCM change

Within about a minute, a new build appeared, with the cause Started by an SCM change. SCM means source code management, here Git, which is also why the trigger is called pollSCM. Nobody told Jenkins about the push. It asked Git and found a new commit. For a cron schedule, you'd use cron('H 2 * * *') the same way. The H hashes the job name to a stable offset, so a hundred nightly jobs don't all start at the same moment. This lab doesn't wait for a nightly run, but scheduling goes through the same engine.

A push hook with an API token

Polling means a delay and traffic even when nothing changed. A hook reverses the direction: the Git server tells Jenkins as soon as a push arrives. Since it's a remote call that starts builds, it must authenticate. Without credentials, Jenkins refuses:

ubuntu@secopslog-cicd:~/lab/triggers · Jenkins 2.580.2
$ curl -fsS -o /dev/null -X POST http://127.0.0.1:8080/job/polled/build
curl: (22) The requested URL returned error: 403
$ ./jk.sh /me/descriptorByName/jenkins.security.ApiTokenProperty/generateNewToken -X POST --data newTokenName=git-hook | jq -r .data.tokenValue > .hook-token; wc -c < .hook-token
35
$ ./seed.sh hooked app/ && ./newjob.sh hooked hooked
pushed hooked: 744ca5f first commit job hooked reads Jenkinsfile from git://git/hooked.git

The token step created an API token and saved it to a file, and the only thing printed is its length. API tokens are the right credential here: they're separate from the password, need no crumb, can be revoked by name, and show up as a named token in the user's settings. In production, make a dedicated user with only Job/Build on the jobs it needs, rather than using admin as this lab does.

Our Git server is plain Git, so the hook is a small script. GitHub and GitLab send webhooks instead. Their Jenkins plugins can verify each webhook with a shared secret, but only if you configure one; without it, the endpoint accepts unsigned calls:

post-receive
#!/bin/sh
# Git server hook: asks Jenkins to build after every push. HOOK_AUTH is base64 of user:api-token.
. /srv/git/hook.env
wget -q -O /dev/null --post-data= --header="Authorization: Basic $HOOK_AUTH" http://controller:8080/job/hooked/build \
&& echo "jenkins: build requested"
ubuntu@secopslog-cicd:~/lab/triggers · Jenkins 2.580.2
$ set -e; printf "HOOK_AUTH=%s\n" "$(printf "admin:%s" "$(cat .hook-token)" | base64 -w0)" > hook.env; docker compose cp hook.env git:/srv/git/hook.env 2>/dev/null; docker compose cp post-receive git:/srv/git/hooked.git/hooks/post-receive 2>/dev/null; docker compose exec -T git chmod 755 /srv/git/hooked.git/hooks/post-receive; rm hook.env .hook-token; echo hook installed
hook installed
$ echo more >> app/README; ./commit.sh app/ "second commit" 2>&1
remote: jenkins: build requested pushed: f2469f5 second commit
$ for i in $(seq 40); do r=$(./jk.sh "/job/hooked/api/json" | jq -r ".lastBuild.number // 0"); [ "$r" -ge 1 ] && break; sleep 1; done; sleep 2; ./jk.sh /job/hooked/lastBuild/api/json | jq -r "\"#\(.number) \(.actions[0].causes[0].shortDescription)\""
#1 Started by user admin

remote: jenkins: build requested is the hook's output, relayed by Git to the person pushing, and the build followed within seconds. The cause reads Started by user admin because the token belongs to admin. That audit trail is another reason for a dedicated user: Started by user git-hook tells you more.

Multibranch: one job per branch

So far each job follows one branch. A multibranch pipeline scans a repository and creates a job for every branch that has a Jenkinsfile, and removes it when the branch goes away. It also makes the branch condition available:

app2/Jenkinsfile
pipeline {
agent { label 'linux' }
stages {
stage('Test') { steps { echo "testing $BRANCH_NAME" } }
stage('Deploy') {
when { branch 'main' }
steps { echo 'deploying' }
}
}
}

The job itself is defined in XML, sent to the same createItem endpoint as before. Its important lines name the repository, discover its branches, and read Jenkinsfile from each one:

multibranch.xml
<org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject plugin="workflow-multibranch">
<sources class="jenkins.branch.MultiBranchProject$BranchSourceList" plugin="branch-api">
<data>
<jenkins.branch.BranchSource>
<source class="jenkins.plugins.git.GitSCMSource" plugin="git">
<id>app2</id>
<remote>git://git/app2.git</remote>
<traits><jenkins.plugins.git.traits.BranchDiscoveryTrait/></traits>
</source>
</jenkins.branch.BranchSource>
</data>
<owner class="org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject" reference="../.."/>
</sources>
<factory class="org.jenkinsci.plugins.workflow.multibranch.WorkflowBranchProjectFactory">
<owner class="org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject" reference="../.."/>
<scriptPath>Jenkinsfile</scriptPath>
</factory>
</org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject>
ubuntu@secopslog-cicd:~/lab/triggers · Jenkins 2.580.2
$ ./seed.sh app2 app2/ && git -C app2 checkout -q -b feature/login && git -C app2 push -q -u origin feature/login && echo two branches pushed
pushed app2: c7e2072 first commit two branches pushed
$ ./jk.sh "/createItem?name=app2" -X POST -H "Content-Type: application/xml" --data-binary @multibranch.xml; ./jk.sh /job/app2/build -X POST; for i in $(seq 60); do n=$(./jk.sh "/job/app2/api/json?tree=jobs[name,lastBuild[result]]" | jq "[.jobs[].lastBuild.result // empty] | length"); [ "$n" = 2 ] && break; sleep 2; done; ./jk.sh "/job/app2/api/json?tree=jobs[name,lastBuild[result]]" | jq -r ".jobs[] | \"\(.name) \(.lastBuild.result)\""
feature%2Flogin SUCCESS main SUCCESS
$ ./jk.sh /job/app2/job/main/lastBuild/consoleText | grep -E "^(testing|deploying|Stage .*skipped|Finished)"
testing main deploying Finished: SUCCESS
$ ./jk.sh /job/app2/job/feature%252Flogin/lastBuild/consoleText | grep -E "^(testing|deploying|Stage .*skipped|Finished)"
testing feature/login Stage "Deploy" skipped due to when conditional Finished: SUCCESS
$ ./down.sh
lab stopped and its data removed

One scan produced two jobs and built both. The Jenkinsfile is the same, but main deployed and feature/login skipped that stage. Jenkins encodes the slash in the branch name as %2F, which you'll see in job URLs (and twice over in the REST path above).

Watch out
Multibranch means Jenkins runs whatever Jenkinsfile a branch contains. Anyone who can push a branch can change what runs on your agents and which credentials it asks for, on the first build. Restrict who can push, keep untrusted branches on separate agents and folders with no production credentials, and don't let when { branch 'main' } be your only control. It sits in the same file an attacker would edit. Pull requests from forks are handled by a separate setting: the GitHub and Bitbucket branch sources have a trust strategy, and by default a fork's pull request builds with the target branch's Jenkinsfile, not the fork's. Keep that default.

Hands-on

In a fresh lab, repeat the multibranch steps and add a third branch, fix/typo. Run ./jk.sh /job/app2/build -X POST to scan again, then list the jobs with the mb-create query. Delete the branch with git -C app2 push origin --delete fix/typo, scan again and see what Jenkins does with its job. Finish with ./down.sh.

What you should see: after the scan with fix/typo pushed, three branch jobs (feature%2Flogin, fix%2Ftypo, main) have each built once. After you delete the branch and scan again, only feature%2Flogin and main remain. With no orphaned-item strategy configured, the default applies: a job whose branch is gone is removed at the next scan, along with its build history. Set orphanedItemStrategy to keep some history if you need it for audits.

Remember

Prefer a push hook, authenticated with a dedicated user's API token, and keep slow polling as a safety net for missed hooks. With multibranch, everyone who can push a branch can edit what your pipeline runs.

Quick check
01You add triggers { pollSCM('H/5 * * * *') } to a Jenkinsfile on a new job and push. No build starts, even after an hour of commits. Why?
Incorrect — H is a valid Jenkins extension to cron syntax.
Correct — Start it once by hand. After that, the trigger is registered on the job.
Incorrect — Polling is the option that needs nothing from the Git server.
Incorrect — It works on an ordinary Pipeline job, as in the lab.
02What is the point of H in cron('H 2 * * *')?
Incorrect — The 2 is the hour. H is in the minute field here.
Incorrect — Scheduling does not wait for idleness. The minute is decided beforehand.
Incorrect — A step value would do that. H picks a single minute.
Correct — A hash of the job name keeps it stable, and it stops a hundred jobs starting together.
03A pipeline deploys only under when { branch 'main' }, using a credential bound in that stage. A contributor who can push branches opens feature/x. What is the risk?
Correct — The condition lives in the file they control, so separate folders, agents and credential scopes are the real control.
Incorrect — Multibranch uses the Jenkinsfile from the branch being built.
Incorrect — Each branch has its own job and workspace.
Incorrect — A bad Jenkinsfile fails that branch's build. The serious problem is what a working one can do.

Related