SonarQube Code Quality Analysis with Maven & CI Pipeline
Connecting Maven Project to SonarQube
- Edit pom.xml → locate the
<properties> block.- Key properties to add / modify:
sonar.host.url → URL of the SonarQube server.- Example (private IP):
http://10.0.0.15:9000/ - Example (public IP):
http://54.88.24.7:9000/
sonar.login → user-name or authentication token.sonar.password → plain password (only if not using a token).
- Three items that must be correct before analysis runs:
- URL.
- Username / token.
- Password (omit when token is used).
- Recommended security practice: create a dedicated SonarQube user (non-root) and generate a personal access token.
- Token replaces the line; comment it out or delete it.
Running Static Code Analysis with Maven
- Core command (inside the project directory):
mvn sonar:sonar - Common extended form:
mvn clean package sonar:sonar > log.txt clean – deletes previous artifacts.package – compiles, tests, produces JAR/WAR.sonar:sonar – pushes data to SonarQube.- Output is piped to log.txt for later inspection.
- Expected console messages:
- “Analysis successful” → link to dashboard is shown.
- On authentication failure: “Please check the properties sonar.login and sonar.password”.
SonarQube Result Metrics (Dashboard)
- Coverage on new code < 80\% ➔ fails quality gate.
- Duplicated lines on new code > 3\% ➔ flagged.
- Maintainability, Reliability, Security ratings (A‒E scale).
- Default widgets: Bugs, Vulnerabilities, Code Smells, Hotspots, etc.
Core Terminology
- Rule: atomic, test-like definition that detects a specific problem (bug, smell, vulnerability, duplication).
- Quality Profile: collection of rules applied during analysis. Every language gets one default profile (Sonar Way).
- Quality Gate: set of conditions evaluated after analysis; determines Pass / Fail for the entire project.
Building a Custom Quality Profile (“Tesla” example)
- Navigation: Quality Profiles ▸ Create.
- Inputs supplied:
- Name:
Tesla-QP. - Language: Java (no parent profile).
- Activate desired rules and define severity:
- Bug-detection rules → Major or Blocker.
- Code smell rules → Minor.
- Vulnerability rule → Blocker.
- Make it default for the language (Set as Default).
- Re-run
mvn sonar:sonar to see dashboard switch from Sonar Way to Tesla-QP.
Creating a Quality Gate (“Tesla-Quality-Gate”)
- Quality Gates ▸ Create ➔ add multiple conditions:
- Coverage on new code < 90\% → FAIL.
- Duplicated lines on new code > 5\% → FAIL.
- Bugs > 2 → FAIL.
- Code Smells > 5 → FAIL.
- Unit-test success rate < 95\% → FAIL.
- After saving, mark gate as default so all future analyses use it automatically.
Authentication & User Management
- Default admin credentials:
admin / admin. - Process for safer access:
- Administration ▸ Security ▸ Users → create new user
class31 with minimal privileges (Sonar Users group only). - Generate token (My Account ▸ Security ▸ Generate Token).
- Token is a concatenation of username & password, e.g.
sqp_ab12cd34ef56....
- Update
pom.xml with <sonar.login>token</sonar.login> and remove password line.
- Promotion / demotion of privileges is instantaneous:
- Adding user to Sonar Administrators shows Administration tab on next refresh.
Troubleshooting Common Failures
- Bad token → build stops at
Failed to execute goal ... check sonar.login. - Running
mvn package clean (wrong order) will build then delete artifacts—avoid. - Forgetting to comment out
<sonar.password> when token is used can cause confusion (empty pwd sent).
SonarQube vs. SonarCloud
| Aspect | SonarQube | SonarCloud |
|---|
| Hosting Model | Self-hosted server (IaaS) | SaaS (no server needed) |
| Port | 9000 (default) | N/A (managed) |
| Use-case | On-prem, private code, strict compliance | Public repos, quick start, no infra overhead |
| Integration | Any SCM / CI | GitHub, Azure DevOps, Bitbucket, GitLab |
CI/CD Pipeline Overview (Narrative)
- Developer push to GitHub.
- Jenkins triggers via Poll-SCM or Webhook.
- Clone & Build with Maven (
clean package). - Static Analysis – Jenkins calls SonarQube or SonarCloud.
- Artifact Backup – upload to Nexus or JFrog Artifactory before deploy.
- Deploy WAR/JAR to App Server (Tomcat / JBoss).
- Monitoring & Alerts – integrate New Relic; if metrics degrade, send Email or Slack notifications.
Security & Best Practices
- Run SonarQube service under dedicated Unix account (not
root). - Command example:
sudo useradd --system sonar.
- Never embed plain admin credentials in SCM; use tokens or encrypted secrets.
- Agree on thresholds with stakeholders (industry baseline + company ambition).
- Regularly review Quality Profiles & Gates to prevent rule fatigue.
Interview & Real-World Talking Points
- Storyline: introduced SonarQube into legacy project ➔ initial resistance ➔ fewer production rollbacks ➔ higher developer pride.
- Rationale for choosing SonarQube over SonarCloud:
- Need on-prem data residency / security.
- Custom plugins or language analyzers not supported in SaaS.
- Full control over upgrades & downtime windows.
- Explain pipeline stages and how static analysis acts as gatekeeper before deployment.
Forward-Looking Topics Mentioned
- Next tool: Nexus repository manager (Saturday video homework).
- Upcoming: Jenkins deep-dive, Artifactory, Kubernetes, advanced monitoring.
Practical Tips Recap
- Use
mvn clean package sonar:sonar for one-line test, build & analysis. - Dashboard checks: verify Quality Profile & Quality Gate names match expectations each run.
- Tokens are one-time view; copy immediately and store securely.
- Always validate token by re-running analysis before committing to SCM.