The tests from the previous lesson answer the question "does the code do what it should?". But code can pass all its tests and still have a NullPointerException waiting on a path nobody tests, a query vulnerable to injection, methods copied and pasted across three classes or a level of complexity that will make the next change cost twice as much. Catching all that by hand, in every PR review, is impossible to sustain. SonarQube analyzes code statically (without running it), checks it against thousands of rules and decides, with a Quality Gate, whether the code meets the required standard. In this lesson you will bring up SonarQube in the lab, connect it to Jenkins with the SonarQube Scanner plugin, analyze orders-api and catalog-web with their coverage, make the pipeline wait for the Quality Gate verdict without tying up resources, and learn what each SonarQube edition allows and which alternatives or complements exist.
What SonarQube Is and What It Measures
SonarQube is a static analysis platform: a scanner goes through the source code (and, in Java, the compiled code), applies language-specific rules and sends the results to a server, which stores them, computes metrics and displays them in a web interface.
| Concept | What it is | Example in orders-api |
|---|---|---|
| Bug (reliability issue) | Code that is likely to misbehave | Calling .get() on an Optional without checking whether it has a value |
| Vulnerability (security issue) | Code that an attacker could exploit | Building an SQL query by concatenating a request parameter |
| Security Hotspot | Sensitive code that a person must review to decide whether it is safe | Disabling CSRF protection, using a non-cryptographic random generator |
| Code smell (maintainability issue) | Code that works, but is hard to maintain | A 200-line method, an unused variable, an empty catch |
| Duplication | Repeated blocks of code | The same validation copied into three controllers |
| Coverage | Percentage of code executed by the tests | The figure SonarQube imports from the JaCoCo report; it does not measure it itself |
| Technical debt | Estimated time to fix all maintainability issues | "2h 30min" |
Recent versions group these issues by software quality (reliability, security, maintainability) and by severity, and give each quality a rating from A to E. The exact names of some metrics have changed between versions; the idea is the same.
Quality Profiles, Quality Gates and "Clean as You Code"
Three concepts govern how SonarQube judges a project:
- Quality Profile: the set of rules active for a language. SonarQube ships with a default profile for each language, called Sonar way. An organization can create its own based on it (enabling or disabling rules, changing their severity).
- Quality Gate: a set of conditions the analysis must meet to be considered acceptable, for example "coverage on new code is at least 70%". The result is binary: Passed or Failed. It is what Jenkins will query.
- New Code: the part of the code added or modified since a reference point (the previous version, a number of days or a reference branch).
The philosophy SonarQube calls Clean as You Code consists of applying the demanding conditions only to new code. If orders-api had 500 legacy issues, requiring zero issues across the whole project would block the team for months; requiring that what is new be clean blocks nobody and, over time, the old code gets replaced or fixed. It is the same idea as the MODIFIED_LINES threshold you saw with the Coverage plugin in 06-03.
flowchart LR
S["Scanner on the agent<br/>(Maven or sonar-scanner)"] -->|"sends the report"| Q["SonarQube server"]
Q --> CE["Background processing<br/>(Compute Engine)"]
CE --> P["Quality Profile:<br/>which rules are broken?"]
P --> G["Quality Gate:<br/>are the conditions met<br/>on new code?"]
G -->|"webhook with the result"| J["Jenkins:<br/>waitForQualityGate"]
Notice that the analysis has two phases: the scanner finishes as soon as it sends the report, but the server processes it afterward, in the background. That is why the pipeline needs to wait for the result, as you will see later.
SonarQube Editions
| Edition | License | What matters most for Jenkins |
|---|---|---|
| SonarQube Community Build | Free, open source | Analysis of a single branch per project; no PR analysis or PR decoration |
| SonarQube Server Developer Edition | Paid | Branch and PR analysis, PR decoration on GitHub/GitLab/Bitbucket/Azure DevOps, more languages and deeper security analysis |
| Enterprise and Data Center | Paid | Portfolio management, reports, high availability |
| SonarQube Cloud (formerly SonarCloud) | Cloud service, free for public projects | The same as a service, with no server of your own |
The names and what each edition includes have changed several times in recent years; check the official page before making purchasing decisions. In the lab you will use Community Build, and its limitations will shape how it is integrated into the pipelines.
SonarQube in the Lab: The sonarqube and sonarqube-db Services
At TecnoShop, SonarQube lives at https://sonar.tecnoshop.local. In your lab you will add it to the docker-compose.yml in ~/tecnoshop-jenkins, and inside the Compose network it will be http://sonarqube:9000.
Resources. SonarQube includes a search engine (Elasticsearch) and needs at least about 2 GB of free RAM, plus whatever PostgreSQL uses. Added to Jenkins, the agent and the monitoring stack from 05-05, a laptop with 8 GB will be very tight. If you do not need it at a given moment, stop it with
docker compose stop sonarqube sonarqube-db.
Host System Requirements
Elasticsearch requires the kernel to allow many memory-mapped areas. On the Linux host (not inside the container):
sudo sysctl -w vm.max_map_count=524288
sudo sysctl -w fs.file-max=131072
echo -e "vm.max_map_count=524288\nfs.file-max=131072" | sudo tee /etc/sysctl.d/99-sonarqube.confsysctl -w: changes the value right away.- The file in
/etc/sysctl.d/makes the change survive a reboot. - With Docker Desktop (macOS or Windows), these values belong to Docker's virtual machine; check its documentation if SonarQube does not start for this reason.
If the setting is missing, the container stops and its log shows a message such as max virtual memory areas vm.max_map_count [65530] is too low.
The Services
Add a password of your own for the database to .env (SONAR_DB_PASSWORD=...) and these services to docker-compose.yml:
sonarqube-db:
image: postgres:17 # a version supported by your SonarQube
container_name: sonarqube-db
restart: unless-stopped
environment:
POSTGRES_USER: sonar
POSTGRES_PASSWORD: ${SONAR_DB_PASSWORD}
POSTGRES_DB: sonar
volumes:
- sonarqube_db:/var/lib/postgresql/data
sonarqube:
image: sonarqube:community # pin a specific version, as in 05-04
container_name: sonarqube
restart: unless-stopped
depends_on:
- sonarqube-db
environment:
SONAR_JDBC_URL: jdbc:postgresql://sonarqube-db:5432/sonar
SONAR_JDBC_USERNAME: sonar
SONAR_JDBC_PASSWORD: ${SONAR_DB_PASSWORD}
ulimits:
nofile:
soft: 131072
hard: 131072
ports:
- "127.0.0.1:9000:9000"
volumes:
- sonarqube_data:/opt/sonarqube/data
- sonarqube_extensions:/opt/sonarqube/extensions
- sonarqube_logs:/opt/sonarqube/logs
volumes:
# ... the existing volumes ...
sonarqube_db:
name: sonarqube_db
sonarqube_data:
name: sonarqube_data
sonarqube_extensions:
name: sonarqube_extensions
sonarqube_logs:
name: sonarqube_logssonarqube-db: PostgreSQL, the database where SonarQube stores projects, analyses and configuration. Pin a version that appears in the requirements for your SonarQube version.SONAR_JDBC_URL: the database connection, using the service name on the Compose network.- Without an external database, SonarQube starts with an embedded H2 database. It is fine for a five-minute trial, but it does not support upgrades to new versions or migration to another database: everything you configure would be lost. Do not use it for anything you want to keep.
ulimits.nofile: the number of open files Elasticsearch needs."127.0.0.1:9000:9000": the interface is only reachable from your machine, like Prometheus and Grafana in 05-05. Jenkins and the agent reach SonarQube over the internal network, without going through this port.- The three SonarQube volumes keep the indexes, plugins and logs; the PostgreSQL one, the data.
Startup takes a minute or two. Wait until you see a line like SonarQube is operational.
First Login, the orders-api Project and the sonar-token Token
First Login
Open http://localhost:9000. The initial user is admin with the password admin, and SonarQube forces you to change it when you log in. Use a strong password and store it in your password manager.
In Administration → Configuration → General Settings → Security, check that Force user authentication is enabled (it is by default in current versions): without it, anyone with network access could see the analyzed code.
A Technical User for Jenkins
Just as in Jenkins with the metrics user from 05-05, Jenkins should not use a person's account:
- Administration → Security → Users → Create User: login
jenkins, nameJenkins TecnoShop, random password. - Administration → Security → Global Permissions: grant
jenkinsonly Execute Analysis. - Log in as
jenkinsand, in My Account → Security, generate a token: namejenkins-tecnoshop, type Global Analysis Token (it can analyze any project, but nothing else), expiring after 90 days. Copy the value (it starts withsqa_); it will not be shown again.
The orders-api Project
As admin: Projects → Create Project → Local project:
| Field | Value |
|---|---|
| Project display name | orders-api |
| Project key | orders-api |
| Main branch name | main |
| New code definition | Previous version |
- Project key: the unique identifier the scanner will use. You will set it in
pom.xml. - Previous version: new code is everything changed since the project version (the one in
pom.xml) last changed. It fits the TecnoShop versioning you will see in 06-05.
SonarQube will offer you an analysis wizard ("How do you want to analyze your repository?"); you can close it. Create the catalog-web project the same way.
The Credential in Jenkins
Manage Jenkins → Credentials → Add Credentials:
| Field | Value |
|---|---|
| Kind | Secret text |
| Scope | Global |
| Secret | The sqa_... token |
| ID | sonar-token |
| Description | SonarQube: Global Analysis Token for the jenkins user. Expires after 90 days. Owner: Laura. |
The SonarQube Scanner Plugin and the sonar-tecnoshop Server
Install the SonarQube Scanner plugin (ID sonar) and add it to plugins.txt. Then, in Manage Jenkins → System → SonarQube servers:
- Check Environment variables: Enable injection of SonarQube server configuration as build environment variables.
- Add SonarQube:
| Field | Lab value | At TecnoShop |
|---|---|---|
| Name | sonar-tecnoshop |
sonar-tecnoshop |
| Server URL | http://sonarqube:9000 |
https://sonar.tecnoshop.local |
| Server authentication token | sonar-token |
sonar-token |
- Save.
- Name: the name the pipelines will use to refer to the server. If the URL ever changes, this is the only place to touch.
- Server URL: the address as seen from the agent, which is the one running the scanner. On the Compose network,
sonarquberesolves to the container.
Analyzing orders-api with withSonarQubeEnv
Properties in the pom.xml
Add to <properties>:
<sonar.projectKey>orders-api</sonar.projectKey>
<sonar.projectName>orders-api</sonar.projectName>
<sonar.coverage.jacoco.xmlReportPaths>${project.build.directory}/site/jacoco/jacoco.xml</sonar.coverage.jacoco.xmlReportPaths>
<sonar-maven-plugin.version>5.1.0.4751</sonar-maven-plugin.version>And, inside <build>, a <pluginManagement> block that pins the version of the SonarQube Maven plugin:
<pluginManagement>
<plugins>
<plugin>
<groupId>org.sonarsource.scanner.maven</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<version>${sonar-maven-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>sonar.projectKey: must match the project key in SonarQube. Without it, the Maven scanner would usegroupId:artifactId(com.tecnoshop:orders-api) and create a different project.sonar.coverage.jacoco.xmlReportPaths: where the JaCoCo XML report from 06-03 is. It is the default path, but writing it out makes it clear where coverage comes from. SonarQube does not run the tests: it imports the report.pluginManagement: pins the scanner version (the one in the example is indicative: check the latest). Without a version, Maven would pick one on its own and the build would not be reproducible.- No URL or token in
pom.xml: Jenkins provides them.
The sonar: Prefix in the Managed Settings
For Maven to understand the short sonar:sonar goal, the plugin's group must be listed in <pluginGroups>. Laura adds it to the maven-settings-tecnoshop managed file from 06-02, right after <interactiveMode>:
Without it, you would have to write the full name: org.sonarsource.scanner.maven:sonar-maven-plugin:sonar.
The Analysis Stage
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'
}
}
}withSonarQubeEnv('sonar-tecnoshop'): inside the block, Jenkins injects the server URL and the token as environment variables (SONAR_HOST_URL,SONAR_AUTH_TOKENand a variable with all the parameters the Maven scanner reads automatically). It also records in the build which analysis was launched, so thatwaitForQualityGatelater knows which result to wait for.mavenTecnoShop goals: 'sonar:sonar': runs the Maven scanner with the managed settings (throughMAVEN_SETTINGS_ID). The token does not appear on the command line or in the log.- The
sonar:sonargoal does not compile or run tests: it analyzes the source code, the compiled classes intarget/classes(fromBuild) and the JaCoCo report (fromTests), which are already in the workspace. That is why this stage comes after the tests. when { branch 'main' }: because of Community Build's limitations, which you will see in the section on branches and PRs.expression { params.RUN_TESTS }: without tests there is no coverage report, and the Quality Gate would fail for lack of coverage on new code.
At the end of the analysis, the console shows:
[INFO] ANALYSIS SUCCESSFUL, you can find the results at: http://sonarqube:9000/dashboard?id=orders-api [INFO] Note that you will be able to see the results only after the background task has been processed. [INFO] More about the report processing at http://sonarqube:9000/api/ce/task?id=AZ...fake
The second line confirms what we said: the result is not ready yet. The build page also shows a SonarQube link to the project dashboard (the internal URL; from your browser, use http://localhost:9000).
The SonarQube Webhook to Jenkins
When SonarQube finishes processing an analysis, it can notify Jenkins with a webhook, just like GitHub in 06-01. The endpoint is provided by the plugin: <Jenkins URL>/sonarqube-webhook/.
In SonarQube, Administration → Configuration → Webhooks → Create:
| Field | Lab value |
|---|---|
| Name | jenkins-tecnoshop |
| URL | http://jenkins-controller:8080/sonarqube-webhook/ |
| Secret | A random value (openssl rand -hex 32) |
- The URL uses the controller's name on the Compose network: there is no need for smee here, because SonarQube and Jenkins are on the same network. At TecnoShop it would be
https://jenkins.tecnoshop.local/sonarqube-webhook/. - The Secret lets Jenkins verify that the notification comes from SonarQube. Store it in Jenkins as a Secret text credential with System scope and ID
sonar-webhook-secret, and select it in Manage Jenkins → System → SonarQube servers → sonar-tecnoshop → Advanced → Webhook Secret. - Some SonarQube versions validate webhook URLs and reject local addresses; if yours rejects the URL, review the webhook validation option in SonarQube's security settings, bearing in mind that relaxing it is only reasonable in a lab.
After the next analysis, the webhook page (Last delivery) will show the delivery with a 200 response.
waitForQualityGate: Waiting for the Verdict
stage('Quality Gate') {
when {
allOf {
branch 'main'
expression { params.RUN_TESTS }
}
}
options {
timeout(time: 5, unit: 'MINUTES')
}
steps {
waitForQualityGate abortPipeline: true
}
}waitForQualityGate: waits for SonarQube to finish processing the analysis launched by the build's lastwithSonarQubeEnvand returns the Quality Gate result. If the webhook notification has already arrived, it responds immediately; if not, it waits for it.abortPipeline: true: if the Quality Gate is Failed, the step fails and the build ends in red. The following stages (Package,Smoke,Deploy to dev) do not run.timeoutis mandatory: if the webhook never arrives (misconfigured, SonarQube down), the step would wait forever. With 5 minutes, the build fails with a clear reason.
Why red and not yellow? According to the semantics from 06-03, yellow is "degraded, but can carry on". The Quality Gate is the quality contract TecnoShop requires of code that reaches main and gets deployed: if it is not met, the code must not move on to dev. If you wanted yellow, you could store the result (def qg = waitForQualityGate()) and call the unstable step when qg.status != 'OK', at the cost of a script block.
Where to Wait: The Lightweight Stage
While it waits, waitForQualityGate does not use CPU, but it does hold the executor if it runs inside an agent. The general recommendation is to wait outside an agent or in a stage with no heavy work:
- In
orders-api, the agent is declared at the pipeline level (05-01 explained why), so theQuality Gatestage holds the executor. That is acceptable because, with the webhook, the wait lasts seconds, and the 5-minutetimeoutbounds the worst case. What matters is that it is a separate, lightweight stage, with no other steps. - In
catalog-web, with a globalagent none, theQuality Gatestage declares no agent and holds no executor while it waits. It is the ideal pattern, and you will see it at the end of the lesson.
TecnoShop's Quality Gate
The default Quality Gate, Sonar way, is reasonable, but it cannot be edited (it is built-in). Laura creates her own:
- Quality Gates → Sonar way → Copy, named
TecnoShop. - Adjust the conditions on new code:
| Condition (on new code) | Threshold | Why |
|---|---|---|
| Coverage | Less than 70% → fails | Consistent with the recordCoverage line threshold |
| Duplicated lines | More than 3% → fails | Copy and paste is the source of bugs that get fixed in one place and not in another |
| Reliability rating | Worse than A → fails | No new bugs |
| Security rating | Worse than A → fails | No new vulnerabilities |
| Security Hotspots reviewed | Less than 100% → fails | Every piece of new sensitive code must be reviewed by a person |
| Maintainability rating | Worse than A → fails | New debt must be small |
- Assign it to both projects (Project Settings → Quality Gate) or mark it as Set as Default.
Metric names vary slightly by version (for example, "Issues" vs. per-quality ratings); choose the equivalents in yours. A SonarQube detail worth knowing: if the new code is very small (a few lines), the coverage and duplication conditions may be ignored to avoid absurd results, such as failing because one line out of two is not covered.
To try it out, Diego adds, on a branch, a method with an obvious bug that SonarQube detects, for example comparing two Strings with ==:
public boolean isShipped(Order order) {
return order.status() == "SHIPPED"; // Wrong: compares references, not content
}After it is merged into main, the analysis finds a new bug, the reliability rating of the new code drops below A, the Quality Gate fails and the main build ends red at the Quality Gate stage without deploying. The fix ("SHIPPED".equals(order.status())) turns it green again.
Notice that this bug reached main: with Community Build, analysis is only done on main, after merging. That is the main limitation, and we deal with it next.
catalog-web: sonar-project.properties and the Scanner
For projects that are neither Maven nor Gradle, you use the generic SonarScanner, configured with a sonar-project.properties file at the root of the repository:
sonar.projectKey=catalog-web
sonar.projectName=catalog-web
sonar.sources=src
sonar.tests=src
sonar.test.inclusions=src/**/*.test.js
sonar.exclusions=src/**/*.test.js
sonar.javascript.lcov.reportPaths=coverage/lcov.info
sonar.sourceEncoding=UTF-8sonar.sourcesandsonar.tests: where the code is and where the tests are. Incatalog-webthey live side by side insrc/.sonar.test.inclusions: which files insonar.testsare tests.sonar.exclusions: excludes the tests from the code analyzed as "source", so they do not count as uncovered code or as duplicates.sonar.javascript.lcov.reportPaths: the LCOV report Jest generates with thelcovreporter from 06-03.
The SonarQube Scanner Tool
Manage Jenkins → Tools → SonarQube Scanner installations → Add SonarQube Scanner: name sonar-scanner, Install automatically from Maven Central with a specific version. As with Node, it will be downloaded to the agent the first time.
An alternative is the scanner's npm package (@sonar/scan, runnable with npx), which avoids configuring a tool in Jenkins, at the cost of downloading code from npm on every build if it is not in the lockfile. TecnoShop prefers the Jenkins tool, with a pinned version.
The Stages
stage('Quality analysis') {
when {
branch 'main'
}
agent {
label 'linux'
}
options {
timeout(time: 10, unit: 'MINUTES')
}
environment {
SCANNER_HOME = tool 'sonar-scanner'
}
steps {
nodejs(nodeJSInstallationName: 'node-22', configId: 'npmrc-tecnoshop') {
sh 'npm ci --prefer-offline'
sh 'npm test'
withSonarQubeEnv('sonar-tecnoshop') {
sh '"$SCANNER_HOME/bin/sonar-scanner"'
}
}
}
post {
cleanup {
cleanWs()
}
}
}
stage('Quality Gate') {
when {
branch 'main'
}
options {
timeout(time: 10, unit: 'MINUTES')
}
steps {
waitForQualityGate abortPipeline: true
}
}SCANNER_HOME = tool 'sonar-scanner': thetoolstep installs the tool on the agent (if needed) and returns its path. Inside theenvironmentof a stage with an agent, it is evaluated on that agent.npm ciandnpm testagain: this stage has its own workspace, different from those of the matrix cells, and the analysis needs the code and thecoverage/lcov.inforeport. You could bring the report over from thenode-22cell withstash, but LCOV reports can contain paths specific to the workspace where they were generated, which would not match this one. Rerunning the tests costs a few seconds and is more robust.nodejs(...): JavaScript analysis needs Node on the agent (depending on the version, the scanner may bring its own; inside the block there is no doubt).sh '"$SCANNER_HOME/bin/sonar-scanner"': runs the scanner, which readssonar-project.propertiesand the variables injected bywithSonarQubeEnv. The double quotes protect the path.Quality Gatewith noagent: because the pipeline hasagent none, this stage holds no executor while it waits.waitForQualityGatedoes not need a workspace: the analysis was recorded in the build.
Branches and Pull Requests: What Each Edition Allows
| Need | Community Build | Developer Edition or higher (and SonarQube Cloud) |
|---|---|---|
Analyze main |
Yes | Yes |
| Analyze other branches | No: an analysis without a branch is stored as if it were the main one and overwrites its results | Yes, each branch separately |
| Analyze a PR before merging | No | Yes: the scanner detects the PR from the Jenkins variables (CHANGE_ID, CHANGE_TARGET...) |
| Comments and status on the GitHub PR (decoration) | No | Yes, by configuring the GitHub integration in SonarQube |
| Quality Gate on the PR | No | Yes |
Hence TecnoShop's decision: with Community Build, only main is analyzed (when { branch 'main' }). Analyzing PRs would be worse than not doing it: every analysis of one of Diego's branches would overwrite the state of main in SonarQube.
So what protects the PRs? The layers you already have: the tests, the recordCoverage coverage thresholds (which work on every branch and PR) and code review. And for each developer, the SonarQube for IDE extension (formerly SonarLint) shows the same issues in the editor as they type, and in "connected mode" it uses the server's Quality Profile. If TecnoShop buys a commercial edition, the change in Jenkins would be to remove the when { branch 'main' }: the plugin and the scanner detect on their own whether the build is for a branch or a PR.
There are community plugins that add branch analysis to Community Build. They are not official, they can stop working with any SonarQube upgrade and they have no support; TecnoShop does not use them.
Complements: Warnings Next Generation
The Warnings Next Generation plugin (warnings-ng) does not analyze code: it reads the reports of analysis tools that run in the build (Checkstyle, SpotBugs, PMD, ESLint, the Java compiler...) and displays them in Jenkins with trends, colorized code and thresholds.
recordIssues(
tools: [
checkStyle(pattern: 'target/checkstyle-result.xml'),
spotBugs(pattern: 'target/spotbugsXml.xml')
],
qualityGates: [[threshold: 1, type: 'NEW', criticality: 'UNSTABLE']]
)tools: each tool with its report (the Checkstyle and SpotBugs Maven plugins would have to run earlier in the build).qualityGateswithtype: 'NEW': the build becomes unstable if at least one new warning appears compared with the reference build. As with Coverage, the exact threshold syntax has changed between versions: use the Snippet Generator.
| Aspect | SonarQube | Warnings Next Generation |
|---|---|---|
| What it is | An analysis server with its own rules | A Jenkins plugin that visualizes reports from other tools |
| Infrastructure | Server and database | Nothing extra |
| Branches and PRs | Depends on the edition | On every branch and PR, comparing with a reference build |
| History and project view | Complete, outside Jenkins | Inside Jenkins, limited to the builds kept |
| Security, duplication, debt | Yes | Whatever the tools you run provide |
| Publishing to GitHub | Decoration (paid editions) | Checks with annotations (with GitHub Checks) |
| Typical use | The organization's quality platform | Fast warnings on every build; a complement to SonarQube Community |
At TecnoShop, recordIssues is the natural candidate for giving PRs the static analysis feedback that Community Build does not offer, once the team decides which tools to run in the build. Security analysis tools for dependencies and images are covered in DevSecOps: Security in the Pipeline.
The Pipelines with Quality Analysis
orders-api
The two new stages go after Integration tests and before Package:
flowchart LR
A["Build"] --> B["Checks<br/>Tests + Dependency analysis"]
B --> C["Integration tests"]
C --> D["Quality analysis<br/>(main only)"]
D --> E["Quality Gate<br/>(main only)"]
E --> F["Package"]
F --> G["Smoke"]
G --> H["Deploy to dev<br/>(main only)"]
- The analysis needs the compiled classes and the coverage report, so it goes after the tests.
- The Quality Gate goes before
Package: if the code does not meet the quality contract, it is neither packaged nor deployed.
With two more stages, the global 20-minute timeout falls short in the worst case (each stage has its own limit). Raise it in options:
options {
timestamps()
timeout(time: 30, unit: 'MINUTES')
buildDiscarder(logRotator(numToKeepStr: '30', artifactNumToKeepStr: '5'))
disableConcurrentBuilds()
preserveStashes(buildCount: 5)
}The rest of the Jenkinsfile does not change; you will see it in full when the module wraps up in 06-07.
catalog-web
catalog-web has changed over the last three lessons. This is its complete state:
@Library('[email protected]') _
pipeline {
agent none
options {
timestamps()
timeout(time: 30, unit: 'MINUTES')
buildDiscarder(logRotator(numToKeepStr: '30', artifactNumToKeepStr: '5'))
}
stages {
stage('Tests per Node version') {
matrix {
axes {
axis {
name 'NODE_VERSION'
values 'node-18', 'node-20', 'node-22'
}
}
agent {
label 'linux'
}
stages {
stage('Test') {
steps {
nodejs(nodeJSInstallationName: env.NODE_VERSION, configId: 'npmrc-tecnoshop') {
sh 'node --version && npm --version'
sh 'npm ci --prefer-offline'
sh 'npm test'
}
}
post {
always {
junit testResults: 'reports/junit.xml', allowEmptyResults: false
}
}
}
stage('Coverage') {
when {
environment name: 'NODE_VERSION', value: 'node-22'
}
steps {
recordCoverage(
tools: [[parser: 'COBERTURA', pattern: 'coverage/cobertura-coverage.xml']],
id: 'jest',
name: 'Coverage (Jest)',
qualityGates: [
[metric: 'LINE', baseline: 'PROJECT', threshold: 80.0, criticality: 'UNSTABLE']
]
)
}
}
}
post {
cleanup {
cleanWs()
}
}
}
}
stage('Build') {
agent {
label 'linux'
}
steps {
nodejs(nodeJSInstallationName: 'node-22', configId: 'npmrc-tecnoshop') {
sh 'npm ci --prefer-offline'
sh 'npm run build'
script {
def version = sh(script: 'node -p "require(\'./package.json\').version"',
returnStdout: true, label: 'Read the version from package.json').trim()
infoBuild application: 'catalog-web', version: version
}
}
archiveArtifacts artifacts: 'dist/**,build-info.txt', fingerprint: true
}
post {
cleanup {
cleanWs()
}
}
}
stage('Quality analysis') {
when {
branch 'main'
}
agent {
label 'linux'
}
options {
timeout(time: 10, unit: 'MINUTES')
}
environment {
SCANNER_HOME = tool 'sonar-scanner'
}
steps {
nodejs(nodeJSInstallationName: 'node-22', configId: 'npmrc-tecnoshop') {
sh 'npm ci --prefer-offline'
sh 'npm test'
withSonarQubeEnv('sonar-tecnoshop') {
sh '"$SCANNER_HOME/bin/sonar-scanner"'
}
}
}
post {
cleanup {
cleanWs()
}
}
}
stage('Quality Gate') {
when {
branch 'main'
}
options {
timeout(time: 10, unit: 'MINUTES')
}
steps {
waitForQualityGate abortPipeline: true
}
}
}
post {
success {
echo "OK: catalog-web #${env.BUILD_NUMBER} tested on Node 18, 20 and 22, built and analyzed."
}
failure {
echo "ERROR: catalog-web #${env.BUILD_NUMBER} failed. Check which stage or cell is red."
}
}
}- In
catalog-webthe analysis goes afterBuild: the artifact is not deployed yet, so there is nothing for the ordering to protect, and the per-Node-version tests (the project's most important feedback) arrive sooner. - The global
timeoutgoes up to 30 minutes for the same reason as inorders-api.
Common Mistakes and Tips
- SonarQube does not start and the log mentions
vm.max_map_count: the kernel setting on the host is missing. Not authorizedor401during the analysis: the token has expired, it was generated with another user or thejenkinsuser lacks Execute Analysis.waitForQualityGatewaits until thetimeout: the webhook is not arriving (mistyped URL, missing trailing slash, or Jenkins unreachable from SonarQube). Check Last delivery in SonarQube.waitForQualityGatewithout atimeout: if the webhook fails, the build hangs, holding an executor.- A
com.tecnoshop:orders-apiproject is created alongsideorders-api:sonar.projectKeyis missing frompom.xml. - 0% coverage in SonarQube while Jenkins has a report: the
sonar.coverage.jacoco.xmlReportPathspath does not match or the analysis ran before the tests (or in another workspace). - Analyzing PR branches with Community Build: each analysis overwrites the
mainone and SonarQube shows data that does not belong to the main branch. - Using the embedded H2 database "for now": there is no way to migrate later; all the configuration is lost.
- Tightening the Quality Gate on all code in a project with legacy debt: it blocks the team. Apply the conditions to new code.
- Tip: when the Quality Gate fails, link from the pipeline's error message to the project dashboard in SonarQube: the developer should reach the problem in one click.
Exercises
Exercise 1. Set up SonarQube in the lab, create the technical user, the sonar-token token, the sonar-tecnoshop server and the webhook, and add the stages to orders-api. Then disable the webhook in SonarQube and run a main build. What happens in the Quality Gate stage and how long does it take? Re-enable it.
Exercise 2. Introduce the isShipped method with the == comparison into orders-api main (along with a test that covers it, so that coverage is not the reason for the failure). State which stages run, which one fails, what gets published to GitHub and what Diego sees in SonarQube. Why did the bug reach main, and what would change with a paid edition?
Exercise 3. A colleague proposes removing when { branch 'main' } from the catalog-web analysis stage "to get analysis on every PR", without changing editions. Explain what would happen and propose an alternative that gives static analysis feedback on PRs with what is available.
Solutions
Solution 1. Without the webhook, the analysis finishes normally, but waitForQualityGate does not receive the notification that processing has completed. The step checks the task status when it starts (if it had already finished, it would respond at that point), but if the task was still being processed it sits waiting for a notification that never comes. After 5 minutes the stage timeout fires, the build ends red (in the console you will see the timeout interrupting the step) and Package, Smoke and Deploy to dev do not run. This is exactly the scenario the timeout exists for: without it, the build would hold the executor indefinitely. Once you re-enable the webhook, the next build gets through the stage in seconds.
Solution 2. In the main build, Build, Checks, Integration tests and Quality analysis run; the Quality Gate stage fails with abortPipeline: true and the following ones are skipped, so there is no deployment to dev. GitHub receives the failed status for the main commit (and the Jenkins check shows the stage where it failed). In SonarQube, Diego sees on the orders-api dashboard the Quality Gate as Failed, the reliability condition on new code not met and the bug on the isShipped line, with the rule's explanation (comparing strings with == compares references). The bug reached main because Community Build only analyzes the main branch, after merging; the PR passed the tests, coverage and review. With Developer Edition, the PR would have been analyzed before merging, SonarQube would have commented on the problem in the PR itself and its Quality Gate, required by the main protection rule, would have prevented the merge.
Solution 3. Without changing editions, every PR build would send its analysis as if it were the main branch: the catalog-web dashboard in SonarQube would show the state of the last PR analyzed (perhaps one that never gets merged), new code and trends would get mixed up, and the main Quality Gate would stop being reliable. Moreover, if two PRs were analyzed one after the other, the result would depend on the order. Alternative: keep the SonarQube analysis on main only and add to every branch a fast analysis with a tool that runs in the build, such as ESLint with an output format Warnings Next Generation understands, published with recordIssues and a threshold on new warnings that marks the build as unstable. That way PRs get static feedback in Jenkins and in GitHub (with GitHub Checks), and SonarQube remains the reference for main. In the medium term, if the value justifies it, the commercial edition solves the problem at its root.
Conclusion
TecnoShop now measures the quality of its code as well as its behavior. You know what SonarQube analyzes (bugs, vulnerabilities, Security Hotspots, code smells, duplication, imported coverage and technical debt), how it judges it with Quality Profiles and Quality Gates and why the Clean as You Code philosophy applies the requirements to new code. In the lab, SonarQube Community Build runs as the sonarqube service with PostgreSQL in sonarqube-db, reachable by Jenkins at http://sonarqube:9000 (at TecnoShop, sonar.tecnoshop.local), with a technical user and the sonar-token credential. The SonarQube Scanner plugin defines the sonar-tecnoshop server; orders-api is analyzed with withSonarQubeEnv and the Maven scanner through mavenTecnoShop, sending JaCoCo coverage, and catalog-web with sonar-project.properties, the sonar-scanner tool and its LCOV report. The /sonarqube-webhook/ webhook lets waitForQualityGate receive the verdict of the TecnoShop Quality Gate in a lightweight stage, with a timeout and stopping the pipeline if it fails. You know that Community Build only analyzes main, what the paid editions add for branches and PRs, and how Warnings Next Generation can complement it. The code on main is now tested and analyzed before it is packaged; the next step is to stop keeping its artifacts only in the Jenkins history and publish them to a repository built for the purpose, in Artifact and Image Repositories.
