At the end of module 5, the TecnoShop platform is solid, but it still finds out about changes by asking: every multibranch scans GitHub every 5 minutes, so Diego waits two or three minutes on average between his push and the start of his build, and Jenkins uses up GitHub API quota even when nobody has touched anything. On top of that, the conversation only goes one way: Jenkins reads the repository, but Diego's pull request does not show whether his build passed. In this lesson you will replace periodic scanning with events (webhooks) signed with a secret, learn the options for receiving them in a lab that lives on localhost, replace the personal token with a GitHub App with minimal permissions, make every build publish its status to GitHub as a commit status and as a GitHub Check, protect the main branch so nobody can merge without Jenkins' approval, and review the advanced checkout options and how to build tags. You will also see how the same is done with GitLab and Bitbucket.
From Periodic Scanning to Events
In 04-05 you configured Scan Multibranch Pipeline Triggers with a 5-minute interval and announced that, with webhooks, that interval would go up to one day. The two ways of finding out about a change are:
| Aspect | Periodic scanning (polling) | Webhook (event) |
|---|---|---|
| Who starts the communication | Jenkins asks GitHub | GitHub notifies Jenkins |
| Delay between push and build | Up to the interval (5 min in the worst case) | Seconds |
| GitHub API usage | Constant, whether or not there are changes | Only when there are changes |
| Network requirement | Jenkins must be able to reach out to GitHub | GitHub must be able to reach in to Jenkins |
| If a notification is lost | Not applicable | The change is not built until the next scan |
TecnoShop's conclusion: events as the main mechanism and a long periodic scan as a safety net. If a webhook is lost (Jenkins restarting, a network outage), the daily scan will pick it up.
How a Webhook Reaches Jenkins
A webhook is an HTTP POST request that GitHub sends to a URL when something happens in the repository. The body is a JSON document that describes the event (branch, commits, author, PR number...).
sequenceDiagram
participant D as Diego
participant G as GitHub
participant J as Jenkins (/github-webhook/)
participant M as Multibranch orders-api
D->>G: git push (branch or PR)
G->>J: POST /github-webhook/ (push or pull_request event, signed)
J->>J: Validates the signature with the shared secret
J->>M: Finds the jobs whose source matches the repository
M->>G: Queries the API (with the credential) to confirm the change
M->>M: Starts the branch or PR build
Notice two details:
- The endpoint is provided by the GitHub plugin (
github), which is installed as a dependency of GitHub Branch Source. The URL is always the same for the whole installation:<Jenkins URL>/github-webhook/, with the trailing slash. - Jenkins does not blindly trust the content of the event: it uses it as a notification and queries the GitHub API with its credential before building. Even so, validating the signature prevents anyone from triggering scans and builds by sending fake requests.
The GitHub Section in Manage Jenkins → System
Open Manage Jenkins → System and scroll down to the GitHub section. It contains two different things:
GitHub Servers (a list of servers with Add GitHub Server):
| Field | TecnoShop value | Explanation |
|---|---|---|
| Name | GitHub |
Descriptive name |
| API URL | https://api.github.com |
The one for GitHub.com. With GitHub Enterprise Server it would be https://<server>/api/v3 |
| Credentials | None | Only needed if you check Manage hooks |
| Manage hooks | Unchecked | See below |
Manage hooks lets Jenkins create and delete the repositories' webhooks itself. It is convenient, but it requires a credential with webhook administration permission on every repository. TecnoShop prefers to create the webhooks by hand (or with the organization's repository management tool) and to make sure the Jenkins credential cannot touch the repositories' configuration. It is the same least-privilege rule you applied to the token in 04-04.
Advanced (under the list of servers) reveals additional options:
- Override Hook URL: use it only if GitHub must call a URL different from the Jenkins URL (for example, a proxy that only exposes the webhook endpoint).
- Shared secrets: the secret Jenkins uses to validate the signature of each event. That is the next section.
The Webhook Shared Secret
GitHub signs every event with a secret known to both sides: it computes an HMAC SHA-256 of the body and sends it in the X-Hub-Signature-256 header. Jenkins recomputes the signature with its copy of the secret and rejects the event if they do not match.
Generating the Secret
openssl rand: generates cryptographically secure random bytes.-hex 32: 32 bytes expressed in hexadecimal (64 characters). That is more than enough.
A sample (fake) value would be 9f3c0d7e...fake...a41b. Keep it handy for a moment: you will need it in Jenkins and in GitHub.
Storing It as a Credential
Manage Jenkins → Credentials → System → Global credentials → Add Credentials:
| Field | Value |
|---|---|
| Kind | Secret text |
| Scope | System |
| Secret | The generated value |
| ID | github-webhook-secret |
| Description | Shared secret for the GitHub webhooks (orders-api, catalog-web). Owner: Laura. |
- Scope System: only Jenkins itself uses this secret, to validate events; no pipeline should be able to read it. Remember the difference between scopes from 04-04.
Attaching It to the GitHub Configuration
In Manage Jenkins → System → GitHub → Advanced → Shared secrets → Add, choose the github-webhook-secret credential. Depending on the plugin version, you can also specify the signature algorithm; leave it at SHA-256, which is the one GitHub recommends (SHA-1 is kept only for compatibility). Save.
From now on, an event with no signature or with an incorrect signature gets an error (usually 400 with a message saying the signature does not match) and triggers nothing.
Creating the Webhook in the Repository
In GitHub, in the orders-api repository: Settings → Webhooks → Add webhook.
| Field | Value | Explanation |
|---|---|---|
| Payload URL | https://jenkins.tecnoshop.local/github-webhook/ (at TecnoShop) |
The Jenkins URL plus /github-webhook/. In the lab you will change it in the next section |
| Content type | application/json |
The format the plugin expects |
| Secret | The same value as github-webhook-secret |
To sign the events |
| SSL verification | Enable SSL verification | Never disable it in production |
| Which events... | Let me select individual events: Pushes and Pull requests | Only what Jenkins needs |
| Active | Checked |
- Pushes: covers new commits on any branch and the creation or deletion of branches and tags.
- Pull requests: opening, updating, closing and reopening PRs. Without this event, a new PR would not be built until the next scan.
- Avoid Send me everything: Jenkins would receive events it has no interest in (stars, issues, comments) and process them for nothing.
Repeat the process in catalog-web with the same URL and the same secret. If TecnoShop used an Organization Folder (04-05), the webhook would be defined once in the organization, adding the Repositories event to detect new repositories.
Jenkins behind a firewall. GitHub.com is on the Internet and the TecnoShop Jenkins is on the internal network, behind the HTTPS proxy from 05-02. To let events in without exposing Jenkins, Laura publishes only the
/github-webhook/path on the proxy, restricted to the webhook IP ranges that GitHub publishes athttps://api.github.com/meta(thehookskey), and leaves every other path reachable only from the internal network. The signature with the secret is the second barrier.
The Lab Problem: Jenkins on localhost
Your Jenkins is at http://localhost:8080/. GitHub cannot reach your laptop's localhost: if you put that URL in the webhook, every delivery will fail. You have two reasonable options.
Option A: A Forwarding Channel with smee.io
smee.io is a free GitHub service designed for developing integrations: it gives you a public URL (a "channel"), GitHub sends the events there, and a small client running on your machine picks them up and forwards them to your local Jenkins. Because the client opens the connection outbound, there is no need to open any ports.
flowchart LR
G["GitHub"] -->|"POST event"| S["smee.io<br/>public channel"]
C["smee-client container<br/>(Compose network)"] -->|"outbound connection,<br/>receives events"| S
C -->|"POST /github-webhook/"| J["jenkins-controller:8080"]
- Open
https://smee.io/and click Start a new channel. Copy the URL, which looks likehttps://smee.io/AbCdEf0123fake. - Add it to the
.envfile in~/tecnoshop-jenkins(the same file from 05-01):
- Add the service to
docker-compose.yml:
smee-client:
image: node:22-alpine # pin a specific version, as in 05-04
container_name: smee-client
restart: unless-stopped
depends_on:
- jenkins-controller
command:
- npx
- --yes
- smee-client@<version> # pin the client version you have reviewed
- --url
- ${SMEE_URL}
- --target
- http://jenkins-controller:8080/github-webhook/node:22-alpine: a small image with Node, needed to run the smee client.npx --yes smee-client@<version>: downloads and runs the official client. Pinning the version prevents every startup from downloading different code from npm without your knowledge.--url ${SMEE_URL}: the channel, read from.env.--target http://jenkins-controller:8080/github-webhook/: the destination inside the Compose network. Just as with the agent in 05-01,localhostwould not work from inside the container.
In the log you will see something like Forwarding https://smee.io/AbCdEf0123fake to http://jenkins-controller:8080/github-webhook/ and Connected.
- In the GitHub webhook, set the Payload URL to the smee channel URL (not the Jenkins one). The other fields stay the same.
Be careful with smee.io:
- The channel is public: anyone who knows the URL can see the events (branch names, commit messages, authors) and send fake events to the channel, which your client would forward to Jenkins. That is why the shared secret is essential here.
- Use it only with your practice repositories. Never with a company's real code: the content of the events goes through a third-party service.
- Do not confuse it with a generic tunnel (ngrok, Cloudflare Tunnel...) that exposes your whole Jenkins on the Internet: smee only delivers requests to the endpoint you choose. Exposing the Jenkins interface on the Internet from a laptop is a bad idea, even with a password.
Option B: Keep Periodic Scanning
If you do not want to depend on an external service, do not configure the webhook and keep the 5-minute scan from 04-05. You lose immediacy, but everything else in this lesson (GitHub App, statuses, Checks, branch protection) works the same, because those pieces go from Jenkins to GitHub, and that direction does work from your laptop.
Checking Deliveries and Adjusting the Fallback Scan
In GitHub
In Settings → Webhooks, open the webhook and go to the Recent Deliveries tab. When you create it, GitHub sends a ping event. Each delivery shows:
- The request: headers (
X-GitHub-Event: push,X-Hub-Signature-256: sha256=...) and body. - The response: HTTP code and body. A
200means Jenkins accepted it. - The Redeliver button, very useful for replaying an event while you debug.
In Jenkins
Make a trivial commit on an orders-api branch and push it. Within seconds:
- In the
orders-apimultibranch, the Multibranch Pipeline Events link shows the received event, with text along the lines ofReceived Push event to branch feature/... in repository <your-username>/orders-api UPDATED eventand the jobs it affected. - The branch build starts without waiting for the scan.
If something goes wrong, here is the troubleshooting table:
| Symptom | Where to look | Likely cause |
|---|---|---|
| The delivery in GitHub shows a connection error | Recent Deliveries | The Payload URL is not reachable from GitHub (in the lab, smee is missing) |
400 response with a message about the signature |
Recent Deliveries | The secret in GitHub and the one in github-webhook-secret do not match |
200 response, but nothing is triggered |
Multibranch Pipeline Events | The multibranch repository URL does not match the one in the event (capitalization, .git, a different account) |
302 or 403 response |
Recent Deliveries | The URL does not end in /github-webhook/ (missing trailing slash) or a proxy redirects to the login page |
Raising the Scan Interval
With events working, in Configure for orders-api and catalog-web, set Scan Multibranch Pipeline Triggers → Interval to 1 day. This is the safety net announced in 04-05. If you chose option B, leave it at 5 minutes.
Authentication: Personal Token vs. GitHub App
So far Jenkins talks to GitHub using the jenkins-tecnoshop fine-grained token, stored in the github-tecnoshop credential. It works, but it has significant limitations for a service:
| Aspect | Fine-grained personal access token | GitHub App |
|---|---|---|
| Who it acts on behalf of | A person (Laura): if she leaves the company or loses access, Jenkins stops working | The application, independent of people |
| Permissions | The ones you choose, but limited to what that person can do | The ones declared in the App, granted when it is installed on specific repositories |
| API rate limit | 5,000 requests per hour, shared with everything that person does with tokens | Its own quota per installation, at least 5,000 per hour and growing with the number of repositories and users |
| Lifetime of the working credential | Whatever you choose (TecnoShop: 90 days) | 1-hour installation tokens, which Jenkins renews on its own from the private key |
| Rotation | Manual: generate a new token and update the credential before it expires | The private key is rotated whenever you decide; the working tokens are already short-lived |
| GitHub Checks API (write) | Not available | Available |
| Auditing in GitHub | Actions appear as performed by Laura | They appear as performed by the App (tecnoshop-jenkins[bot]) |
The last technical row of the table is decisive: Checks (the rich build summary inside the PR) can only be written by GitHub Apps. That is why TecnoShop is migrating to an App. If you cannot create one (for example, because your organization's policy does not allow it), the minimum alternative is to add the Commit statuses: Read and write permission to the token (Settings → Developer settings → Fine-grained tokens → jenkins-tecnoshop → Edit): you will get commit statuses on PRs, although not Checks.
Creating the TecnoShop GitHub App
At TecnoShop the App is created in the organization (Organization settings → Developer settings → GitHub Apps → New GitHub App). In your lab, in your account: avatar → Settings → Developer settings → GitHub Apps → New GitHub App.
| Field | Value | Explanation |
|---|---|---|
| GitHub App name | tecnoshop-jenkins (in your account, add a suffix: the name is unique across all of GitHub) |
It will appear as the author of the Checks |
| Homepage URL | https://jenkins.tecnoshop.local/ |
Required, but informational only |
| Webhook → Active | Unchecked | You already receive events through the repository webhook. An App can also send events, but mixing two sources makes troubleshooting harder |
| Where can this GitHub App be installed? | Only on this account | Nobody outside TecnoShop can install it |
Repository permissions (everything else set to No access):
| Permission | Level | What for |
|---|---|---|
| Contents | Read-only | Clone the code and read the Jenkinsfile |
| Metadata | Read-only | Mandatory; basic repository information |
| Pull requests | Read-only | Discover PRs and their information |
| Commit statuses | Read and write | Publish the classic status of each commit |
| Checks | Read and write | Publish GitHub Checks |
Notice what it does not have: no code write access, no administration, no webhook management. If the App key were leaked, the damage would be limited to reading those repositories and writing fake statuses.
Click Create GitHub App. On the App's page:
- Write down the App ID (a number, for example
123456, fictitious). - Under Private keys, click Generate a private key. The browser downloads a
.pemfile. It is the App's secret: treat it like an administrator password. - In Install App (side menu), install it on your account with Only select repositories:
orders-api,catalog-webandjenkins-shared-lib.
Converting the Key to the Format Jenkins Expects
GitHub generates the key in PKCS#1 format. The GitHub Branch Source plugin documentation asks you to convert it to PKCS#8 (recent versions may accept both, but the conversion does no harm and avoids errors):
openssl pkcs8 -topk8 -inform PEM -outform PEM \
-in tecnoshop-jenkins.2026-11-28.private-key.pem \
-out app-key-pkcs8.pem -nocryptpkcs8 -topk8: converts the key to PKCS#8 format.-inform PEM -outform PEM: text input and output (the-----BEGIN ...-----lines).-in/-out: the downloaded file and the converted file (the name of the downloaded file will vary).-nocrypt: not encrypted with a password; Jenkins will store it encrypted in its credential store.
The converted file starts with -----BEGIN PRIVATE KEY----- (without RSA). Once you have stored it in Jenkins, delete both files from your disk.
The GitHub App Credential and Migrating the Multibranch Jobs
A Decision: Keep the github-tecnoshop ID
The github-tecnoshop credential is used in both multibranch jobs, in the tecnoshop-lib library configuration and in the legacy freestyle job orders-api-build. The jobs reference it by its ID, so if the new credential keeps the same ID, none of them needs to change. This is the advantage of the stable IDs you argued for in 04-04: the ID says what the credential is for, not how it is made.
Jenkins does not let you change the type (Kind) of an existing credential, so the migration consists of testing the App, deleting the old credential and creating the new one with the same ID.
Step 1: Test the App with a Temporary Credential
Manage Jenkins → Credentials → System → Global credentials → Add Credentials:
| Field | Value |
|---|---|
| Kind | GitHub App |
| Scope | Global |
| ID | github-app-test (temporary) |
| App ID | Yours (123456 in the example) |
| Key | The full contents of app-key-pkcs8.pem |
Click the form's connection test button (Test Connection in current versions). It should respond with a success message and the remaining API quota. If the App were installed on several accounts or organizations, you would specify the Owner under Advanced so Jenkins knows which installation to use.
Open Configure for the orders-api multibranch, choose github-app-test in the GitHub source and click Validate, without saving. If it responds Credentials ok, the App works. Leave without saving and delete the temporary credential.
Step 2: Replace the Credential
Do it at a time when no builds are running (in production, with a heads-up in #ci-orders):
- Manage Jenkins → Credentials, open
github-tecnoshopand click Delete. - Create a GitHub App credential with ID
github-tecnoshop, the same App ID and the same key, and the descriptionGitHub App tecnoshop-jenkins (Contents/Metadata/PR read; Statuses/Checks write). Owner: Laura. - In each multibranch, click Scan Repository Now and check the Scan Repository Log: it should list branches and PRs as before.
- Run a build of
orders-apimain: loading[email protected]and the checkout should work as before. - In GitHub, revoke the
jenkins-tecnoshoptoken (Fine-grained tokens → Delete). A secret that is no longer used should not stay alive.
The GitHub App credential also works for regular Git operations over HTTPS: Jenkins obtains an installation token and uses it as the password. That is why the freestyle job orders-api-build keeps working unchanged.
Build Status in GitHub: Commit Status and Checks
Commit Status
With the Commit statuses: Read and write permission, the GitHub Branch Source plugin automatically publishes the status of each build on the corresponding commit, without touching the Jenkinsfile. The contexts you will see are:
| Context | When |
|---|---|
continuous-integration/jenkins/branch |
Branch builds |
continuous-integration/jenkins/pr-merge |
PR builds with the merge strategy (TecnoShop's) |
continuous-integration/jenkins/pr-head |
PR builds with the PR head revision strategy |
Each status goes through pending (build queued or running) and ends in success or failure, with a link to the build. An UNSTABLE build is published as a failure by default: for GitHub, "it is not green".
GitHub Checks
Checks are richer: in addition to the result, they show a summary, per-stage detail and annotations. To publish them:
- Install the GitHub Checks plugin (
github-checks) and add it to theplugins.txtfrom 05-04 (remember the rule: in production, plugins come in through the image). - Use a GitHub App credential in the multibranch source (you already do).
From the next build onward, the PR's Checks tab shows a check called Jenkins, with the status of each stage (Build, Checks, Smoke...) and a link to the build. Other plugins publish their own Checks if GitHub Checks is installed: the junit step publishes one with the test results, as you will see in 06-03.
In the multibranch Configure page, the plugin adds the Status Checks Properties behavior (Add under Behaviours), which lets you change the check's name (TecnoShop keeps Jenkins) and adjust what gets published. For a while you may see both the classic status (continuous-integration/jenkins/pr-merge) and the Jenkins check: that is normal, because they are two different mechanisms. Recent versions offer options to skip one of the two; their exact name varies by version, so check the help in the form itself.
This is how Diego will see it in his PR:
Some checks were not successful ✗ Jenkins — Failed in stage Checks › Tests Details ✗ continuous-integration/jenkins/pr-merge — This commit cannot be built Details
The Details link takes you to the Jenkins build. Diego no longer needs to open Jenkins to know whether his change works; only to find out why it does not.
Protecting the main Branch
Publishing the status does not prevent anyone from merging a red PR. That is what GitHub branch protection is for. In the repository, Settings → Rules → Rulesets → New ruleset → New branch ruleset (or, with the classic interface, Settings → Branches → Add branch protection rule):
| Option | Value | Effect |
|---|---|---|
| Ruleset name | protect-main |
|
| Enforcement status | Active | |
| Target branches | Include default branch | Applies to main |
| Restrict deletions | Checked | Nobody can delete main |
| Require a pull request before merging | Checked, 1 approval | Every change goes through review |
| Require status checks to pass | Checked; add the Jenkins check | A PR cannot be merged unless its build is green |
| Require branches to be up to date before merging | Optional | Forces the PR to be updated with main before merging; with TecnoShop's merge strategy the PR is already tested against main, but a main that moved on after the build can invalidate the result |
| Block force pushes | Checked | Nobody rewrites the history of main |
Practical details:
- GitHub only offers in its search box the checks that have run recently in the repository. If Jenkins does not show up, run a PR build first.
- If you stick with the token and have no Checks, the status you must require is
continuous-integration/jenkins/pr-merge. - On free GitHub accounts, protection rules are not enforced on private repositories (they require a paid plan). In your lab you can configure them and see the form, or try them on a public practice repository.
- Check who can bypass the rule (Bypass list). A rule that administrators skip "because they are in a hurry" stops protecting anything.
Apply the same configuration to catalog-web and jenkins-shared-lib. For the library it is even more important: remember from 04-06 that its code runs outside the sandbox.
GitLab and Bitbucket
The concepts are the same with other providers: a source plugin for multibranch, an endpoint for events and publishing the build status.
| Aspect | GitHub | GitLab | Bitbucket |
|---|---|---|---|
| Multibranch source plugin | GitHub Branch Source | GitLab Branch Source | Bitbucket Branch Source |
| Trigger plugin for standalone jobs | GitHub (github) |
GitLab (gitlab-plugin) |
Included in Bitbucket Branch Source / Bitbucket Server plugins |
| Webhook endpoint (approximate) | /github-webhook/ |
With gitlab-plugin: /project/<job-path>; with GitLab Branch Source, its own endpoint |
/bitbucket-scmsource-hook/notify |
| Event validation | HMAC signature with a secret | Secret token in the X-Gitlab-Token header |
Secret or signature, depending on Cloud or Data Center |
| Build status | Commit status and Checks, automatic | On the merge request: automatic with Branch Source; with gitlab-plugin, the gitlabCommitStatus / updateGitlabCommitStatus steps |
Automatic build status |
| Recommended credential | GitHub App | Project/group access token with minimal scope | Repository or project access token / App password (being retired in Cloud) |
With the GitLab plugin in a Pipeline job, the status of each stage is published on the merge request like this:
gitlabCommitStatus(name: ...): wraps the steps; it publishes running when they start and success or failed when they finish, under that name.- Explicit alternative:
updateGitlabCommitStatus name: 'build', state: 'success'in apostsection.
The exact names of endpoints and options change between versions of these plugins and between the cloud and self-managed editions: check each plugin's page on plugins.jenkins.io before configuring them.
Advanced Checkout Options
In a multibranch, the checkout is configured by the source's Behaviours (not by the Jenkinsfile). Under Configure → Branch Sources → GitHub → Behaviours → Add you will find:
| Behavior | Main options | When to use it |
|---|---|---|
| Advanced clone behaviours | Shallow clone and Shallow clone depth; Fetch tags; Path of the reference repo; Timeout (in minutes) for clone and fetch operations | Large repositories or ones with a long history; slow networks |
| Advanced checkout behaviours | Checkout Timeout | Checkouts with many files |
| Sparse Checkout paths | Paths to include | Monorepos: the build only needs one directory |
| Advanced sub-modules behaviours | Recursive, parent repository credentials, depth, timeout | Repositories with Git submodules |
| Git LFS pull after checkout | - | Repositories with large files in Git LFS (requires git-lfs on the agent) |
What you need to know about each one:
- Shallow clone (
--depth N): downloads only the last N commits. It saves time and disk space, but it breaks anything that needs history:git describe, tools that compute versions or the "new code" of an analysis, and TecnoShop's PR merge, which needs the common ancestor of the branch andmain(with a small depth it can fail with errors such asrefusing to merge unrelated histories). - Reference repo: a local "mirror" clone on the agent (for example, at
/home/jenkins/agent/git-cache/orders-api.git) from which Git takes the objects it already has instead of downloading them. Very effective with large repositories; the mirror has to be kept up to date. - Sparse checkout: Git downloads the repository, but only writes the specified paths to the workspace.
- Submodules: if the parent repository uses credentials, check Use credentials from default remote of parent repository so that submodules from the same provider are cloned with the same credential.
- Timeouts: the default Git timeout in Jenkins is 10 minutes; with huge repositories it may not be enough, and with a small one a lower value detects a hung server sooner.
TecnoShop's decision: orders-api and catalog-web are small and need their history for PR merges and, in 06-04, for SonarQube's new code. They keep the full clone. They only add Advanced clone behaviours with Fetch tags checked (you will need it in the next section) and an explicit 10-minute timeout.
checkout scmGit(...) in a Jenkinsfile
Sometimes a pipeline needs a second repository. For example, a stage that reads the environment configuration from a fictitious tecnoshop/environment-config repository and only needs its orders-api/ directory. The Snippet Generator (03-06), with the checkout: Check out from version control step and the Git SCM, generates something like this:
dir('config') {
checkout scmGit(
branches: [[name: 'main']],
userRemoteConfigs: [[
url: 'https://github.com/<your-username>/environment-config.git',
credentialsId: 'github-tecnoshop'
]],
extensions: [
cloneOption(shallow: true, depth: 1, noTags: true, timeout: 5),
sparseCheckout(sparseCheckoutPaths: [[path: 'orders-api/']]),
submodule(recursiveSubmodules: true, parentCredentials: true),
lfs()
]
)
}dir('config'): the second repository is cloned into a subdirectory so it does not get mixed up with theorders-apicode.scmGit(...): the modern syntax of thecheckoutstep for Git (it replaces the old[$class: 'GitSCM', ...], which you will see in many examples on the Internet).branches: [[name: 'main']]: the branch to download.userRemoteConfigs: URL and credential. The App also has access to this repository if you install it there.cloneOption(shallow: true, depth: 1, noTags: true, timeout: 5): a shallow clone of a single commit, with no tags and 5 minutes at most. Here it does make sense: only the latest version of a few files is read.sparseCheckout(...): onlyorders-api/is written to the workspace.submodule(...)andlfs(): shown as a syntax example; include them only if the repository uses submodules or LFS.
The main checkout of a multibranch is still done with the implicit checkout scm, which inherits the source's behaviors.
Building Tags
TecnoShop will mark each published version with a Git tag (v1.0.0, v1.1.0...), and in 06-05 the build of that tag will be the one that publishes the final version. For Jenkins to see the tags:
- In Configure for
orders-api, Behaviours → Add → Discover tags. Save. - After the next scan, a Tags tab appears with one job per tag.
As you already saw coming in 04-05, tag jobs are not built automatically: that way, when you enable discovery, Jenkins does not rebuild every old tag at once. They are built with Build Now on the tag's job. To build them when they are created, there is the Basic Branch Build Strategies plugin, which allows it with conditions (for example, ignoring tags older than a few days); its use in the delivery flow is covered in module 7.
In the pipeline, a tag build can be recognized like this:
| Element | Value in the v1.0.0 build |
|---|---|
env.BRANCH_NAME |
v1.0.0 (the tag name) |
env.TAG_NAME |
v1.0.0 |
env.TAG_DATE |
Date of the tag |
when { buildingTag() } |
Matches |
when { tag 'v*' } |
Matches (glob-style pattern) |
when { branch 'main' } |
Does not match |
The orders-api Jenkinsfile already behaves well with tags: the cron is only enabled on main and Deploy to dev requires branch 'main', so a tag build compiles, tests and packages, but does not deploy or schedule nightly builds. This lesson does not change the Jenkinsfile: everything you have done is Jenkins and GitHub configuration.
Common Mistakes and Tips
- Payload URL without the trailing slash (
/github-webhook): Jenkins responds with a redirect and GitHub marks it as a failure. - Putting
http://localhost:8080/...in the webhook: GitHub cannot reach your laptop. Use smee or periodic scanning. - Different secrets in GitHub and Jenkins, often because of an extra space or line break copied by accident: every delivery fails on the signature.
- Secret credential with Global scope: it works, but any pipeline could read it. Use System.
- Checking Manage hooks "so you don't have to create the webhooks by hand": it requires giving Jenkins administration permissions on the repositories.
- Forgetting to install the App on a repository: scanning that repository fails with access errors even though the credential is valid.
- Expecting Checks with a personal token: the Checks API only accepts GitHub Apps; with a token you will only get commit statuses.
- Requiring a check with a different name in branch protection (for example,
continuous-integration/jenkins/branchinstead of the PR one): the PR sits waiting for a status that never arrives. - Enabling shallow clone "to go faster" on a small repository: you save seconds and break PR merges and new-code analysis.
- Tip: record in each credential's description who owns it and how it is rotated. With the App, also note the date of the current private key.
Exercises
Exercise 1. Configure the orders-api webhook with smee.io and the github-webhook-secret secret. Then change one character of the secret in GitHub and push a commit. What do Recent Deliveries and Multibranch Pipeline Events show? Restore the secret and use Redeliver on the failed delivery: what happens now?
Exercise 2. Laura receives this proposal from a colleague for the Jenkins App: Contents: Read and write, Administration: Read and write and Webhooks: Read and write permissions, "so Jenkins can create tags and manage the hooks on its own". Write her reply, stating which permissions she would grant and why.
Exercise 3. A TecnoShop team has a 4 GB monorepo, tecnoshop/platform, with 12 years of history; their service lives in services/billing/ and their PRs take 6 minutes just for the checkout. Propose a behavior configuration for their multibranch and explain the risk of each option you choose.
Solutions
Solution 1. With the altered secret, the delivery appears in Recent Deliveries with a 400 error and a body saying the signature does not match; nothing appears in Multibranch Pipeline Events, because Jenkins discards the event before processing it, and no build is triggered (until the fallback scan runs). Once you restore the secret, Redeliver sends the same event again, but GitHub signs it afresh with the current secret: the response is 200, the event appears in Multibranch Pipeline Events and the branch build starts. It is the fastest way to verify a fix without making test commits.
Solution 2. "I would not grant any of those three. Write access to Administration and Webhooks would turn the App key into a key for changing the configuration of our repositories: if it leaked, someone could disable the protection on main or redirect the webhooks. We manage the webhooks ourselves, without Manage hooks. Write access to Contents would let any pipeline (including one from a PR) push code or tags to our repositories. If in the future we need a process to create release tags, we will consider a separate credential, limited to that process and to main. The App keeps Contents, Metadata and Pull requests as read-only, and Commit statuses and Checks as read and write."
Solution 3. Proposal: (1) Advanced clone behaviours with Path of the reference repo pointing to a mirror on the agent (git clone --mirror kept up to date by a scheduled job), which avoids downloading the history on every build without losing it; risk: the mirror takes up disk space and, if it falls out of date, Git downloads whatever is missing (it breaks nothing, it just becomes less effective). (2) Sparse Checkout paths with services/billing/ and the shared files the build needs (for example, the parent pom.xml); risk: if the build needs another path that is not on the list, it fails in a way that is not obvious. (3) A 20-minute clone Timeout for the first clone. (4) Shallow clone only if the team verifies that PR merges work with the chosen depth (for example, 50) and that it does not use tools that need history; if PRs live only a few days, a moderate depth is usually enough, but it is the riskiest of the four options. Measuring the checkout time before and after each change, one at a time, keeps you from crediting the improvement to the wrong option.
Conclusion
Jenkins and GitHub now talk in both directions. GitHub notifies Jenkins with push and pull request webhooks to the /github-webhook/ endpoint, signed with the github-webhook-secret secret that Jenkins validates; in the lab you receive them through a smee.io channel (with the caution a public channel demands) or keep periodic scanning, and in both cases the long scan remains as a safety net. Jenkins authenticates with the tecnoshop-jenkins GitHub App, installed only on the repositories it needs and with minimal permissions, under the same github-tecnoshop ID so that the multibranch jobs and the library do not change, and it publishes the result of every build as a commit status and as a GitHub Check, which the protect-main rule requires before merging. You know how the same is done with GitLab and Bitbucket, when shallow clones, reference repos, sparse checkouts, submodules and LFS pay off, and orders-api now discovers its tags, which are recognized with buildingTag(). With changes arriving instantly, the next step is to look inside the build: how Jenkins uses Maven, Gradle and npm reproducibly and with configuration managed by the platform, in Integrating with Build Tools.
