Configure SonarQube quality gates and custom rules for enterprise code analysis

Intermediate 45 min Apr 24, 2026 138 views
Ubuntu 24.04 Debian 12 AlmaLinux 9 Rocky Linux 9

Set up SonarQube quality gates with custom conditions and coding rules to enforce enterprise-grade code quality standards. Configure LDAP authentication and integrate with CI/CD pipelines for automated code analysis workflows.

Prerequisites

  • SonarQube server installed and running
  • Administrator access to SonarQube
  • LDAP server for authentication (optional)
  • CI/CD pipeline access

What this solves

SonarQube quality gates and custom rules provide automated code quality enforcement across your development teams. This tutorial shows how to configure quality gates with specific conditions, create custom coding rules, and integrate with enterprise authentication systems like LDAP for scalable code analysis workflows.

Understanding SonarQube quality gate architecture

Quality gates in SonarQube act as checkpoints that determine whether code meets your quality standards. They evaluate metrics like code coverage, technical debt, security vulnerabilities, and maintainability ratings against configurable thresholds.

The architecture consists of three main components: quality profiles (rule sets), quality gates (pass/fail conditions), and projects (code being analyzed). Quality profiles define which rules to apply during analysis, while quality gates evaluate the results against your acceptance criteria.

Note: This tutorial assumes you have SonarQube already installed. If you need installation guidance, see our SonarQube installation tutorial.

Step-by-step quality gate configuration

Access SonarQube administration

Log in to SonarQube with administrator privileges and navigate to the administration section.

https://your-sonarqube-server:9000/admin

Click on "Quality Gates" in the left sidebar to access quality gate management.

Create a custom quality gate

Create a new quality gate tailored to your organization's requirements.

In the Quality Gates interface, click "Create" and name your gate (e.g., "Enterprise Standard"). This creates a baseline quality gate that you can customize with specific conditions.

Configure quality gate conditions

Add conditions that define when code passes or fails quality checks.

Click "Add Condition" and configure the following enterprise-standard conditions:

  • Coverage: Less than 80% fails
  • Duplicated Lines (%): Greater than 3% fails
  • Maintainability Rating: Worse than A fails
  • Reliability Rating: Worse than A fails
  • Security Rating: Worse than A fails
  • Security Hotspots Reviewed: Less than 100% fails

Set up branch-specific conditions

Configure different conditions for different branch types in your development workflow.

For main/master branches, use stricter conditions:

  • New Code Coverage: Less than 90% fails
  • New Vulnerabilities: Greater than 0 fails
  • New Bugs: Greater than 0 fails

For feature branches, use more lenient conditions to allow iterative development while maintaining quality standards.

Creating custom coding rules

Access quality profiles

Navigate to quality profiles to create custom rule sets for different programming languages.

Go to Administration > Quality Profiles and select the language profile you want to customize (e.g., "Sonar way" for Java).

Create custom quality profile

Create a copy of the default profile to customize without affecting the baseline.

Click the dropdown next to your target profile and select "Copy". Name it "Enterprise [Language]" (e.g., "Enterprise Java"). This creates an independent profile you can modify.

Configure custom rule parameters

Modify existing rules and add custom parameters to match your coding standards.

In your custom profile, click "Activate More" to browse available rules. Search for specific rules like "Cognitive Complexity" and modify the threshold from 15 to 10 for stricter complexity requirements.

For naming convention rules, configure patterns that match your organization's standards:

  • Class names: PascalCase with specific prefixes
  • Method names: camelCase with descriptive verbs
  • Constants: UPPER_SNAKE_CASE

Create rule templates

Use rule templates to create organization-specific rules that can't be achieved with existing rules.

Navigate to Rules > Rule Templates and search for relevant templates. For example, use the "Track uses of forbidden classes" template to prevent use of deprecated or internal APIs specific to your codebase.

Click "Create" on a template and configure:

  • Rule name: "Forbidden legacy API usage"
  • Class pattern: "com\.yourcompany\.legacy\..*"
  • Severity: Major

Enterprise LDAP integration

Configure LDAP authentication

Set up LDAP integration to manage users centrally through your enterprise directory.

Navigate to Administration > Configuration > Security and scroll to the LDAP section.

sonar.security.realm=LDAP
ldap.url=ldap://your-ldap-server:389
ldap.bindDn=cn=sonar,ou=services,dc=yourcompany,dc=com
ldap.bindPassword=your-service-account-password
ldap.user.baseDn=ou=users,dc=yourcompany,dc=com
ldap.user.request=(&(objectClass=user)(sAMAccountName={login}))
ldap.user.realNameAttribute=displayName
ldap.user.emailAttribute=mail
ldap.group.baseDn=ou=groups,dc=yourcompany,dc=com
ldap.group.request=(&(objectClass=group)(member={dn}))

Map LDAP groups to SonarQube permissions

Configure group mappings to automatically assign permissions based on LDAP group membership.

In Administration > Security > Groups, create groups that match your LDAP structure:

  • "sonar-developers" group: Browse, Execute Analysis
  • "sonar-leads" group: Administer Issues, Administer Security Hotspots
  • "sonar-admins" group: Administer System

Test LDAP integration

Verify that LDAP authentication works correctly before deploying to production.

Log out of SonarQube and attempt to log in with an LDAP user account. Check that group memberships are correctly synchronized by viewing the user's permissions in Administration > Security > Users.

CI/CD pipeline integration

Configure project analysis

Set up projects to use your custom quality gates and profiles.

For each project, go to Project Settings > Quality Gate and select your "Enterprise Standard" quality gate. In Quality Profiles, assign your custom language profiles.

Generate authentication tokens

Create service account tokens for CI/CD integration.

Navigate to your user profile > Security and generate a new token named "CI-Pipeline-Token". Store this securely in your CI/CD system's secret management.

Configure pipeline integration

Add SonarQube analysis to your build pipeline with quality gate checking.

pipeline {
    agent any
    stages {
        stage('SonarQube Analysis') {
            steps {
                script {
                    def scannerHome = tool 'SonarScanner'
                    withSonarQubeEnv('SonarQube') {
                        sh "${scannerHome}/bin/sonar-scanner"
                    }
                }
            }
        }
        stage('Quality Gate') {
            steps {
                timeout(time: 1, unit: 'HOURS') {
                    waitForQualityGate abortPipeline: true
                }
            }
        }
    }
}

Configure GitLab CI integration

For GitLab environments, add SonarQube scanning to your .gitlab-ci.yml file.

sonarqube-check:
  stage: test
  image:
    name: sonarsource/sonar-scanner-cli:latest
    entrypoint: [""]
  variables:
    SONAR_USER_HOME: "${CI_PROJECT_DIR}/.sonar"
    GIT_DEPTH: "0"
  cache:
    key: "${CI_JOB_NAME}"
    paths:
      - .sonar/cache
  script:
    - sonar-scanner
  only:
    - merge_requests
    - master
    - develop

Advanced rule customization

Configure language-specific rules

Customize rules for different programming languages based on your technology stack.

For Java projects, activate rules for:

  • Spring Framework best practices
  • JUnit test quality
  • Microservices patterns

For JavaScript/TypeScript projects, focus on:

  • ESLint integration
  • React/Angular specific patterns
  • Security vulnerabilities in dependencies

Set up custom metrics

Define custom metrics that align with your organization's quality objectives.

Create custom rules for:

  • Architecture compliance (layer separation)
  • Logging standards enforcement
  • Exception handling patterns
  • Performance anti-patterns

Configure rule inheritance

Set up profile inheritance to maintain consistency across related projects.

Create a base "Enterprise Common" profile with universal rules, then extend it with language-specific profiles. This ensures consistent application of core quality standards while allowing language-specific customizations.

Monitoring and reporting

Set up quality gate webhooks

Configure webhooks to notify teams when quality gates fail.

In Administration > Configuration > Webhooks, add endpoints for:

  • Slack notifications for quality gate failures
  • Email alerts for security vulnerabilities
  • Integration with your ticketing system for technical debt tracking

Create quality dashboards

Set up project portfolios to track quality metrics across your organization.

Navigate to Projects and create portfolios grouped by:

  • Business domain
  • Technology stack
  • Development team

This provides executive-level visibility into code quality trends and allows for data-driven quality improvement initiatives.

Verify your setup

curl -u admin:admin http://localhost:9000/api/qualitygates/list
curl -u admin:admin http://localhost:9000/api/qualityprofiles/search

Check that your quality gate appears in the list and your custom quality profiles are available. Test the LDAP integration by attempting to log in with an LDAP user account.

Run a test analysis on a sample project to verify that your custom rules and quality gate conditions are properly applied:

sonar-scanner \
  -Dsonar.projectKey=test-project \
  -Dsonar.sources=. \
  -Dsonar.host.url=http://localhost:9000 \
  -Dsonar.login=your-token

Common issues

SymptomCauseFix
Quality gate not applied to projectDefault gate still assignedGo to Project Settings > Quality Gate and select custom gate
LDAP users cannot log inIncorrect LDAP configurationCheck bindDn credentials and user baseDn path
Custom rules not appearingRule not activated in quality profileGo to Quality Profiles and activate the custom rule
Pipeline fails quality gate incorrectlyCondition thresholds too strictReview and adjust condition values in quality gate settings
Webhook notifications not sentWebhook URL unreachableTest webhook endpoint and verify network connectivity

Next steps

Running this in production?

Want this handled for you? Setting this up once is straightforward. Keeping it patched, monitored, backed up and performant across environments is the harder part. See how we run infrastructure like this for European teams.

Need help?

Don't want to manage this yourself?

We handle managed devops services for businesses that depend on uptime. From initial setup to ongoing operations.