orders-api is built on every push, tested, analyzed, published to Nexus and deployed to dev-01. But if the nightly main build fails at two in the morning, or if the eleven o'clock merge breaks the deployment to dev, nobody will know until someone happens to open Jenkins, or until Marta discovers that dev is still running yesterday's version. A continuous integration system is only useful if its result reaches the right people, in time and without noise. In this lesson you will define TecnoShop's notification principles, configure email with Email Extension (with a test SMTP server in the lab), Slack with the Slack Notification plugin and its app, and see how to send notices to Microsoft Teams with Workflows webhooks. Then you will centralize all those decisions in a new library step, notifyTeam, use it in orders-api and catalog-web, and close the module with the complete orders-api Jenkinsfile.
Principles: Actionable, to the Right People, Without Noise
The fastest way to get a team to ignore Jenkins notifications is to send them lots of them. If #ci-orders gets a message for every green build of every branch, within a week nobody will read the channel, not even on the day main breaks. Three principles:
| Principle | Question | Good example | Bad example |
|---|---|---|---|
| Actionable | Does someone have to do something after reading it? | "main has started failing in Integration tests" |
"Build #57 of feature/x succeeded" |
| To the right people | Does it reach someone who can act? | The authors of the changes that broke it and the team channel | The whole company |
| Without noise | Is it a change of state or a repetition? | "Back to green" once | "Still failing" by email every hour |
And a fourth, practical one: the message must be enough to get started. Project, branch, build number, what happened and a direct link. If you have to open Jenkins and search to understand the notice, the notice is incomplete.
This lesson is about notifications on build results. Alerts about the health of the platform itself (controller disk, queue, agents down) are a different matter, and you already solved them with Prometheus and Alertmanager in 05-05.
What to Notify and to Whom: TecnoShop's Rules
Remember the post block conditions from 03-05: failure, unstable, success, fixed (green after red or yellow), regression (worse than the previous build), changed, aborted... TecnoShop turns them into these rules:
Situation on main |
Equivalent post condition |
Who | Channel |
|---|---|---|---|
| Starts failing | failure when the previous build was not failing (regression) |
The authors of the changes, whoever triggered the build and the team | Slack #ci-orders and email |
| Still failing | failure when the previous build also failed |
The team | Slack, short message |
| Becomes unstable | unstable when the previous build was green (regression) |
The team | Slack |
| Back to green | fixed |
The team | Slack |
| Green after green | success with no change |
Nobody | - |
| Aborted | aborted |
Nobody: whoever aborted it already knows | - |
Any branch or PR other than main |
All | The PR author | GitHub (statuses and Checks, 06-01) |
Two decisions deserve an explanation:
- Branches and PRs do not notify the channel. A red PR is its author's business; they already see it in GitHub and cannot merge it because of the
protect-mainrule. Notifying the channel would turn every developer's daily work into noise for everyone. - Email only for "starts failing". That is the moment when a specific person (whoever made the change) has to act, and email reaches them even if they are not watching Slack. Repeating it on every subsequent failure would be noise.
If the team also wants a record of what gets deployed to dev, the recommended practice is a dedicated deployments channel, separate from the notices channel: mixing "information" with "something is wrong" leads people to ignore the latter.
The Channel for Pull Requests: GitHub
In 06-01 you made every build publish its status to GitHub as a commit status and as a check, and in 06-03 you made the tests show up in the Tests check. For a developer, that is the main feedback: it arrives where they work (the PR), with the detail of which stage failed and a link to the build, and GitHub already notifies them according to their preferences. Nothing else needs to be added for branches and PRs.
Email with Email Extension: The SMTP Configuration
Jenkins has two email plugins:
| Plugin | Step | Use |
|---|---|---|
| Mailer (core) | mail |
Simple emails: recipient, subject, body |
Email Extension (email-ext, included in the suggested plugins) |
emailext |
Computed recipients (authors of the changes, whoever triggered the build), attaching the log, templates, tokens |
TecnoShop uses Email Extension. The configuration is in Manage Jenkins → System:
Jenkins Location → System Admin e-mail address: Jenkins TecnoShop <[email protected]>. It is the sender of every email Jenkins sends; many SMTP servers reject emails without a valid sender.
Extended E-mail Notification:
| Field | At TecnoShop | In the lab (Mailpit) |
|---|---|---|
| SMTP server | smtp.tecnoshop.local (the same one Alertmanager uses in 05-05) |
mailpit |
| SMTP Port | 587 |
1025 |
| Credentials (under Advanced) | A Username with password credential for the sending account | None |
| Use TLS | Checked | Unchecked |
| Default user e-mail suffix | @tecnoshop.example |
@tecnoshop.example |
| Default Content Type | Plain Text (text/plain) | Plain Text (text/plain) |
- Use TLS on port 587: the connection is encrypted before credentials and content are sent. Never send SMTP credentials unencrypted outside a lab.
- Default user e-mail suffix: if Jenkins only knows a user's ID (for example,
diego), it builds their address as[email protected]. It helps resolve computed recipients. - Default Content Type: text/plain: plain text avoids problems when you include data you do not control (commit messages, branch names) in an HTML email.
Recent versions of the plugin also let you restrict the destination domains (for example, only tecnoshop.example), which keeps a Jenkinsfile from sending emails outside the company. If your version offers it, enable it. The E-mail Notification section (from the Mailer plugin) has its own SMTP configuration and a button to send a test email; if you fill it in with the same values, you can use it to verify the connection.
Optional Lab: Mailpit
To test without sending real emails, add a test SMTP server to docker-compose.yml. Mailpit accepts any email and shows it in a web interface, without delivering it to anyone:
mailpit:
image: axllent/mailpit:<version> # pin a specific version, as in 05-04
container_name: mailpit
restart: unless-stopped
ports:
- "127.0.0.1:8025:8025"- Inside the Compose network, SMTP is at
mailpit:1025(not published on the host: only Jenkins uses it). - The web interface is published at
http://localhost:8025, only on your machine. - No volume: emails are lost when the container is recreated, which is what you want for testing.
Configure Jenkins with mailpit and 1025 as in the previous table. Every email it sends will appear at http://localhost:8025. (MailHog is a similar and well-known alternative, but it has not been actively maintained for years.)
The emailext Step
emailext(
to: '[email protected]',
recipientProviders: [culprits(), developers(), requestor()],
subject: "[Jenkins] ${env.JOB_NAME} #${env.BUILD_NUMBER}: started failing",
body: """The build ${env.JOB_NAME} #${env.BUILD_NUMBER} failed.
Build: ${env.BUILD_URL}
Console: ${env.BUILD_URL}console
Changes: ${env.BUILD_URL}changes
""",
mimeType: 'text/plain',
attachLog: true,
compressLog: true
)| Parameter | What it does |
|---|---|
to |
Fixed recipients, separated by commas |
recipientProviders |
Recipients computed by Jenkins (see below) |
subject |
The subject |
body |
The body |
mimeType |
text/plain or text/html |
attachLog |
Attaches the build log |
compressLog |
Attaches it compressed (a pipeline log can be several MB) |
The most useful recipient providers:
| Provider | Who it adds |
|---|---|
culprits() |
The authors of the changes since the last successful build: the people who probably broke it (if main has had three red builds, it includes the changes from all three) |
developers() |
The authors of the changes in this build |
requestor() |
Whoever triggered the build by hand (in automatic builds, nobody) |
brokenBuildSuspects() |
The suspects for breaking the build, based on the change of state |
Jenkins gets the commit authors from Git. For them to become email addresses, each author must match a Jenkins user with an email address or be resolved with the default suffix; if emails are not reaching the people they should, check that before looking at SMTP.
Groovy Interpolation vs. Email Extension Tokens
Look at the quotes. In the example, subject and body are in double quotes: Groovy substitutes ${env.BUILD_URL} before calling the step, as in any pipeline string. Email Extension also has its own token system, which the plugin substitutes when it generates the email, and those are written in single quotes so Groovy leaves them alone:
emailext(
to: '[email protected]',
subject: '[Jenkins] ${JOB_NAME} #${BUILD_NUMBER}: ${BUILD_STATUS}',
body: '${BUILD_URL}\n\nLast lines of the log:\n${BUILD_LOG, maxLines=40}',
mimeType: 'text/plain'
)${BUILD_STATUS},${BUILD_LOG, maxLines=40},${CHANGES}... are plugin tokens. The full list is in the help for the Default Content field in the configuration (Content Token Reference).- With double quotes, Groovy would try to resolve
${BUILD_LOG, maxLines=40}as code and would fail. - Neither form should include secrets. And if you use
text/html, data you do not control (${CHANGES}, commit messages) could inject HTML: another reason for plain text.
The TecnoShop library uses Groovy interpolation, because the format is decided by the step itself and does not depend on the plugin's global configuration.
Slack: The App, the slack-token Credential and the Plugin
Creating the Slack App
At TecnoShop, the notices channel for orders-api is #ci-orders. For the lab you can create a free test Slack workspace; if you would rather not, follow the lesson with Mailpit and read this section.
- At
https://api.slack.com/apps→ Create New App → From scratch: nameJenkins TecnoShop, your workspace. - OAuth & Permissions → Scopes → Bot Token Scopes: add
chat:write(post messages). Optionally,files:writeif you are going to upload files andchat:write.customizeif you want to change the name or icon each message appears with. Nothing else. - Install to Workspace and accept. Copy the Bot User OAuth Token, which starts with
xoxb-. - In Slack, in the
#ci-orderschannel, invite the bot:/invite @Jenkins TecnoShop. A bot can only post in the channels it belongs to.
The Credential
In 04-04 you created slack-token as Secret text with the fake value xoxb-0000-fake-tecnoshop. Open the credential, click Update and enter the bot's real token. Update the description: Slack: bot token for the Jenkins TecnoShop app (chat:write). Owner: Laura.
The Plugin
Install Slack Notification (slack) and add it to plugins.txt. In Manage Jenkins → System → Slack:
| Field | Value |
|---|---|
| Workspace | Your workspace's subdomain (the xxx part of xxx.slack.com) |
| Credential | slack-token |
| Default channel / member id | #ci-orders |
| Custom slack app bot user | Checked (you are using a bot token from your own app) |
Click Test Connection: a test message should appear in #ci-orders and the Success response in Jenkins. Save.
Slack's old "Jenkins CI" integration, with tokens that do not start with xoxb-, is deprecated; if you see it in tutorials, replace it with your own app.
slackSend: Colors, Links, Threads and Updates
slackSend(
channel: '#ci-orders',
color: 'danger',
message: "*orders-api/main #57: started failing*\n<${env.BUILD_URL}|Open the build> · <${env.BUILD_URL}console|Console>"
)channel: the channel (or a channel or user ID). If omitted, the one from the global configuration.color: the message's side bar:good(green),warning(amber),danger(red) or a hexadecimal color.message: the text, in Slack format (mrkdwn):*bold*,_italics_, line breaks with\nand links in the form<url|text>.tokenCredentialId: lets a single call use a credential other than the global one (for example, the bot for another workspace).
With an app using a bot token, slackSend returns an object with the data of the posted message, which enables two useful patterns for reducing noise:
def notice = slackSend(channel: '#ci-orders', color: 'danger',
message: '*orders-api/main #57: started failing*')
// Reply in a thread on the message (the channel does not get a new message)
slackSend(channel: notice.threadId, message: 'Stage: Integration tests. Owner: Diego.')
// Update the message itself instead of posting another one
slackSend(channel: notice.channelId, timestamp: notice.ts, color: 'good',
message: '*orders-api/main #57*: fixed in #58')threadId: identifies the message's thread; using it as thechannelposts the reply inside it.channelId+timestamp: notice.ts: thetsidentifies a specific message; with it,slackSendedits it.
Keeping that identifier across different builds (so the build that fixes main updates the message from the one that broke it) requires persisting it somewhere, and it adds complexity. TecnoShop sticks with one message per change of state, which is simple and sufficient; threads are useful for adding detail within a single build.
Microsoft Teams with Workflows Webhooks
If your organization uses Microsoft Teams, the way to receive messages from an external system has changed. For years people used Office 365 connectors ("Incoming Webhook"), and in Jenkins the Office 365 Connector plugin; Microsoft is gradually retiring them and recommends replacing them with the Workflows app (based on Power Automate). The dates and terms of the retirement have changed several times; check Microsoft's official notices before building anything new with connectors.
With Workflows:
- In the Teams channel → Workflows → the template to Post to a channel when a webhook request is received.
- The wizard generates a URL. Whoever has it can post to the channel: treat it as a secret and store it in Jenkins as Secret text (for example, with the ID
teams-webhook-orders). - The webhook expects JSON with an Adaptive Card.
From the pipeline, with no additional plugins, using curl:
stage('Teams notice (example)') {
steps {
writeFile file: 'teams.json', text: """{
"type": "message",
"attachments": [{
"contentType": "application/vnd.microsoft.card.adaptive",
"content": {
"type": "AdaptiveCard",
"version": "1.4",
"body": [
{ "type": "TextBlock", "weight": "Bolder", "size": "Medium",
"text": "${env.JOB_NAME} #${env.BUILD_NUMBER}: ${currentBuild.currentResult}" },
{ "type": "TextBlock", "wrap": true, "text": "Build result from the TecnoShop Jenkins." }
],
"actions": [
{ "type": "Action.OpenUrl", "title": "Open the build", "url": "${env.BUILD_URL}" }
]
}
}]
}
"""
withCredentials([string(credentialsId: 'teams-webhook-orders', variable: 'TEAMS_URL')]) {
sh 'curl -sf -X POST -H "Content-Type: application/json" --data @teams.json "$TEAMS_URL"'
}
}
}writeFile: writes the card. The interpolated values (JOB_NAME,BUILD_NUMBER, the result and the URL) are generated by Jenkins and contain no quotes; if you included external data, such as a PR title, you would have to escape it so as not to break the JSON."type": "AdaptiveCard"and"actions": a card with a title, a text and a button linking to the build.withCredentials+"$TEAMS_URL"in single quotes in Groovy: only the shell sees the secret URL, and Jenkins masks it in the log.--data @teams.json: the request body is read from the file.
The HTTP Request plugin offers the httpRequest step to do the same without curl; if you use it, enable its quiet: true option so it does not write the URL or the body to the log. TecnoShop uses Slack, so this pattern stays as a reference.
Centralizing the Rules: notifyTeam in tecnoshop-lib v1.3.0
The rules in the table from section 2 should be the same for every TecnoShop project. If each Jenkinsfile implemented them with its own post blocks, within six months every project would notify in a different way. It is the exact use case for the library from 04-06: Laura creates the notifyTeam step.
vars/notifyTeam.groovy:
/**
* Notifies the team of the build result using the common TecnoShop rules.
* Called from post { always { ... } }.
*
* notifyTeam channel: '#ci-orders', email: '[email protected]'
*
* Parameters: channel (required), email (optional), branches (optional, defaults to ['main']).
*/
def call(Map config = [:]) {
if (!config.channel) {
error 'notifyTeam: the "channel" parameter is missing'
}
List branches = config.branches ?: ['main']
String branch = env.BRANCH_NAME ?: ''
if (!branches.contains(branch)) {
echo "notifyTeam: branch '${branch}' does not notify the team (feedback for branches and PRs is in GitHub)"
return
}
String current = currentBuild.currentResult
String previous = currentBuild.previousCompletedBuild?.result
String event = classify(current, previous)
if (!event) {
echo "notifyTeam: ${current} after ${previous ?: 'no build'}; nothing to notify"
return
}
Map format = formatFor(event)
String title = "${env.JOB_NAME} #${env.BUILD_NUMBER}: ${format.text}"
boolean withEmail = format.email && config.email
echo "notifyTeam: ${event} → Slack ${config.channel}" + (withEmail ? ' and email' : '')
try {
slackSend(channel: config.channel, color: format.color,
message: "*${title}*\n<${env.BUILD_URL}|Open the build> · <${env.BUILD_URL}console|Console>")
} catch (Exception e) {
echo "notifyTeam: could not notify Slack (${e.message})"
}
if (withEmail) {
try {
emailext(
to: config.email,
recipientProviders: [culprits(), developers(), requestor()],
subject: "[Jenkins] ${title}",
body: """${title}
Branch: ${branch}
Build: ${env.BUILD_URL}
Console: ${env.BUILD_URL}console
Changes: ${env.BUILD_URL}changes
The build log is attached, compressed.
--
TecnoShop Jenkins. This email is sent when a ${branch} build starts failing.
""",
mimeType: 'text/plain',
attachLog: true,
compressLog: true
)
} catch (Exception e) {
echo "notifyTeam: could not send the email (${e.message})"
}
}
}
private String classify(String current, String previous) {
if (current == 'FAILURE') {
return previous == 'FAILURE' ? 'STILL_FAILING' : 'FAILED'
}
if (current == 'UNSTABLE') {
return (previous == null || previous == 'SUCCESS') ? 'DEGRADED' : null
}
if (current == 'SUCCESS' && (previous == 'FAILURE' || previous == 'UNSTABLE')) {
return 'FIXED'
}
return null
}
private Map formatFor(String event) {
switch (event) {
case 'FAILED':
return [text: 'started failing', color: 'danger', email: true]
case 'STILL_FAILING':
return [text: 'still failing', color: 'danger', email: false]
case 'DEGRADED':
return [text: 'is unstable (check the coverage)', color: 'warning', email: false]
default:
return [text: 'is back to green', color: 'good', email: false]
}
}How it works, from top to bottom:
- Branch filter: only the branches in
branches(by default,main) notify. On any other, the step writes a line to the console explaining why it is not notifying and returns. A project with a maintenance branch could passbranches: ['main', 'release/1.x']. currentBuild.currentResult: the build result at this moment. Insidepost { always }, it already reflects what happened in every stage.currentBuild.previousCompletedBuild?.result: the result of the previous completed build. The?.avoids an error on a branch's first build, which has no previous one.classify: translates the (current, previous) pair into an event from the table in section 2. It is exactly the logic ofpost'sregression,fixedandfailure, in a single place:FAILEDis "fails and was not failing before",STILL_FAILINGis "fails and was failing before too",DEGRADEDis "unstable and was green before",FIXEDis "green after red or yellow".ABORTED,NOT_BUILTand green after green produce no event.formatFor: the text, the Slack color and whether the event includes an email. Changing the format of every TecnoShop notice means changing this method.try/catcharound each send: if Slack is down or the SMTP server rejects the email, the step logs it to the console, but does not change the build result. A notification that fails must not turn a green build red, nor hide the reason for a red one.privatemethods in avars/file are helpers: they cannot be called from theJenkinsfile.
Document the step in vars/notifyTeam.txt (parameters, rules and an example), follow the versioning workflow (a feature/notify-team branch, a test PR in orders-api, merge) and release:
git tag -a v1.3.0 -m "notifyTeam: common notifications (Slack and email) with change-of-state rules"
git push origin v1.3.0It is a new, compatible feature: v1.3.0.
Testing notifyTeam with JenkinsPipelineUnit
Notification rules are pure logic and deserve tests, like mavenTecnoShop in 04-06. test/groovy/NotifyTeamTest.groovy:
import com.lesfurets.jenkins.unit.BasePipelineTest
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import static org.junit.jupiter.api.Assertions.*
class NotifyTeamTest extends BasePipelineTest {
def step
@Override
@BeforeEach
void setUp() throws Exception {
super.setUp()
helper.registerAllowedMethod('slackSend', [Map], null)
helper.registerAllowedMethod('emailext', [Map], null)
helper.registerAllowedMethod('culprits', [], null)
helper.registerAllowedMethod('developers', [], null)
helper.registerAllowedMethod('requestor', [], null)
binding.setVariable('env', [BRANCH_NAME: 'main', JOB_NAME: 'orders-api/main',
BUILD_NUMBER: '57', BUILD_URL: 'http://localhost:8080/job/orders-api/job/main/57/'])
step = loadScript('vars/notifyTeam.groovy')
}
private void results(String current, String previous) {
binding.setVariable('currentBuild', [currentResult: current,
previousCompletedBuild: previous ? [result: previous] : null])
}
private int calls(String method) {
helper.callStack.count { it.methodName == method }
}
@Test
void aNewFailureNotifiesSlackAndEmail() {
results('FAILURE', 'SUCCESS')
step.call(channel: '#ci-orders', email: '[email protected]')
assertEquals(1, calls('slackSend'))
assertEquals(1, calls('emailext'))
}
@Test
void aRepeatedFailureOnlyNotifiesSlack() {
results('FAILURE', 'FAILURE')
step.call(channel: '#ci-orders', email: '[email protected]')
assertEquals(1, calls('slackSend'))
assertEquals(0, calls('emailext'))
}
@Test
void greenAfterGreenDoesNotNotify() {
results('SUCCESS', 'SUCCESS')
step.call(channel: '#ci-orders')
assertEquals(0, calls('slackSend'))
}
@Test
void branchesOtherThanMainDoNotNotify() {
binding.getVariable('env').BRANCH_NAME = 'PR-12'
results('FAILURE', 'SUCCESS')
step.call(channel: '#ci-orders', email: '[email protected]')
assertEquals(0, calls('slackSend'))
assertEquals(0, calls('emailext'))
}
}registerAllowedMethod: mocks the Slack and Email Extension steps and the recipient providers; nothing is sent.results(...): mockscurrentBuildwith the current and previous results, as a map. Groovy lets you readcurrentBuild.currentResultfrom a map just as it would from the real object.calls(...): counts how many times a step has been called.- The four tests cover the key rules: a new failure (Slack and email), a repeated failure (Slack only), green after green (nothing) and branches other than
main(nothing).
notifyTeam in orders-api and catalog-web
orders-api
The pipeline's post block gets simpler. It used to have four conditions with echo (success, unstable, failure, fixed); now:
post {
always {
notifyTeam channel: '#ci-orders', email: '[email protected]'
}
cleanup {
cleanWs()
}
}always: the step decides whether and how to notify, so it is always called. The line it writes to the console (notifyTeam: FAILED → Slack #ci-orders and email, or the reason it is not notifying) replaces the oldechos.cleanupis still the last condition to run, afteralways.- The first line of the file becomes
@Library('[email protected]') _.
catalog-web
catalog-web was on [email protected]. Because all the intermediate versions are compatible, the jump to v1.3.0 requires no changes to what it already uses (infoBuild):
@Library('[email protected]') _
pipeline {
agent none
// ... options and stages unchanged from 06-04 ...
post {
always {
notifyTeam channel: '#ci-catalog', email: '[email protected]'
}
}
}- The catalog team has its own channel,
#ci-catalog; the rules and the format are the same as inorders-api. - With
agent none, the pipeline'sposthas no agent. That does not matter:slackSendandemailextwork with the build (result, log, URL), not with workspace files. If in your version of Email Extension attaching the log required a workspace, the solution would be to wrap the call in anode('linux')block. - The old
successandfailureechos go away, just as inorders-api.
Make each change on a branch with a PR: the PR build will show in the console that the branch does not notify, and the first main build after merging will say nothing to notify (if it is green, like the previous one). To see a real notice, deliberately break a test on main through a PR, merge it and watch Slack (or Mailpit); then fix it and you will see the green is back to green message.
The orders-api Jenkinsfile at the End of Module 6
@Library('[email protected]') _
pipeline {
agent {
label 'linux'
}
options {
timestamps()
timeout(time: 30, unit: 'MINUTES')
buildDiscarder(logRotator(numToKeepStr: '30', artifactNumToKeepStr: '5'))
disableConcurrentBuilds()
preserveStashes(buildCount: 5)
}
parameters {
booleanParam(name: 'RUN_TESTS', defaultValue: true,
description: 'Uncheck only to quickly verify that the code compiles. Without tests nothing is analyzed, published or deployed.')
choice(name: 'ENVIRONMENT', choices: ['dev', 'staging', 'production'],
description: 'Target environment. For now only dev has a deployment (dev-01.tecnoshop.local), and only from main.')
}
triggers {
cron(env.BRANCH_NAME == 'main' ? 'TZ=Europe/Madrid\nH 2 * * 1-5' : '')
}
environment {
MAVEN_ARGS = '-B -ntp'
MAVEN_SETTINGS_ID = 'maven-settings-tecnoshop'
IMAGE = 'registry.tecnoshop.local/orders-api'
APP_VERSION = sh(script: './mvnw -q help:evaluate -Dexpression=project.version -DforceStdout',
returnStdout: true, label: 'Read the version from the pom').trim()
IMAGE_TAG = "${APP_VERSION}-${BUILD_NUMBER}"
}
stages {
stage('PR info') {
when {
changeRequest()
}
steps {
echo "PR #${env.CHANGE_ID} by ${env.CHANGE_AUTHOR}: ${env.CHANGE_BRANCH} → ${env.CHANGE_TARGET} (${env.CHANGE_URL})"
}
}
stage('Build') {
steps {
echo "Build ${env.BUILD_NUMBER} of ${env.JOB_NAME} | branch ${env.BRANCH_NAME} | version ${env.APP_VERSION} | ENVIRONMENT=${params.ENVIRONMENT} | RUN_TESTS=${params.RUN_TESTS}"
mavenTecnoShop 'clean compile'
}
}
stage('Checks') {
failFast true
parallel {
stage('Tests') {
when {
expression { params.RUN_TESTS }
}
options {
timeout(time: 10, unit: 'MINUTES')
}
steps {
mavenTecnoShop 'test'
recordCoverage(
tools: [[parser: 'JACOCO', pattern: 'target/site/jacoco/jacoco.xml']],
id: 'jacoco',
name: 'Coverage (JaCoCo)',
sourceCodeRetention: 'LAST_BUILD',
qualityGates: [
[metric: 'LINE', baseline: 'PROJECT', threshold: 70.0, criticality: 'UNSTABLE'],
[metric: 'BRANCH', baseline: 'PROJECT', threshold: 60.0, criticality: 'UNSTABLE']
]
)
}
post {
always {
junit testResults: 'target/surefire-reports/*.xml', allowEmptyResults: false
}
failure {
echo 'The tests failed: check the Test Result page of the build.'
}
}
}
stage('Dependency analysis') {
options {
timeout(time: 5, unit: 'MINUTES')
}
steps {
mavenTecnoShop goals: 'dependency:tree -DoutputFile=dependencies.txt', label: 'Dependency tree'
archiveArtifacts artifacts: 'dependencies.txt'
}
}
}
}
stage('Integration tests') {
when {
expression { params.RUN_TESTS }
}
options {
timeout(time: 10, unit: 'MINUTES')
}
steps {
mavenTecnoShop goals: 'failsafe:integration-test failsafe:verify', label: 'Integration tests'
}
post {
always {
junit testResults: 'target/failsafe-reports/TEST-*.xml', allowEmptyResults: false
}
}
}
stage('Quality analysis') {
when {
allOf {
branch 'main'
expression { params.RUN_TESTS }
}
}
options {
timeout(time: 10, unit: 'MINUTES')
}
steps {
withSonarQubeEnv('sonar-tecnoshop') {
mavenTecnoShop goals: 'sonar:sonar', label: 'SonarQube analysis'
}
}
}
stage('Quality Gate') {
when {
allOf {
branch 'main'
expression { params.RUN_TESTS }
}
}
options {
timeout(time: 5, unit: 'MINUTES')
}
steps {
waitForQualityGate abortPipeline: true
}
}
stage('Package') {
steps {
mavenTecnoShop '-DskipTests package'
infoBuild application: 'orders-api', version: env.APP_VERSION, image: "${env.IMAGE}:${env.IMAGE_TAG}"
archiveArtifacts artifacts: 'target/*.jar,build-info.txt', fingerprint: true
stash name: 'jar', includes: 'target/*.jar'
}
}
stage('Smoke') {
options {
timeout(time: 3, unit: 'MINUTES')
}
steps {
smokeSpringBoot extraPath: '/api/orders', expectedText: 'SHIPPED'
}
}
stage('Publish') {
when {
allOf {
expression { params.RUN_TESTS }
anyOf {
allOf {
branch 'main'
expression { env.APP_VERSION.endsWith('-SNAPSHOT') }
}
tag pattern: 'v\\d+\\.\\d+\\.\\d+', comparator: 'REGEXP'
}
}
}
options {
timeout(time: 5, unit: 'MINUTES')
}
steps {
sh label: 'Check that the tag matches the version', script: '''
if [ -n "${TAG_NAME:-}" ] && [ "$TAG_NAME" != "v$APP_VERSION" ]; then
echo "ERROR: the tag $TAG_NAME does not match the pom version ($APP_VERSION)"
exit 1
fi
'''
mavenTecnoShop goals: '-DskipTests -Dmaven.install.skip=true deploy',
settings: 'maven-settings-tecnoshop-publish',
label: 'Publish to Nexus'
}
}
stage('Deploy to dev') {
when {
allOf {
branch 'main'
expression { params.ENVIRONMENT == 'dev' }
expression { params.RUN_TESTS }
}
}
options {
timeout(time: 5, unit: 'MINUTES')
}
environment {
DEV_SERVER = 'dev-01.tecnoshop.local'
}
steps {
unstash 'jar'
sshagent(credentials: ['ssh-dev']) {
sh label: 'Deploy to dev-01 over SSH', script: 'sh deploy/deploy.sh "$DEV_SERVER"'
}
}
}
}
post {
always {
notifyTeam channel: '#ci-orders', email: '[email protected]'
}
cleanup {
cleanWs()
}
}
}How orders-api evolved over the module:
| Lesson | What it contributed |
|---|---|
| 06-01 | No changes to the file: signed webhooks, GitHub App in github-tecnoshop, statuses and Checks, the protect-main rule, tag discovery |
| 06-02 | [email protected] and MAVEN_SETTINGS_ID: the maven-settings-tecnoshop managed settings in every Maven step |
| 06-03 | junit in post { always }, recordCoverage with thresholds and the Integration tests stage (JaCoCo and Failsafe in pom.xml) |
| 06-04 | Quality analysis and Quality Gate stages (main only), a 30-minute global timeout |
| 06-05 | Publish stage to Nexus (SNAPSHOTs from main, releases from tags) with maven-settings-tecnoshop-publish |
| 06-06 | A real Deploy to dev to dev-01 with sshagent and ssh-dev; updated parameter descriptions |
| 06-07 | [email protected] and notifyTeam in the post section |
And what surrounds the file, in the repository and on the platform: deploy/deploy.sh, deploy/known_hosts and deploy/orders-api.service; OrderControllerIT; the sonarqube, sonarqube-db and nexus services (and, optionally, smee-client, dev-01 and mailpit) in docker-compose.yml; and the github-tecnoshop (GitHub App), github-webhook-secret, sonar-token, sonar-webhook-secret, nexus-deployer, registry-tecnoshop, ssh-dev and slack-token credentials.
Common Mistakes and Tips
- Notifying on every build of every branch: within a week the channel gets muted and the important notice is lost.
slackSendresponds withnot_in_channel(or similar) in the console: the bot has not been invited to the channel.invalid_auth: the token inslack-tokenbelongs to another app, has been revoked or is not a bot token (xoxb-), or Custom slack app bot user is not checked.- Emails do not reach the authors of the changes: the Git authors are not resolving to addresses; check the Default user e-mail suffix and the Jenkins users. Check in Mailpit who the email was actually sent to.
- Using double quotes with Email Extension tokens (
"${BUILD_LOG, maxLines=40}"): Groovy tries to interpret it and the build fails. - A notification that makes the build fail: without
try/catch(orcatchError), a Slack outage turns successful builds red.notifyTeamalready takes care of this. - Storing a Teams webhook URL in the
Jenkinsfile: anyone with access to the repository could post to the channel. It is a secret. - Messages without a link: they force people to look for the build by hand. Every notice must include
BUILD_URL. - Tip: review the notification rules with the team after a month. If someone has muted the channel, the problem is not that person: it is the rules.
Exercises
Exercise 1. Set up Mailpit, configure Email Extension and release tecnoshop-lib v1.3.0 with its tests. In orders-api, produce this sequence on main: a green build, a failure (break a test through a PR and merge it), another failure (a commit that does not fix it) and the fix. For each build, state what notifyTeam writes to the console and what you receive in Slack and in Mailpit.
Exercise 2. The catalog-web team asks to also get a Slack notice when one of their PRs fails, "so we find out sooner". Write Laura's reply, with an alternative.
Exercise 3. Extend notifyTeam with an optional deployChannel parameter: if it is given and the main build ends green and the Deploy to dev stage has run, it posts an informational message with the deployed version to that channel. What version number does the library get? Hint: the step can check env.APP_VERSION and env.BUILD_NUMBER, but how does it know whether a deployment happened?
Solutions
Solution 1. (1) Green build after green: notifyTeam: SUCCESS after SUCCESS; nothing to notify; nothing in Slack or Mailpit. (2) First failure: notifyTeam: FAILED → Slack #ci-orders and email; in Slack, a red message "orders-api/main #N: started failing" with the links; in Mailpit, an email with the subject [Jenkins] orders-api/main #N: started failing, addressed to [email protected] and to the authors of the changes (if they resolve), with the compressed log attached. (3) Second failure: notifyTeam: STILL_FAILING → Slack #ci-orders; a red "still failing" message and no email. (4) Fix: notifyTeam: FIXED → Slack #ci-orders; a green "is back to green" message. The builds of the intermediate PRs write branch 'PR-N' does not notify the team. If you do not have Slack, you will see the caught notice in the console (could not notify Slack) and the build result does not change: that is the try/catch at work.
Solution 2. "I understand the need, but a notice in the channel for every red PR would turn #ci-catalog into the whole team's work log: PRs fail many times while they are being developed, and the notice that matters (that main is broken) would get buried. The author of each PR already gets the result in GitHub, in the PR itself, with the Jenkins check, the Tests check with the failed tests and the link to the build; and GitHub notifies them according to their preferences (email, mobile app or the GitHub integration for Slack, which can send each person their own notifications by direct message). If someone wants to find out sooner, I recommend enabling notifications for checks on their PRs in GitHub. The channel stays for what affects everyone: main."
Solution 3. It is a new, compatible feature (an optional parameter): v1.4.0. The step cannot tell on its own which stages have run, so the simplest and most explicit way is for the deployment stage to say so. For example, at the end of Deploy to dev, an environment variable with env.DEPLOYED_TO = 'dev-01.tecnoshop.local' (in declarative syntax, inside a small script block, or in a library step that deploys and sets it). In notifyTeam, after the branch filter:
if (config.deployChannel && currentBuild.currentResult == 'SUCCESS' && env.DEPLOYED_TO) {
try {
slackSend(channel: config.deployChannel, color: '#439FE0',
message: "orders-api ${env.APP_VERSION}-${env.BUILD_NUMBER} deployed to ${env.DEPLOYED_TO} · <${env.BUILD_URL}|build>")
} catch (Exception e) {
echo "notifyTeam: could not announce the deployment (${e.message})"
}
}The message goes to a channel different from the notices channel (for example, #dev-deployments), with a neutral color, because it is information and not a call to action. Before releasing, add a JenkinsPipelineUnit test that checks that it is sent when DEPLOYED_TO is defined and not sent without it. (Instead of a hard-coded orders-api, the step should use an application parameter or the job name, so that it works for any project.)
Conclusion
With this lesson you close module 6, and the result of every build reaches whoever has to act. TecnoShop's rules notify only what is actionable and only from main (a new failure by Slack and email; a repeated failure, degradation and recovery by Slack; nothing when everything stays green), while PRs get their feedback in GitHub through the statuses and Checks from 06-01. You know how to configure email with Email Extension and its SMTP server (with Mailpit in the lab), compute recipients with culprits(), developers() and requestor() and tell Groovy interpolation apart from the plugin's tokens; post to Slack with your own app, the slack-token credential and slackSend, including threads and updates; and send cards to Microsoft Teams with Workflows webhooks, now that Office 365 connectors are being retired. All those decisions live in a single tested step, notifyTeam, in tecnoshop-lib v1.3.0, used by orders-api and catalog-web. With the module complete, Jenkins is integrated with TecnoShop's whole ecosystem: GitHub triggers builds through events and receives their status; Maven, Gradle and npm build with managed configuration; JUnit, JaCoCo and Jest report on tests and coverage; SonarQube watches over the quality of main; Nexus stores dependencies and immutable artifacts; SSH takes each version to dev-01; and Slack and email keep the team informed. You have all the pieces of an integration and delivery chain; what is missing is designing it with intent, understanding what integrating, delivering and deploying continuously really means and which practices make it possible. That is the starting point of module 7, in Understanding CI/CD.
