Adding Semgrep to CI takes about twenty minutes. Making it survive contact with a codebase that has existed for five years is the part nobody writes down. The first full scan of a mature repository routinely returns several hundred findings, none of which the person opening today’s pull request wrote, and a gate that blocks on all of them gets disabled within a fortnight. The fix is --baseline-commit: Semgrep scans twice, subtracts the findings that already existed at the merge base, and only fails on what the change actually introduced. By the end of this guide you will have the CLI installed, a ruleset you chose deliberately, one custom rule of your own, a diff-aware gate wired into GitHub Actions and GitLab CI, SARIF output feeding the security tab, and a way to silence a genuine false positive without switching a rule off globally.
What you’ll accomplish
- Semgrep CLI installed locally and running the same rules your pipeline will run, so you can reproduce a CI failure on your laptop.
- A rule configuration that mixes registry rulesets with a local
.semgrep.yml, instead of the--config autoshrug. - One custom rule written with
patterns,pattern-eitherandmetavariable-regex, with a passing test file next to it. - A pull-request gate that fails only on findings the change introduced, and a scheduled full scan that reports the backlog without blocking anyone.
- A documented, reviewable way to suppress a false positive with
nosemgrep, plus SARIF output so findings land in the GitHub security tab or the GitLab MR widget.
Prerequisites
- A git repository. Baselining is a git operation — it will not work on a source tree that is not under git, and it will not work on a shallow clone that does not contain the base commit.
- Python 3.9 or newer if you install with
pip. macOS users can use Homebrew instead. If you would rather not manage a Python environment on the runner, the officialsemgrep/semgrepcontainer image ships everything. - Any recent Semgrep 1.x release. Flags have been stable for a long time in this area, but check
semgrep --versionbefore you copy a pipeline from a blog post older than the release you are on. - Outbound HTTPS to
semgrep.devif you use registry rulesets (p/...orr/...). Rules are fetched at scan time and cached. If your runners are on an isolated network, vendor the rules into the repository instead and point--configat a local directory. - A CI platform that exposes the base commit of a pull request. GitHub Actions gives you
github.event.pull_request.base.sha; GitLab gives youCI_MERGE_REQUEST_DIFF_BASE_SHA. Both require a full clone. - No Semgrep account is needed for anything in this guide. The hosted platform adds finding history and rule policies; the CLI gate works without it.
How it works
Semgrep matches patterns against a parsed syntax tree, not against text. That is why a rule for requests.get(..., verify=False, ...) matches regardless of how the arguments are wrapped, indented or ordered, and why it does not match a comment that happens to contain the same characters.
Two commands do almost the same thing with different defaults. semgrep scan is the general-purpose scanner: it prints findings and, unless you pass --error, still exits 0. semgrep ci is the wrapper meant for pipelines: it reads the CI environment, respects .semgrepignore, and exits 1 when it finds something blocking. In CI you almost always want semgrep ci.
The baseline is the piece that decides whether the gate survives. When you pass --baseline-commit, Semgrep runs the scan on the current working tree, then checks out the baseline commit into a temporary git worktree and runs the identical rules again. The findings present in the second scan are subtracted from the first. What remains is the set of findings this branch introduced.
An important detail: the baseline is computed per pull request, against its merge base. It is not a date and not an allowlist. A finding you inherited today still shows up in reports, and the moment somebody edits the line it sits on, it becomes a new finding and blocks. The backlog is deferred, not forgiven.
Step-by-step
- Install the CLI and confirm the version. Do this on your workstation first, so a CI failure is always reproducible locally.
python3 -m pip install --user semgrep
semgrep --version
1.98.0
On macOS, brew install semgrep works equally well. In a container-based pipeline, use semgrep/semgrep as the job image and skip the install step entirely.
- Measure the honest starting point before you turn anything on. Run a full scan and count what you are dealing with. This number is the whole argument for baselining.
cd /path/to/repo
semgrep scan --config p/default --metrics=off
┌──────────────┐
│ Scan Summary │
└──────────────┘
Ran 1043 rules on 2917 files: 917 findings.
Nine hundred findings is a normal result for a repository that has never been scanned. It is not a crisis and it is not something you can fix this sprint. The choice you make right now determines whether the gate is still running in three months.
- Choose rulesets deliberately instead of using
--config auto. Theautovalue asks the registry to guess based on your languages, which makes your gate’s behaviour change without a commit. Name what you run:
semgrep scan --config p/default --config p/owasp-top-ten --metrics=off --severity ERROR
p/default is the curated low-noise set and is the right starting point. p/owasp-top-ten adds web-application categories. Language packs such as p/python or p/javascript go deeper at the cost of more findings. --severity filters by rule severity and can be repeated — --severity ERROR --severity WARNING is a reasonable gate setting while INFO rules stay in the report.
- Add a local rule file for the things only you care about. Registry rules cannot know about your internal conventions. Create
.semgrep.ymlat the repository root:
rules:
- id: requests-tls-verification-disabled
message: >-
TLS certificate verification is disabled on this HTTP call.
Remove verify=False, or point verify at a CA bundle path.
languages: [python]
severity: ERROR
patterns:
- pattern-either:
- pattern: requests.$METHOD(..., verify=False, ...)
- pattern: $SESSION.$METHOD(..., verify=False, ...)
- metavariable-regex:
metavariable: $METHOD
regex: ^(get|post|put|patch|delete|head|request)$
paths:
exclude:
- tests/
Three pieces of syntax are doing the work. patterns means every child must match, so this is an AND. pattern-either is the OR inside it, covering both the module-level helpers and a session object. metavariable-regex constrains what $METHOD is allowed to bind to, which stops the second pattern from matching every method call in the codebase that happens to take a verify argument. The ... is Semgrep’s ellipsis: it matches any sequence of arguments, so argument order and count do not matter.
- Check the rule is valid, then test it against known-good and known-bad code. Semgrep validates rule files without scanning anything:
semgrep --validate --config .semgrep.yml
Configuration is valid - found 1 valid rule, 0 invalid rules.
Now write a test file. Semgrep’s test runner pairs a rule file with a code file of the same basename, and reads annotation comments:
# rules/tls.py — paired with rules/tls.yaml
import requests
# ruleid: requests-tls-verification-disabled
requests.get("https://internal.example.com/health", verify=False)
# ok: requests-tls-verification-disabled
requests.get("https://internal.example.com/health", verify="/etc/ssl/certs/internal-ca.pem")
semgrep --test --config rules/
1/1: ✓ All tests passed
A rule with tests is a rule someone can safely change later. A rule without tests is one nobody dares touch.
- Wire the gate into GitHub Actions. Two behaviours in one workflow: pull requests are gated on new findings only,
maingets a full inventory scan that reports but never blocks.
# .github/workflows/semgrep.yml
name: semgrep
on:
pull_request: {}
push:
branches: [main]
permissions:
contents: read
security-events: write
jobs:
semgrep:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-python@v5
with:
python-version: '3.12'
- run: pip install semgrep
- name: Gate on new findings only
if: github.event_name == 'pull_request'
run: |
semgrep ci \
--config p/default \
--config .semgrep.yml \
--baseline-commit "${{ github.event.pull_request.base.sha }}" \
--metrics=off
- name: Full inventory scan (report only)
if: github.event_name == 'push'
run: |
semgrep scan \
--config p/default \
--config .semgrep.yml \
--sarif --output semgrep.sarif \
--metrics=off
- uses: github/codeql-action/upload-sarif@v3
if: github.event_name == 'push'
with:
sarif_file: semgrep.sarif
The fetch-depth: 0 is not optional. GitHub’s default shallow clone does not contain the base commit, and Semgrep will refuse the baseline scan. Note also that this workflow installs Semgrep with pip rather than using container: semgrep/semgrep — the container is faster, but the SARIF upload action needs a Node runtime that the Semgrep image does not provide, so mixing the two in one job fails at the last step.
A passing pull request looks like this:
Scanning 2917 files tracked by git with 1044 rules:
Scanning 41 files that changed since the baseline commit.
┌─────────────────┐
│ 0 Code Findings │
└─────────────────┘
- The GitLab CI equivalent. Same idea, different variable names, plus the native SAST report format so findings appear in the merge request widget.
# .gitlab-ci.yml
semgrep:
stage: test
image: semgrep/semgrep
variables:
GIT_DEPTH: 0
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
script:
- semgrep ci
--config p/default
--config .semgrep.yml
--baseline-commit "$CI_MERGE_REQUEST_DIFF_BASE_SHA"
--gitlab-sast --output gl-sast-report.json
--metrics=off
artifacts:
when: always
reports:
sast: gl-sast-report.json
GIT_DEPTH: 0 is GitLab’s equivalent of fetch-depth: 0. artifacts: when: always matters — without it the report is discarded on the exact runs where you most want to read it.
- Suppress a false positive the reviewable way. When a finding is genuinely wrong for one specific line, annotate the line rather than deleting the rule:
# The load balancer VIP presents a self-signed cert on its health port only.
# nosemgrep: requests-tls-verification-disabled
resp = requests.get(VIP_PROBE_URL, verify=False, timeout=2)
A bare # nosemgrep silences every rule on that line, which is almost never what you want. Naming the rule id keeps the line covered by everything else. The comment goes on the offending line or the line directly above it, and it shows up in code review, which is the point — a suppression that nobody can see is indistinguishable from a hole. If you ever need to find out how many suppressions have accumulated, semgrep scan --disable-nosemgrep ignores them all for one run.
Validate it works
Prove the gate fires, then prove it stops firing. Do it on a throwaway branch.
git checkout -b semgrep-gate-selftest
mkdir -p app && cat > app/probe.py <<'EOF'
import requests
resp = requests.get("https://internal.example.com/health", verify=False)
EOF
git add app/probe.py
git commit -m "deliberate finding for gate self-test"
semgrep ci --config .semgrep.yml --baseline-commit "$(git merge-base origin/main HEAD)" --metrics=off
echo "exit code: $?"
┌────────────────┐
│ 1 Code Finding │
└────────────────┘
app/probe.py
❯❯❱ requests-tls-verification-disabled
TLS certificate verification is disabled on this HTTP call.
2┆ resp = requests.get("https://internal.example.com/health", verify=False)
exit code: 1
Now confirm the baseline really is subtracting, rather than the gate simply being quiet. Point --baseline-commit at your own HEAD — the finding already exists there, so it should disappear:
semgrep ci --config .semgrep.yml --baseline-commit HEAD --metrics=off
echo "exit code: $?"
┌─────────────────┐
│ 0 Code Findings │
└─────────────────┘
exit code: 0
If the first command exits 1 and the second exits 0, the whole mechanism is working. Delete the branch. On the CI side, open a draft pull request that touches only a comment and confirm the check goes green even though the repository still holds hundreds of inherited findings.
Troubleshooting
Baseline scan requires a clean git tree or a similar abort. The baseline scan creates a temporary worktree, which git refuses to do with uncommitted changes in the way. Commit or stash first. In CI this never happens; locally it happens constantly.
The baseline commit is not in the clone. Symptoms are an error naming the SHA, or a scan that reports every finding in the repository as new. Almost always a shallow clone: add fetch-depth: 0 in Actions or GIT_DEPTH: 0 in GitLab. For forked pull requests, also confirm the base repository’s history is actually fetched.
Exit code 2 rather than 1. Semgrep distinguishes “I found something” from “I failed”. Exit 1 means findings; anything higher means Semgrep itself could not complete — an unreachable registry, a malformed rule file, a language it could not parse. Read stderr instead of assuming the code is dirty, and run semgrep --validate --config .semgrep.yml to rule out your own rules.
The gate blocks on a file the team does not own. Vendored dependencies, generated clients and minified bundles produce findings nobody can act on. Exclude them at the repository level in .semgrepignore, which uses gitignore syntax, or per rule with the paths: exclude key. Be aware that creating your own .semgrepignore replaces Semgrep’s built-in defaults rather than adding to them, so start by reproducing the exclusions you actually relied on.
Scans are slow enough that people notice. A full scan of a large monorepo with several language packs can run for many minutes. On pull requests, --baseline-commit already restricts the work to changed files; if it is still slow, trim the ruleset to the languages present, exclude test fixtures, and move the exhaustive run to a nightly schedule where nobody is waiting on it.
When this is the wrong approach
Semgrep is a pattern matcher over syntax. It does not do whole-program data-flow analysis across service boundaries, it does not know which of your inputs are attacker-controlled unless a rule says so, and it will not find a logic flaw in your authorisation model. Treating a green Semgrep check as evidence that code is secure is a misreading of what the tool measures.
It is also the wrong layer for dependency risk. A CVE in a transitive package is a job for a software composition scanner — see Docker image security scanning with Trivy and Grype for the container side of that, and Cosign image signing and verification if what you actually need is provenance rather than detection.
If your repository has fewer than a few thousand lines and no meaningful backlog, skip the baseline entirely and gate on the full scan — it is simpler, and there is nothing to defer. And if nobody is going to triage the findings, do not add the gate at all. A blocking check with no owner becomes a check that gets bypassed, and the bypass habit costs more than the tool was ever going to save. The reference material worth bookmarking is the Semgrep documentation and the semgrep repository for the rule schema.
If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.