Detection as Code: A Practical Guide

How to run detection as code in practice: the repository, the rule format, tests, the CI pipeline, deployment, drift, and the one failure mode commit-time tests cannot catch.

Last reviewed November 2026

Detection as code is the practice of managing detection rules the way software teams manage code: stored in version control, changed through reviewed pull requests, tested automatically, and deployed to the SIEM by a pipeline instead of edited by hand in a console.

Most explanations stop at that definition, and most teams that adopt it get stuck on the details: what goes in the repository, what a test for a detection looks like, how to deploy without breaking the console workflow everyone is used to, and what to do about the rules that already exist. This guide covers those details, for the engineers building the pipeline and the managers deciding whether it is worth the effort. For where detection as code sits in the wider discipline, see our detection engineering guide.

Why teams move to detection as code

A SIEM console is a poor place to keep a few hundred rules. Edits leave little history, nobody reviews them, and after a year a rule has been changed by four people for reasons nobody wrote down. When a rule starts misfiring, there is no diff to read.

Detection as code fixes that with tools most security teams already have:

  • History. Every change has an author, a date, a reason and a diff.
  • Review. A second engineer reads every new rule and, equally important, every new exclusion. Exclusions are where coverage quietly disappears.
  • Testing. A rule is checked before it reaches production, every time it changes.
  • Reproducibility. What is in the repository is what is running, so you can rebuild a SIEM's rule set from scratch or carry it to a new one.
  • Rollback. A bad change is reverted with one commit.

For managers there is a second benefit: the repository becomes the inventory. Rule counts, ownership, ATT&CK mapping and test coverage stop being a spreadsheet someone updates once a quarter.

What goes in the repository

One rule per file, with its metadata, its tests and nothing else. A layout that scales:

detections/
  rules/
    windows/
      credential_access/
        lsass_dump_via_procdump.yml
    linux/
    cloud/
  tests/
    lsass_dump_via_procdump/
      match_procdump_ma.json      # an event that must fire
      no_match_taskmgr.json       # a lookalike that must not
  exclusions/
    lsass_dump_via_procdump.yml   # reviewed separately, with an owner and expiry
  tools/
    lint.py
    test.py
    deploy.py

The rule format is either your SIEM's native query plus a metadata header, or a portable format such as Sigma that converts at build time. Vendors publish their own: Elastic's detection-rules repository keeps one file per rule with a metadata section and a rule section, and Splunk's security content repository follows the same pattern. Pick one schema and enforce it.

The metadata is what makes the repository useful beyond storage. At minimum:

  • A stable id, a title and a description of the behavior.
  • The ATT&CK technique.
  • The data sources and fields the rule needs.
  • Severity, and what an analyst should do when it fires.
  • An owner.
  • Known false positives.
  • A link to the research or the incident that prompted it.

Exclusions deserve their own files. Tuning a rule by adding and not user = "svc_backup" inside the query hides a coverage decision in a diff nobody will read again. A separate exclusion file with a reason, an owner and an expiry date gets reviewed as what it is.

Testing detections

Three layers of test, from cheapest to most valuable.

1. Linting and schema checks. Does the rule parse? Is every required metadata field present? Does the ATT&CK id exist? Does the query use only fields from your data dictionary? These run in seconds and catch most careless mistakes.

2. Unit tests against stored events. For each rule, keep at least one event that must match and several that must not. The non-matching events matter most: they are the lookalikes (Task Manager creating a dump file, an admin tool touching lsass) that prove the rule is specific. The test harness either runs the query against the events directly, with a local engine or a test index, or converts the rule and evaluates it in a scratch tenant.

3. Integration tests against real telemetry. Run the behavior in a lab, with an Atomic Red Team test or your own emulation, and confirm the deployed rule fires on the events your real collection pipeline produces. This is the only layer that tests your parsers and field mappings as well as the rule. It is slower, so most teams run it nightly or before a release, not on every commit.

A practical bar for "done": no rule merges without a positive test, a negative test and complete metadata.

The pipeline

A minimal continuous integration workflow, in GitHub Actions:

name: detections
on:
  pull_request:
  push:
    branches: [main]

jobs:
  validate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: pip install -r requirements.txt
      - run: python tools/lint.py rules/
      - run: python tools/test.py rules/ tests/

  deploy:
    if: github.ref == 'refs/heads/main'
    needs: validate
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: python tools/deploy.py rules/ --target production

The deploy step calls the SIEM's API with credentials from the CI secret store. Most platforms support it: Elastic and Google SecOps have rule APIs, Microsoft Sentinel can deploy from a connected repository, and Splunk saved searches can be managed through its API or packaged as an app. Deploy to a staging tenant first if you have one.

Two design choices matter more than the tooling:

  • Deploy the whole set, idempotently. The deploy script should make the SIEM match the repository, creating, updating and disabling rules as needed, rather than applying one change at a time. That way every run corrects drift.
  • Tag what the pipeline owns. Mark deployed rules so the script never touches vendor or hand-made rules it does not manage.

Drift: when the console and the repository disagree

Someone will edit a rule in the console during an incident. That is fine, and it is also how a repository stops being the truth.

Run a drift check on a schedule: export the deployed rules, compare them with the repository, and open an issue or a pull request for every difference. Then decide per case. Either the console change was right and goes into the repository, or it was a quick fix and the next deploy overwrites it. What you want to avoid is the third option, where nobody notices and the two drift apart for a year.

Starting with the rules you already have

Few teams start with an empty SIEM. The migration that works:

  1. Export everything into the repository as it is, including vendor rules you have modified. The first commit is an inventory.
  2. Add metadata and owners, and delete or disable what nobody will own.
  3. Turn on linting in CI, so new changes meet the schema.
  4. Add tests to the highest-severity rules first, then to every rule that changes.
  5. Switch on automated deployment once the repository and the SIEM match.

Expect the inventory step to be uncomfortable. It usually surfaces rules nobody remembers writing, duplicates, and rules pointed at indexes or tables that no longer exist.

What detection as code cannot catch

Every test above runs at commit time, against events you saved and assumptions you made about the data. Detection as code tells you a rule was correct when it merged. It cannot tell you the rule still works today.

After deployment, the data moves under the rule. A vendor renames a field, a parser update changes a value's format, a log source stops arriving from one region, an agent upgrade drops a field on half the fleet. The rule stays valid, keeps running and matches nothing. No test fails, because no test runs. In our Detection Debt Report, 29% of deployed, enabled rules were broken in this kind of way.

The fix is continuous validation in production: checking, on a schedule, that each rule's data sources are arriving and its fields are populated with the values it expects, and re-running positive controls after changes to the collection pipeline. We cover that layer in more depth in detection health. Spectrum's detection engineering platform works this way: it validates rules on your live data before they land in your repository as a pull request, and keeps checking them afterwards.

Measuring it

For managers, detection as code makes the following measurable, often for the first time:

  • Lead time: from a detection request to a rule running in production.
  • Change failure rate: the share of rule changes that are reverted or patched within a week.
  • Test coverage: the share of rules with both positive and negative tests.
  • Ownership: the share of rules with a named, current owner.
  • Drift: differences found between the repository and the SIEM per month.

Pair them with a measure of whether the deployed rules still fire on your data. The first five tell you the process is healthy. The last one tells you the detections are.

See what your environment is actually detecting

Spectrum maps your coverage, builds the detections you are missing, and keeps them working.