This SonarCloud tutorial is a complete guide to Static Code Analysis using SonarCloud. You will also understand how to Integrate SonarCloud with Jenkins and GitHub:
What is SonarCloud?
SonarCloud is a cloud-based static code analysis tool that developers use to perform automated analysis and detect coding issues. It supports 26 different programming languages. With SonarCloud, like other SAAS platforms, you need not worry about infra-hosting the software.
Clean code is still the key here to eliminate bugs, security vulnerabilities, code smells, etc. SonarCloud like SonarQube is used in the early stages of development to identify bugs and help developers fix them. It also finds other issues and ensures clean code goes into production deployment.
Table of Contents:
SonarCloud Tutorial – Static Code Analysis
How to Sign up for Sonarcloud
Teams can sign up for SonarCloud from SonarCloud Sign Up | Sonar (sonarsource.com). When you sign up, you will first need to select your Cloud DevOps platform such as Github, Bitbucket, GitLab, or Azure DevOps where the code resides.
For this SonarCloud tutorial, I am using my Maven project where the code resides in GitHub.com, and will integrate SonarCloud with it for performing static code analysis.
In this SonarCloud tutorial you will see the following:
- Integrate SonarCloud with GitHub and connect to an Organization
- Install the SonarCloud App in the GitHub Organization
- Setup Automatic Analysis to analyze the default branches and pull requests
- Add Quality Gate to the GitHub repository as a check which will prevent merging the pull request
- Manual static analysis of the code from the command line
- Integrate SonarCloud with Jenkins
SonarCloud Pricing
Most of the SAAS product plans and pricing are either based on the number of users or storage.
In SonarCloud the plans and pricing are based on the number of Lines of Code (LOC) up to 20 Million lines of code. The details on pricing of different slabs of LOC can be found at Plans & Pricing | Sonar (sonarsource.com) which will be something like shown below.
Suggested Read =>> Best DevOps Service Provider Companies and Consulting Firms
Integrate SonarCloud Project With GitHub
As mentioned, my code resides in GitHub. Post the signup to SonarCloud and connect to GitHub as my DevOps platform, I can import my GitHub Organization and the repository to perform my code analysis.
#1) In SonarCloud click on + -> Analyze new project
#2) Click on Import another organization
#3) Click on Import an organization from GitHub
#4) Select an Org on GitHub. The SonarCloud app will be installed to enable the integration.
#5) On GitHub, you can then choose to enable SonarCloud for all repositories or a specific repository.
#6) Click on Save. In SonarCloud, the projects will be listed once imported successfully and also in the My Projects menu.
Automatic Analysis Setup
In SonarCloud integrated with my GitHub repository, if any changes are pushed or committed to the main/master branch or a Pull Request is raised the code analysis is triggered automatically. These are primarily the 2 types of analysis done by SonarCloud which are branch level and Pull Request analysis.
To set up Automatic Analysis,
#1) Select the project and click on Administration -> Analysis Method
#2) Toggle the button next to Recheck compatibility
Automatic Analysis at the Branch Level
In GitHub in the main or master branch, I have the following code which is committed and has 2 issues.
<html> <head> <title>Hello World Maven Application</title> </head> <body> <h2>Hello World from Niranjan Bengaluru, KARNATAKA, India </h2> </body> </html>After a few minutes, the analysis report should be seen with 2 issues (Bug which is primarily a coding mistake) in the Main Branch -> Issues Tab within the project.
The other two types of issues are Vulnerability (e.g. SQL Injection) where the code is open to any kind of attack and Code Smell (e.g. Long method or Duplicate code) where the code is difficult to maintain.
The fixed code committed based on the recommendations above is shown below and the automatic analysis will list no issues.
<!DOCTYPE> <html lang="en"> <head> <title>Hello World Maven Application</title> </head> <body> <h2>Hello World from Niranjan Bengaluru, KARNATAKA, India </h2> </body> </html>Back in SonarCloud, go to your Project -> Main Branch -> Issues TAB
So it is all clear now. This is an example of Automatic Analysis at the branch level.
Automatic Analysis using Pull Request
In my code, I made the following changes in my development branch. I have raised a pull request to merge the changes to my master branch.
<html lang="en"> <head> <title>Hello World Maven Application</title> </head> <body> <h2>Hello World from Niranjan Bengaluru, KARNATAKA, India </h2> </body> </html>Create a pull request and proceed to merge. You can see that in SonarCloud there is one issue after the successful merge. Once the code is fixed the issue will be gone with the auto analysis being triggered. This is a good best practice to follow especially while doing development.
SonarCloud Quality Gate
Typically from a code quality point of view, every project would need to meet certain conditions so that it can be deployed to different environments. These are pre-defined criteria that are created and should mandatorily be met. In SonarCloud it is called Quality Gate which is called post the analysis and checked against the pre-defined criteria created.
For example, if there are issues > 1 or Major issues > 1 or Bugs > 1 then the quality gate should fail. This has to be resolved before proceeding.
In the last section, we did see just the sonar scan and its analysis. Here in this section, we will look at the below:
- Create a Quality gate and make it the default
- Add a condition
- Automatic Analysis is triggered at the branch level
- Block merge of Pull Request when Quality Gate fails
The result is either PASSED or FAILED.
#1) Create a Quality Gate and Add conditions
To create a Quality Gate in the SonarCloud project, go to Administration -> Quality Gate.
Click on the link Organization settings
Click on Create
Enter a name and click on Save
#2) For the Quality Gate created, click on Add Condition
Add conditions as shown or specific to your project needs.
Click on Add Condition. Select a project to associate with and make this Quality Gate default by clicking on the button Set as Default.
#3) Automatic Analysis with Quality Gate enabled at Branch Level
In the master or main branch in GitHub, I use the following code which is committed. Since Automatic Analysis is already set up it will be triggered and results will be displayed.
<html> <head> <title>Hello World Maven Application</title> </head> <body> <h2>Hello World from Niranjan Bengaluru, KARNATAKA, India </h2> </body> </html>In the Project -> Main Branch and Summary Tab you should see the following message.
Post the analysis the Quality gate is failed due to the condition which is added.
Click on the link 2 Bugs to see the details. As the code is fixed as per recommendations the Quality Gate will be PASSED.
#4) Block merge of Pull Request when the Quality Gate is failed
In this scenario, we will look at how to block the merge of pull requests when the quality gate fails.
First, we need to add a Branch protection rule in the repository and set up a requirement where for any push to a branch a status check like invoking SonarCloud Code Analysis when Quality Gate is enabled.
Click on Add branch protection rule and select as shown. The branch name pattern is * to apply for all branches. Select the checkbox ‘Require status checks to pass before merging’. Search and select ‘SonarCloud code analysis’ also as shown below.
Click on Create.
Now go back to the development branch in GitHub and commit the following code. In the JSP file, the code below has 2 issues.
<html> <head> <title>Hello World Maven Application</title> </head> <body> <h2>Hello World from Niranjan Bengaluru, KARNATAKA, India </h2> </body> </html>Create pull request to merge the changes from the development branch to the master branch.
Once the Pull Request is created and due to Quality Gate conditions, the merge of the PR will be blocked as shown.
Click on the 2 Bugs link to view the details. This will take you to the SonarCloud -> Pull Request Issues section.
Now since the Pull Request merge is blocked, you need to go back to the development branch and fix the code and you will see that the analysis will re-run automatically in the Pull Request created above. No need to create another Pull Request.
Fixed code as per the guidelines shown above:
<!DOCTYPE> <html lang="en"> <head> <title>Hello World Maven Application</title> </head> <body> <h2>Hello World from Niranjan Bengaluru, KARNATAKA, India </h2> </body> </html>Commit or Push the code to the repo. Go back to the Pull Request created and you will see the analysis run automatically.
After a few mins, you should see the checks have passed and the Pull Request can be merged.
Click on Merge pull request to merge the code to the master branch and close the Pull Request. Collected information about analysis is pushed back to SonarCloud.
Back in SonarCloud, you should see a clean slate in the Pull Requests -> Issues TAB.
This process of blocking the Pull Request merge through the Quality Gate ensures the developer fixes the code before merging to the master branch thereby maintaining clean code gets into the PRODUCTION environment.
Manual Analysis for SonarCloud
In the previous section, we saw how SonarCloud is integrated with GitHub and performs code analysis at either the branch level or the Pull Request level and also using Quality Gate. Typically, as developers write their code on their own systems, it is mandatory to perform analysis before they push the code to GitHub or any other code repository.
In this section, we will look at how developers can invoke analysis from the command line for their Maven project.
In my local system, I have the following code in my index.jsp file in a maven project.
<html> <body> <h2>Hello World from SonarCloud!</h2> </body> </html>In SonarCloud click on + Analyze new project
Click on the link create a project manually. Provide a Project Key and Display Name. Click on Set Up.
In the following screen, select Manually
Follow the instructions to perform the analysis manually by selecting the option Maven.
Set the environment variable, update the pom.xml, and run the mvn command as shown on the page.
Let’s look at the results in the SonarCloud dashboard using the link provided in the window. Click on Main Branch -> Issues TAB
The issue can be fixed by going through the recommendations and re-running the mvn command.
Generate SonarCloud Token
For SonarCloud token, go to your Profile -> My Account -> Security TAB and click on Generate Token.
The token must be saved for integration with Jenkins in the next section.
Integrate SonarCloud with Jenkins and GitHub
SonarCloud is just like your on-prem SonarQube server. So typically Sonar Scanner would be used on your local/build system and the following additions done in Manage Jenkins -> Configure System.
#1) Create SonarCloud credentials in Jenkins
In Jenkins, go to Manage Jenkins -> Credentials and add a System -> Global Credentials
Click on Global credentials and + Add Credentials. Use the Secret Text credentials and add the SonarCloud Token generated in the previous section in the Secret box. Provide an ID and Description. Click Create.
#2) Add SonarCloud URL as shown, select the token as created above under SonarQube servers.
Ensure that the checkbox “Enable injection of SonarQube server configuration as build environment variables” is checked. Click on Save.
Further Reading => SonarQube for Java & Integration with Jenkins
#3) Add SonarQube Scanner details to Jenkins
SonarQube Scanner a CLI utility is needed for analyzing your code with SonarQube.
SonarQube Scanner for your OS can be found in SonarQube Docs
The SonarQube scanner needs to be installed and run on your build machine. I am using a Windows build system and it is installed in E drive.
In Jenkins, go to Manage Jenkins -> Global Tool Configuration. Under SonarQube Scanner, add the details of the scanner location. Click on Save.
#4) Configure the sonar-scanner.properties file as shown below which is located in the conf folder of the Sonar Scanner installation.
#5) Configure sonar-project.properties file present at the root of your maven project.
Ensure sonar.organization property is added along with projectKey and projectName which can be found in your SonarCloud Project Information.
#6) Jenkins job configuration
GitHub step information:
My index.jsp file in the GitHub repository has the below contents and SonarCloud will analyze the same.
<html lang="en"> <body> <h2>Hello World from SonarCloud!</h2> </body> </html>Build Step:
Execute SonarQube Scanner Steps:
Select the SonarQube installation Configure, SonarQube Scanner, and add an Analysis property of projetKey. Click on Save and trigger the build.
Console Output:
The SonarCloud dashboard will show the details under Project -> Main Branch -> Issues.
As usual you fix the code and re-run the Jenkins job which will show no issues.
Conclusion
In this SonarCloud tutorial, we have seen that as a developer and following the shift-left policy we need to ensure our code is clean early on in the development life cycle to get into production.
With SonarCloud, we have seen the same to achieve the goal of clean code without bugs, vulnerabilities, and code smell, with branch and pull request-based analysis, and also using quality gates.
More on the types of issues and the severities (Blocker, Critical, Major, Minor, Info) which need to be either fixed or reviewed immediately can be found at the SonarCloud Issues
We did also look at manual analysis to find out the types of issues mentioned above and integration of SonarCloud with Jenkins and code from the GitHub repository for automated analysis to avoid effort spent on manual code review.
Developers should also consider using SonarLint which will help them to perform analysis within their IDEs before they can push their code to a SCM repository.
So truly SonarCloud or SonarQube is a must-have tool to be part of your development life cycle for static code analysis.
Further Reading =>> Top best Static Code Analysis Tools
Was this helpful?
Thanks for your feedback!