Ansible Code Scanning and High quality Checks With SonarQube – DZone – Uplaza

It’s best to have heard about SonarQube as a code scanning and code high quality test software. SonarQube would not help Ansible by default. A plugin must be set as much as scan Ansible playbooks or roles. On this article, you’ll study on arrange and use SonarQube in your Ansible (YAML) code for linting and code evaluation. This text makes use of the group version of SonarQube. 

What Is Ansible?

As defined in earlier articles round Ansible: Ansible Past Automation and Automation Ansible AI, Ansible is a straightforward IT automation software that helps you provision infrastructure, set up software program, and help utility automation by means of superior workflows. 

Ansible playbooks are written in YAML format and outline a collection of duties to be executed on distant hosts. Playbooks supply a transparent, human-readable method to describe complicated automation workflows. Utilizing playbooks, you outline the required dependencies and desired state to your utility. 

What Is SonarQube?

SonarQube is a broadly used open-source platform for steady code high quality inspection and evaluation. It’s designed to assist builders and groups determine and tackle potential points of their codebase, reminiscent of bugs, code smells, safety vulnerabilities, and technical debt. SonarQube helps a variety of programming languages, together with Java, C#, C/C++, Python, JavaScript, and plenty of others. The group version of SonarQube can carry out static code evaluation for 19 languages like Terraform, code formation, Docker, Ruby, Kotlin, Go, and so on.,

Comparability of SonarQube Editions

Code Scanning and Evaluation

SonarQube performs static code evaluation, which suggests it examines the supply code with out executing it. This evaluation is carried out by parsing the code and making use of a set of predefined guidelines and patterns to determine potential points. SonarQube covers varied facets of code high quality, together with:

  • Code smells: SonarQube can detect code smells, that are indicators of potential maintainability points or design flaws within the codebase. Examples embody duplicated code, complicated strategies, and extreme coupling.
  • Bugs: SonarQube can determine potential bugs within the code, reminiscent of null pointer dereferences, useful resource leaks, and different frequent programming errors.
  • Safety vulnerabilities: SonarQube can detect safety vulnerabilities within the code, reminiscent of SQL injection, cross-site scripting (XSS), and different safety flaws.
  • Technical debt: SonarQube can estimate the technical debt of a codebase, which represents the trouble required to repair recognized points and produce the code as much as a desired degree of high quality.

Significance of Code Scanning and Evaluation

Code scanning and evaluation with SonarQube supply a number of advantages to improvement groups:

  • Improved code high quality: By figuring out and addressing points early within the improvement course of, groups can enhance the general high quality of their codebase, decreasing the probability of bugs and making the code extra maintainable.
  • Elevated productivity: By automating the code evaluation course of, SonarQube saves builders effort and time that will in any other case be spent manually reviewing code.
  • Constant code requirements: SonarQube can implement coding requirements and finest practices throughout the whole codebase, guaranteeing consistency and adherence to established pointers.
  • Safety consciousness: By detecting safety vulnerabilities early, groups can tackle them earlier than they turn out to be exploitable in manufacturing environments, decreasing the chance of safety breaches.
  • Technical debt administration: SonarQube’s technical debt estimation helps groups prioritize and handle the trouble required to handle recognized points, guaranteeing that the codebase stays maintainable and extensible.

Carry out Static Utility Safety Testing

SonarQube is a number one software for performing SAST, providing complete capabilities to boost code safety and high quality. Static Utility Safety Testing (SAST) is a technique of safety testing that analyzes supply code to determine vulnerabilities and safety flaws. Not like Dynamic Utility Safety Testing (DAST), which assessments operating purposes, SAST examines the code itself, making it a type of white-box testing.

SonarQube integrates seamlessly with well-liked improvement instruments and steady integration/steady deployment (CI/CD) pipelines, making it straightforward to include code evaluation into the event workflow. With its complete evaluation capabilities and help for varied programming languages, SonarQube has turn out to be a necessary software for improvement groups in search of to enhance code high quality, preserve a safe and maintainable codebase, and ship high-quality software program merchandise.

Set up SonarQube on Your Native Machine

You possibly can set it up utilizing a zipper file or you possibly can spin up a Docker container utilizing one among SonarQube’s Docker photos.

1. Obtain and set up Java 17 from Eclipse Temurin Newest Releases. In case you are utilizing a macOS, you possibly can set up utilizing HomeBrew with the under command.

brew set up --cask temurin@17

2. Obtain the SonarQube Group Version zip file.

3. As talked about within the SonarQube documentation, as a non-root consumer unzip the downloaded SonarQube group version zip file to C:sonarqube on Home windows or on Linux / macOS /choose/sonarqube

On Linux / macOS, you’ll have to run a command to create folder as a root  sudo mkdir -p /choose/sonarqube

4. The folder construction in your /choose/sonarqube ought to look much like the under picture. The important thing folders that you’ll be utilizing for this text could be bin and extensions/plugins

SonarQube Group version folder construction

5. To start out the SonarQube server, change to the listing the place you unzipped the group version and run the under instructions below the respective Working System. For instance, In case you are operating on a macOS, you’ll change the listing to /choose/sonarqube/bin/macosx-universal-64

# On Home windows, execute:
C:sonarqubebinwindows-x86-64StartSonar.bat
 
# On different working techniques, as a non-root consumer execute:
/choose/sonarqube/bin//sonar.sh console

Here is the folder construction below the bin folder.

bin folder construction

6. On a macOS, that is the way it appears to be like once you run the server with Java 17 setup

# To alter to the listing and execute
cd /choose/sonarqube/bin/macosx-universal-64
./sonar.sh console

SonarQube server up and operating

In case you are utilizing a Docker picture of the group version from the Dockerhub, run the under command 

docker run -d --name sonarqube -e SONAR_ES_BOOTSTRAP_CHECKS_DISABLE=true -p 9000:9000 sonarqube:newest

7. You possibly can entry the SonarQube server at this localhost. Preliminary system administrator username: admin and password: admin. You’ll be requested to reset the password as soon as logged in.  

SonarQube console

SonarQube Initiatives

A SonarQube venture represents a codebase that you simply need to analyze. Every venture is recognized by a singular key and will be configured with varied settings, such because the programming languages used, the supply code directories, and the standard gates (thresholds for code high quality metrics). You possibly can create a brand new venture in SonarQube by means of the online interface or mechanically through the first evaluation of your codebase. When making a venture manually, you have to present a venture key and different particulars just like the venture identify and visibility settings.

Scanner CLI for SonarQube

A scanner is required to be arrange that will probably be used to run code evaluation on SonarQube. Undertaking configuration is learn from file sonar-project.properties or handed on the command line.

The SonarScanner CLI (Command Line Interface) is a software that lets you analyze your codebase from the command line. It’s the advisable scanner when there isn’t any particular scanner accessible to your construct system or once you need to run the evaluation outdoors of your construct course of.

Obtain and Configure SonarScanner CLI

  1. Based mostly on the Working system, you might be operating your SonarQube server, obtain the sonar-scanner from this hyperlink.
  2. Unzip or develop the downloaded file into the listing of your selection. Let’s seek advice from it as within the subsequent steps.
  3. Replace the worldwide settings to level to your SonarQube server by enhancing $install_directory/conf/sonar-scanner.properties
# Configure right here basic details about the surroundings, such because the server connection particulars for instance
# No details about particular venture ought to seem right here

#----- SonarQube server URL (default to SonarCloud)
sonar.host.url=http://localhost:9000/

#sonar.scanner.proxyHost=myproxy.mycompany.com
#sonar.scanner.proxyPort=8002

4. Add the /bin listing to your path. In case you are utilizing macOS or Linux, add this to your ~/.bashrc or ~/.zshrc and supply the file supply ~/.bashrc 

Setup Ansible Plugin

Earlier than you arrange the SonarQube plugin for Ansible, set up ansible-lint

npm set up -g ansible-lint

On macOS, when you’ve got homebrew put in, use this command brew set up ansible-lint

To put in and setup the SonarQube plugin for Ansible, comply with the directions right here

  1. Obtain the YAML and Ansible SonarQube plugins
  2. Copy them into the extensions/pluginslisting of SonarQube and restart SonarQube
    ├── README.txt
    
    ├── sonar-ansible-plugin-2.5.1.jar
    
    └── sonar-yaml-plugin-1.9.1.jar
  3. Log into SonarQube Server console.
  4. Click on on High quality Profiles to create a brand new high quality profile for YAML.

High quality Profiles

5.  Click on Create.

6. Choose Copy from an present high quality profile, fill within the under particulars and click on Create.

  1. Language: YAML
  2. Father or mother: YAML Analyzer (Constructed-in)
  3. Title: ansible-scan

New high quality profile

7.  Activate the Ansible guidelines on the ansible-scan high quality profile by clicking on the menu icon and choosing Lively Extra Guidelines.

Activate extra guidelines for Ansible

8.  Search with the tag “ansible” and from the Bulk Change, Click on on Activate in ansible-scan.

Search and apply

9. Set ansible-scan because the Default. The Ansible guidelines will probably be relevant to different YAML information. Now you can see that for YAML you might have 20 guidelines and for Ansible you might have 38 guidelines.

Set ansible-scan 

Create a New Undertaking and Run Your First Scan

  1. 1. Navigate to the localhost in your browser to launch the SonarQube Server console.
  2. 2. Click on Create Undertaking and choose Native venture. 

For demo objective, you possibly can obtain Ansible code from this GitHub repository.

Create native venture

3.  Enter a venture displayname, venture key, department identify, and click on Subsequent.

Native venture creation

4. Below Select the baseline for brand new code for this venture, choose Use the worldwide setting and click on Create venture. Learn the data under the choice to grasp why it is best to decide this selection.

Choose settings

5.  Choose Regionally below the Evaluation Technique as you’ll be operating this domestically in your machine.

Evaluation technique

6. Below Present a token, choose Generate a token. 

  1. Give your token a reputation, click on Generate, and click on Proceed.
  2. Below Run evaluation in your venture, Choose Different.
  3. Choose the Working System(OS).

7. Click on on the Copy icon to avoid wasting the instructions to the clipboard. 

Generate token

8. On a terminal or command immediate, navigate to your Ansible code folder, and paste and execute instructions in your venture’s folder. You possibly can see the Ansible-lint guidelines known as within the log.

INFO: ansible model:
INFO: ansible [core 2.17.0]
INFO:   config file = None
INFO:   configured module search path = ['/Users/vmac/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
INFO:   ansible python module location = /usr/native/Cellar/ansible/10.0.1/libexec/lib/python3.12/site-packages/ansible
INFO:   ansible assortment location = /Customers/vmac/.ansible/collections:/usr/share/ansible/collections
INFO:   executable location = /usr/native/bin/ansible
INFO:   python model = 3.12.3 (principal, Apr  9 2024, 08:09:14) [Clang 15.0.0 (clang-1500.3.9.4)] (/usr/native/Cellar/ansible/10.0.1/libexec/bin/python)
INFO:   jinja model = 3.1.4
INFO:   libyaml = True
INFO: ansible-lint model:
INFO: ansible-lint 24.6.0 utilizing ansible

9. On the SonarQube server console, you possibly can see the evaluation data

Overview

Ansible code analyzed

Conclusion

On this article, you discovered set up, configure, and run the SonarQube plugin for Ansible that permits builders and operations groups to investigate the Ansible playbooks and/or roles for code high quality, safety vulnerabilities, and finest practices. It leverages the YAML SonarQube plugin and provides extra guidelines particularly tailor-made for Ansible.

Steered Studying

In case you are new to Ansible and need to study the instruments and capabilities it gives, test my earlier articles:

  1. Ansible Past Automation
  2. Automation Ansible AI
Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Exit mobile version