Register with Jenkins

Updated at:
Copy as MD

Run codesec-cli in a Jenkins pipeline to integrate Code Security source code scanning, including Static Application Security Testing (SAST), Software Composition Analysis (SCA), secret detection, and Infrastructure as Code (IaC). This topic describes how to configure incremental gating scans for merge requests and full baseline scans for the main branch, write scan results back as merge request comments, and view the results in the Code Security console.

The integration has five steps: prepare Alibaba Cloud access credentials, register credentials in Jenkins, configure the Jenkins pipeline and triggers, configure a webhook in the code platform, and trigger a build to verify the integration.

Step Name Main action Where to perform the action
One Get credentials Create a RAM access policy and user, and obtain an AccessKey Alibaba Cloud RAM console
Two Configure credentials Register the AK/SK, endpoint, and token as Jenkins credentials Jenkins Credentials
Three Configure the scan job Create a Pipeline, and configure triggers and the scan script Jenkins
Four Configure the code platform webhook Register the webhook address, Secret token, and trigger events Code platform
Five Verify the integration Run a manual build, trigger builds through a push or a merge request, and view the scan results Jenkins and the Code Security console

Before you begin

  • The Jenkins version is 2.361 or later.

  • The GitLab Plugin, Pipeline, and Git-related plugins are installed.

  • The Jenkins build node can access the Internet to call the Code Security OpenAPI.

  • A Git repository is ready for scanning, and you have permission to configure webhooks in the code platform. If the code platform restricts webhook access to internal addresses, you also need configuration permission in the Admin Area.

  • If you run scans with the container image method, the build environment must have access to the Docker daemon (mount docker.sock and configure permissions).

Step 1: Get credentials

Code Security reports scan results and retrieves results through OpenAPI. Create a RAM user with Code Security operation permissions and obtain the AccessKey of the user.

Create a custom access policy

Log on to the Alibaba Cloud RAM console and choose Permissions > Policies > Create Policy, select JSON Editor, paste the following content, and save the policy. The suggested policy name is AliyunCodeSecFullAccess.

{
  "Version": "1",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "yundun-codesec:*",
      "Resource": "*"
    }
  ]
}

Create a RAM user and obtain an AccessKey

Choose Identities > Users > Create User, and select Permanent AccessKey. After the user is created, immediately save the AccessKey ID and AccessKey secret.

Important

The AccessKey secret is displayed only once, when it is created. Save it at that time. You cannot view it again later and can only create a new one.

Grant permissions to the user

On the user details page, click Add Permissions, select the custom access policy created in Step 1, and bind it to the user.

Record the integration endpoint

The Code Security OpenAPI gateway address follows the format https://codesec.<region-id>.aliyuncs.com. The endpoint for China (Hangzhou) is https://codesec.cn-hangzhou.aliyuncs.com. Register this address as a credential in Step 2.

Warning

An AccessKey is a long-term credential. Inject it through Jenkins Credentials. Do not hardcode it in a Jenkinsfile or commit it to a code repository.

Step 2: Configure credentials

In Jenkins, choose Manage Jenkins > Credentials > Add Credentials, and add each of the following credentials. Unless otherwise specified, set Kind to Secret text.

Add required credentials

Credential ID Environment variable Value Description
codesec-ak YUNDUN_CODESEC_OPENAPI_AK LTAI5tXxx... The AccessKey ID created in Step 1.
codesec-sk YUNDUN_CODESEC_OPENAPI_SECRET xxxxxxxx... The AccessKey secret created in Step 1.
codesec-endpoint YUNDUN_CODESEC_OPENAPI_ENDPOINT https://codesec.cn-hangzhou.aliyuncs.com The Code Security OpenAPI gateway address.
gitlab-git-cred — Username and token or password Used by the Pipeline to pull code. Set Kind to Username with password.

Add optional credentials

Credential ID Environment variable Value When required
codesec-gitlab-token YUNDUN_CODESEC_GITLAB_TOKEN glpat-xxxx... Required only when --comment is used to write back merge request comments.
Important

The GitLab API token type used by the GitLab Plugin is for plugin use only. In a Pipeline, credentials() can bind only Secret text credentials to environment variables. Therefore, even if the token value is the same, create an additional Secret text credential.

Step 3: Configure the scan job

Create a Pipeline job

On the Jenkins home page, click New Item, enter the job name codesec-scan, select Pipeline, and then click OK.

Configure build triggers

On the job configuration page, in the Build Triggers section, complete the following configuration:

  1. Select Build when a change is pushed to GitLab.

  2. In the expanded options, select Opened Merge Request Events and Accepted Merge Request Events so that merge requests can also trigger builds.

  3. Record the webhook URL displayed on the page. The format is http://<jenkins-host>:8080/project/codesec-scan.

  4. Click Advanced, and then generate and copy the Secret token. In Step 4, paste this token into the code platform.

  5. In the same Advanced section, find Allowed branches, select Filter branches by name, and in Include, enter the main branch name, such as main.

Note

Allowed branches ensures that only pushes to the main branch trigger a full build. The plugin ignores pushes to other branches. Merge request events are not affected by this filter and still trigger incremental scans.

Whether a webhook can trigger a build depends on the following Jenkins security settings:

Configuration item Location Result if not configured
Allow anonymous read access Manage Jenkins > Configure Global Security > Authorization, and select Allow anonymous read access The webhook sends a POST request anonymously. The request is blocked before it reaches the plugin and returns 404.
Matching secret tokens Paste the token generated by Jenkins, without changes, into the Secret token field of the code platform webhook. When the token does not match, the request is handled with anonymous-user permissions and returns 403 anonymous is missing the Job/Build permission.

The plugin validates the Secret token. When the token matches, the plugin triggers the build with system permissions.

Select scan strategies

Enable both incremental gating scans and full baseline scans, so that incremental gating is paired with a full-scan safety net.

Strategy Trigger Scan scope Result destination
Incremental gating scan A merge request that targets the main branch is created or updated Only the code changed in the current request Written back as a merge request comment. The build fails when high-severity issues are found.
Full baseline scan A push to the main branch All code in the repository JSON and SARIF reports are generated and archived.

Choose an execution method

Jenkins supports the following two methods for running codesec-cli. Choose one of them.

Comparison item Option A: binary installation (recommended) Option B: container image
How it works Preinstall codesec-cli in the Jenkins image or on the build node, and run it directly from the Pipeline. Run a codesec-cli container in the Pipeline with docker run.
Path mapping No additional configuration is required. If Jenkins runs in a container, map the host path.
Credential delivery credentials() injects environment variables that the shell process can read directly. Pass each environment variable to the container with -e.
Version upgrades Rebuild the image or reinstall the binary file. Change the image tag.
Docker dependency No Docker daemon access is required. Mount docker.sock and configure permissions.

To prepare Option A, install codesec-cli on the Jenkins build node or in a custom image.

# Extract the binary from the official image
docker run --rm -v $(pwd):/out \
    codesec-cli-registry.cn-hangzhou.cr.aliyuncs.com/codesec-cli/codesec-cli:latest \
    cp /usr/local/bin/codesec-cli /out/codesec-cli

# Add the binary to the Jenkins custom-image Dockerfile in the USER root section
COPY codesec-cli /usr/local/bin/codesec-cli
RUN chmod +x /usr/local/bin/codesec-cli
Important

The binary file must match the system architecture of the build node. The default architecture is linux/amd64.

Configure the Pipeline script: binary installation

At the bottom of the job configuration page, in the Pipeline section, set Definition to Pipeline script, and paste the following script. Before you paste the script, replace the angle-bracket placeholders (such as <gitlab-host>, <group>, and <project>) with actual values. The script selects the scan method based on the trigger source. A push to the main branch runs a full scan. A merge request runs an incremental scan and writes the results back as a comment. Other events are skipped. The branch guard in the script and Allowed branches in the build triggers form two layers of filtering: Allowed branches filters push events only at the plugin layer. The branch guard also validates the merge request target branch at the script layer. Together, they ensure that scans run only for pushes to the main branch or for merge requests that target the main branch.

pipeline {
    agent any

    environment {
        GIT_REPO     = 'http://<gitlab-host>/<group>/<project>.git'
        MAIN_BRANCH  = 'main'
        REPORT_DIR   = 'codesec-report'
        GITLAB_API   = 'http://<gitlab-host>/api/v4'
        // credentials() injects values as process environment variables, which codesec-cli reads directly
        YUNDUN_CODESEC_OPENAPI_AK       = credentials('codesec-ak')
        YUNDUN_CODESEC_OPENAPI_SECRET   = credentials('codesec-sk')
        YUNDUN_CODESEC_OPENAPI_ENDPOINT = credentials('codesec-endpoint')
        YUNDUN_CODESEC_GITLAB_TOKEN     = credentials('codesec-gitlab-token')
    }

    stages {
        stage('Checkout') {
            steps {
                git branch: "${env.gitlabSourceBranch ?: env.MAIN_BRANCH}",
                    url: "${GIT_REPO}",
                    credentialsId: 'gitlab-git-cred'
            }
        }

        stage('CodeSec Scan') {
            steps {
                script {
                    def isMR = env.gitlabMergeRequestIid != null

                    // Branch guard: scan only main-branch pushes or merge requests that target the main branch
                    if (!isMR && env.gitlabBranch && env.gitlabBranch != env.MAIN_BRANCH) {
                        echo "Skip: pushed branch is ${env.gitlabBranch}, not the main branch"
                        return
                    }
                    if (isMR && env.gitlabTargetBranch && env.gitlabTargetBranch != env.MAIN_BRANCH) {
                        echo "Skip: merge request target branch is ${env.gitlabTargetBranch}, not the main branch"
                        return
                    }

                    if (isMR) {
                        sh """
                            codesec-cli scan \
                                --platform jenkins \
                                --diff --base origin/${env.gitlabTargetBranch} \
                                --change-id ${env.gitlabMergeRequestIid} \
                                --api-url ${GITLAB_API} \
                                --comment \
                                --report sarif=${REPORT_DIR}/report.sarif \
                                --fail-on high
                        """
                    } else {
                        sh """
                            codesec-cli scan \
                                --platform jenkins \
                                --all \
                                --report json=${REPORT_DIR}/report.json \
                                --report sarif=${REPORT_DIR}/report.sarif \
                                --fail-on high
                        """
                    }
                }
            }
        }

        stage('Archive Report') {
            steps {
                archiveArtifacts artifacts: 'codesec-report/**', allowEmptyArchive: true
            }
        }
    }

    post {
        failure {
            echo 'The scan found high-severity issues or failed to run. View the archived reports.'
        }
    }
}

With the binary installation method, the codesec-cli command requires at least --platform jenkins and a scan mode parameter. For a full scan, specify --all. For an incremental scan, specify --diff, along with the --base, --change-id, and --api-url parameters. Use --comment to write the scan results back as a merge request comment. Credentials and the endpoint are read automatically from environment variables. The project name, branch, and commit are inferred automatically from the .git/ of the current directory.

Configure the Pipeline script: container image

The container image method differs from the binary installation method mainly in the scan stage: mount the workspace into the container and pass each environment variable separately. In the script, placeholders such as <host jenkins_home path> must also be replaced with actual values.

pipeline {
    agent any

    environment {
        GIT_REPO      = 'http://<gitlab-host>/<group>/<project>.git'
        MAIN_BRANCH   = 'main'
        CODESEC_IMAGE = 'codesec-cli-registry.cn-hangzhou.cr.aliyuncs.com/codesec-cli/codesec-cli:latest'
        REPORT_DIR    = '/src/codesec-report'
        GITLAB_API    = 'http://<gitlab-host>/api/v4'
        // Required only when Jenkins itself runs in a container: points to the jenkins_home mount point on the host
        JENKINS_HOME_HOST = '<host jenkins_home path>'
        YUNDUN_CODESEC_OPENAPI_AK       = credentials('codesec-ak')
        YUNDUN_CODESEC_OPENAPI_SECRET   = credentials('codesec-sk')
        YUNDUN_CODESEC_OPENAPI_ENDPOINT = credentials('codesec-endpoint')
        YUNDUN_CODESEC_GITLAB_TOKEN     = credentials('codesec-gitlab-token')
    }

    stages {
        stage('Checkout') {
            steps {
                git branch: "${env.gitlabSourceBranch ?: env.MAIN_BRANCH}",
                    url: "${GIT_REPO}",
                    credentialsId: 'gitlab-git-cred'
            }
        }

        stage('CodeSec Scan') {
            steps {
                script {
                    // Jenkins runs in a container, convert the container WORKSPACE path to the actual host path
                    def hostWorkspace = "${WORKSPACE}".replace('/var/jenkins_home', "${JENKINS_HOME_HOST}")
                    def isMR = env.gitlabMergeRequestIid != null

                    if (!isMR && env.gitlabBranch && env.gitlabBranch != env.MAIN_BRANCH) {
                        echo "Skip: pushed branch is ${env.gitlabBranch}, not the main branch"
                        return
                    }
                    if (isMR && env.gitlabTargetBranch && env.gitlabTargetBranch != env.MAIN_BRANCH) {
                        echo "Skip: merge request target branch is ${env.gitlabTargetBranch}, not the main branch"
                        return
                    }

                    def scanCmd = isMR \
                        ? "codesec-cli scan --platform jenkins --diff --base origin/${env.gitlabTargetBranch} --change-id ${env.gitlabMergeRequestIid} --api-url ${GITLAB_API} --comment --report sarif=${REPORT_DIR}/report.sarif --fail-on high" \
                        : "codesec-cli scan --platform jenkins --all --report json=${REPORT_DIR}/report.json --report sarif=${REPORT_DIR}/report.sarif --fail-on high"

                    sh """
                        docker run --rm \
                            -v ${hostWorkspace}:/src \
                            -w /src \
                            -e YUNDUN_CODESEC_OPENAPI_AK=\${YUNDUN_CODESEC_OPENAPI_AK} \
                            -e YUNDUN_CODESEC_OPENAPI_SECRET=\${YUNDUN_CODESEC_OPENAPI_SECRET} \
                            -e YUNDUN_CODESEC_OPENAPI_ENDPOINT=\${YUNDUN_CODESEC_OPENAPI_ENDPOINT} \
                            -e YUNDUN_CODESEC_GITLAB_TOKEN=\${YUNDUN_CODESEC_GITLAB_TOKEN} \
                            \${CODESEC_IMAGE} \
                            ${scanCmd}
                    """
                }
            }
        }

        stage('Archive Report') {
            steps {
                archiveArtifacts artifacts: 'codesec-report/**', allowEmptyArchive: true
            }
        }
    }
}
Important

If Jenkins runs in a container and calls the host Docker daemon by mounting docker.sock, ${WORKSPACE} is a path inside the Jenkins container, but the Docker daemon resolves the path on the host. Without conversion, Docker mounts an empty directory that does not exist, and the scan result is No scannable files. If Jenkins is deployed directly on a physical machine or virtual machine, no conversion is required. Use ${WORKSPACE} directly.

Step 4: Configure the code platform webhook

In the code repository, choose Settings > Webhooks, and complete the following configuration:

  1. Set URL to the Jenkins webhook address recorded in Step 3.

  2. Paste the token generated in Step 3 into Secret token. This field is required. If it is missing, the request returns 403.

  3. Select Push events, and in the expanded Branch filter, enter the main branch name.

  4. Select Merge request events. This event is not affected by the Branch filter.

  5. If the internal network does not use HTTPS, clear Enable SSL verification.

  6. After you save the webhook, click Test > Push events to run a verification. The request should return HTTP 200.

Note

If the webhook page displays URL is blocked, in the code platform choose Admin Area > Settings > Network > Outbound requests, and allow webhooks to access internal addresses.

Step 5: Verify the integration

Trigger a build manually

On the Jenkins job page, click Build Now, and then view the execution result in Console Output. The following is an example of the expected output:

[Pipeline] stage (Checkout)
Cloning repository http://<gitlab-host>/<group>/<project>.git
[Pipeline] stage (CodeSec Scan)
[codesec-cli] Starting full scan...
[codesec-cli] Scan completed. Found X issues.
[Pipeline] stage (Archive Report)
Archiving artifacts

Verify automatic triggering

Push a commit to the main branch to verify whether a push can automatically trigger a build. The following is an example:

git clone http://<gitlab-host>/<group>/<project>.git
cd <project>
echo "// security test" >> README.md
git add . && git commit -m "trigger security scan"
git push origin main

After the push, Jenkins should automatically trigger a build. For a merge request, create a merge request that targets the main branch. After the build finishes, the scan result comment should appear on the merge request page. Scan results are also reported through OpenAPI, and you can log on to the Code Security console to view them in one place.