Integrating CodeScan in GitLab
  • 03 Nov 2022
  • 1 Minute to read
  • Contributors
  • Dark
    Light

Integrating CodeScan in GitLab

  • Dark
    Light

Integrating CodeScan into your GitLab pipeline is easy with our SFDX plugin. There are only a few lines to add to your .YML file to run codescan when a build is triggered.

Note:

The following is based on a docker pipeline with Java and Node installed in the container.

First, we'll need to add your CodeScan token as a variable we can access in our .YML file.

  • Open your project and navigate to Settings > CI/CD then expend the Variables section.
  • Add your token with the name CODESCAN_TOKEN and check the masked variable box. To learn how to generate a token, see HERE.

Now you'll be able to access this variable by using $CODESCAN_TOKEN in your .YML file.

Add the following into your .YML file:

Note:

The following is a great way to get started scanning with this plugin, however this script will install the CodeScan plugin with each run. A better implementation would include this installation in the docker image used.

image: salesforce/salesforcedx:latest-full

CodeScan:
  rules:
    - if: $CI_COMMIT_REF_NAME =~ /^[<branch>]/ && $CI_PIPELINE_SOURCE =~ /^[push|schedule]/
      variables:
        CODESCAN_CMD: "sfdx codescan:run --token=$CODESCAN_TOKEN --projectkey=<project> --organization=<organization> -Dsonar.branch.name=$CI_COMMIT_REF_NAME"
    - if: $CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_TARGET_BRANCH_NAME =~ /^[<branch>]/
      variables:
        CODESCAN_CMD: "sfdx codescan:run --token=$CODESCAN_TOKEN --projectkey=<project> --organization=<organization> -Dsonar.pullrequest.branch=$CI_COMMIT_REF_NAME -Dsonar.pullrequest.base=$CI_MERGE_REQUEST_TARGET_BRANCH_NAME -Dsonar.pullrequest.key=$CI_MERGE_REQUEST_IID"
  script:
    - echo y|sfdx plugins:install sfdx-codescan-plugin
    - $CODESCAN_CMD

You will need to replace the placeholder variables ( <project> and <organization>) in the env section of the script with your Project Key and Organization Key.

To specify the branches to scan on a push, replace the <branch> placeholder with the name of your branch.

The pull request details are being set by the following parameters:

  • sonar.pullrequest.branch: This is the name of the branch.
  • sonar.branch.target: This is the target branch for the pull request.
  • sonar.pullrequest.key: The pull request key/number/id.

By default, the CodeScan SFDX plugin will fail if the Quality Gate fails. If you would prefer that the build passes despite the quality gate, use the --nofail tag when calling sfdx codescan:run.

You can find a complete list of flags and examples on our npm plugin page.


Was this article helpful?