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

You need to have heard about SonarQube as a code scanning and code high quality test instrument. SonarQube does 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 easy methods to arrange and use SonarQube in your Ansible (YAML) code for linting and code evaluation. This text makes use of the neighborhood 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 instrument that helps you provision infrastructure, set up software program, and help software automation by way of superior workflows. 

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

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 handle potential points of their codebase, equivalent to 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 neighborhood version of SonarQube can carry out static code evaluation for 19 languages like Terraform, code formation, Docker, Ruby, Kotlin, Go, and many others.,

Comparability of SonarQube Editions

Code Scanning and Evaluation

SonarQube performs static code evaluation, which implies 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 elements 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 embrace duplicated code, complicated strategies, and extreme coupling.
  • Bugs: SonarQube can determine potential bugs within the code, equivalent to null pointer dereferences, useful resource leaks, and different frequent programming errors.
  • Safety vulnerabilities: SonarQube can detect safety vulnerabilities within the code, equivalent to 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 convey the code as much as a desired degree of high quality.

Significance of Code Scanning and Evaluation

Code scanning and evaluation with SonarQube provide a number of advantages to growth groups:

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

Carry out Static Utility Safety Testing

SonarQube is a number one instrument 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 working functions, SAST examines the code itself, making it a type of white-box testing.

SonarQube integrates seamlessly with standard growth instruments and steady integration/steady deployment (CI/CD) pipelines, making it simple to include code evaluation into the event workflow. With its complete evaluation capabilities and help for varied programming languages, SonarQube has change into an important instrument for growth groups searching for 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 may spin up a Docker container utilizing certainly one of SonarQube’s Docker photos.

1. Obtain and set up Java 17 from Eclipse Temurin Newest Releases. If you’re utilizing a macOS, you may set up utilizing HomeBrew with the beneath command.

brew set up --cask temurin@17

2. Obtain the SonarQube Neighborhood Version zip file.

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

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

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

SonarQube Neighborhood version folder construction

5. To begin the SonarQube server, change to the listing the place you unzipped the neighborhood version and run the beneath instructions below the respective Working System. For instance, If you’re working on a macOS, you’ll change the listing to /decide/sonarqube/bin/macosx-universal-64

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

This is the folder construction below the bin folder.

bin folder construction

6. On a macOS, that is the way it appears if you run the server with Java 17 setup

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

SonarQube server up and working

If you’re utilizing a Docker picture of the neighborhood version from the Dockerhub, run the beneath 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 Tasks

A SonarQube challenge represents a codebase that you simply need to analyze. Every challenge 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 challenge in SonarQube by way of the net interface or mechanically through the first evaluation of your codebase. When making a challenge manually, it is advisable to present a challenge key and different particulars just like the challenge 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. Challenge configuration is learn from file sonar-project.properties or handed on the command line.

The SonarScanner CLI (Command Line Interface) is a instrument that permits you to analyze your codebase from the command line. It’s the really useful scanner when there isn’t a particular scanner obtainable in your construct system or if you need to run the evaluation exterior of your construct course of.

Obtain and Configure SonarScanner CLI

  1. Primarily based on the Working system, you might be working your SonarQube server, obtain the sonar-scanner from this hyperlink.
  2. Unzip or broaden the downloaded file into the listing of your alternative. Let’s discuss with it as within the subsequent steps.
  3. Replace the worldwide settings to level to your SonarQube server by modifying $install_directory/conf/sonar-scanner.properties
# Configure right here common details about the setting, such because the server connection particulars for instance
# No details about particular challenge 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. If you’re 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, if in case you have 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 current high quality profile, fill within the beneath particulars and click on Create.

  1. Language: YAML
  2. Mum or dad: YAML Analyzer (Constructed-in)
  3. Identify: 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 have got 20 guidelines and for Ansible you have got 38 guidelines.

Set ansible-scan 

Create a New Challenge 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 Challenge and choose Native challenge. 

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

Create native challenge

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

Native challenge creation

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

Choose settings

5.  Choose Regionally below the Evaluation Methodology as you may be working this regionally 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 challenge, Choose Different.
  3. Choose the Working System(OS).

7. Click on on the Copy icon to save lots of 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 challenge’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 (fundamental, 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 may see the evaluation data

Overview

Ansible code analyzed

Conclusion

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

Instructed Studying

If you’re new to Ansible and need to study the instruments and capabilities it supplies, 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