Triggers, webhooks and multibranch
Polling, a push hook with an API token, and one job per branch.
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: ffd39da4bc093ffaad30d14833b7b774617e62eddbd272572a6e31f0ef2c73d0CI 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:
pipeline {agent { label 'linux' }triggers { pollSCM('* * * * *') }stages {stage('Test') { steps { echo 'polled build' } }}}
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:
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:
#!/bin/sh# Git server hook: asks Jenkins to build after every push. HOOK_AUTH is base64 of user:api-token.. /srv/git/hook.envwget -q -O /dev/null --post-data= --header="Authorization: Basic $HOOK_AUTH" http://controller:8080/job/hooked/build \&& echo "jenkins: build requested"
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:
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:
<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>
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).
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.
triggers { pollSCM('H/5 * * * *') } to a Jenkinsfile on a new job and push. No build starts, even after an hour of commits. Why?H is a valid Jenkins extension to cron syntax.H in cron('H 2 * * *')?2 is the hour. H is in the minute field here.H picks a single minute.when { branch 'main' }, using a credential bound in that stage. A contributor who can push branches opens feature/x. What is the risk?