Set up Jenkins pipeline projects for Bitbucket repositories
Requirements
Ensure you have set up triggering events from Bitbucket to Jenkins.
Create a Jenkins pipeline project
- From the Jenkins Dashboard click on create a New Item.
- Type a project name and select the Pipeline option.
- In the General section, click the Build with Bitbucket Push and Pull Request Plugin. Alternatively, the plugin can also be called Bitbucket Cloud Pull Request or Bitbucket Server Pull Request.
- In Triggers > Select an Action select Created and Updated.
- In the Pipeline Section:
- In Repository URL, enter the Bitbucket repository URL.
- In Branch Specifier, enter your main or trunk branch (
master
in the screenshot). - In Script Path, enter the path to your 'Jenkinsfile'.
- Create the Jenkinsfile in the Bitbucket repository. It must define the logic to run Semgrep diff scans if it is a pull request or Semgrep full scans if it is a push to the main branch. It can look like this:
pipeline {
agent any
environment {
SEMGREP_APP_TOKEN = credentials('SEMGREP_APP_TOKEN')
SEMGREP_BASELINE_REF = "origin/master"
}
stages {
stage('Semgrep-Scan') {
steps {
script {
if (env.BITBUCKET_PULL_REQUEST_ID) {
echo "Semgrep diff scan"
sh '''git checkout ${BITBUCKET_PULL_REQUEST_LATEST_COMMIT_FROM_SOURCE_BRANCH}'''
sh '''git fetch origin +ref/heads/*:refs/remotes/origin/*'''
sh '''docker run \
-e SEMGREP_APP_TOKEN=$SEMGREP_APP_TOKEN \
-e SEMGREP_PR_ID=${BITBUCKET_PULL_REQUEST_ID} \
-e SEMGREP_BASELINE_REF=$SEMGREP_BASELINE_REF \
-v "$(pwd):$(pwd)" --workdir $(pwd) \
semgrep/semgrep semgrep ci'''
}
else {
echo "Semgrep full scan"
sh '''docker run \
-e SEMGREP_APP_TOKEN=$SEMGREP_APP_TOKEN \
-v "$(pwd):$(pwd)" --workdir $(pwd) \
semgrep/semgrep semgrep ci'''
}
}
}
}
}
}
note
- Ensure that you have defined a
SEMGREP_APP_TOKEN
as a credential in Jenkins. - The variable SEMGREP_BASELINE_REF must be set to the main branch, in the example:
origin/master
.
Test the new Jenkins pipeline project
- Commit a change in the repository and create a pull request. It automatically runs a Semgrep diff scan in Jenkins: Note that the pull request can be marked as failed if there are blocking findings, as in the example.
- Merge the change to master. It will run a Semgrep full scan in Jenkins.
Not finding what you need in this doc? Ask questions in our Community Slack group, or see Support for other ways to get help.