PROJECTIntermediate

OpenSCAP CIS Compliance Scanning with Ansible: Audit and Harden a Linux Fleet

Build a repeatable CIS benchmark pipeline: scan Ubuntu servers with OpenSCAP, collect HTML and XML reports with Ansible, tailor out noisy rules, and apply reviewed remediation safely.

Dylan H.

Projects

November 25, 2026
6 min read
3-5 hours
OpenSCAP CIS Compliance Scanning with Ansible: Audit and Harden a Linux Fleet

Tools & Technologies

OpenSCAPSCAP Security GuideAnsibleUbuntu Security Guide

Overview

Hardening a single server against the CIS Benchmark is a one-afternoon job. Keeping ten servers hardened, and proving it, is where most teams fall over. Configuration drifts, packages get installed, and nobody remembers which controls were deliberately skipped.

This project builds a repeatable compliance loop with free tooling:

  1. Scan each host with OpenSCAP against a CIS profile.
  2. Collect XML results and HTML reports centrally using Ansible.
  3. Tailor the profile so accepted exceptions are documented rather than ignored.
  4. Remediate with generated Ansible, reviewed and applied in check mode first.
  5. Re-scan on a schedule and track the score over time.

By the end you will have a playbook that produces a per-host compliance report and a trend you can show an auditor.

Architecture

 Control node (Ansible)
   |-- playbooks/scan.yml        --> oscap xccdf eval on each host
   |-- playbooks/remediate.yml   --> reviewed fixes, check mode first
   |-- tailoring/lab-tailoring.xml  (documented exceptions)
   `-- reports/<host>/<date>/    <-- results.xml + report.html pulled back

 Managed hosts (Ubuntu 24.04)
   `-- openscap-scanner + SCAP Security Guide datastream

Key design choices:

  • Agentless. Ansible pushes the scan over SSH. Hosts only need the scanner package.
  • Scan and remediate are separate playbooks. Remediation can disable services or tighten access, so it never runs unreviewed.
  • Tailoring over deletion. Rules you reject go into a tailoring file with a reason, so the decision survives staff changes.

Prerequisites

  • A control node with Ansible 2.15 or newer.
  • Two or more Ubuntu 24.04 test VMs. Do not start on production.
  • SSH key access and sudo on the targets.
  • A snapshot of every target before you remediate anything.

Step 1: Inventory and base setup

# inventory.ini
[linux]
srv-test-01 ansible_host=192.168.50.11
srv-test-02 ansible_host=192.168.50.12
 
[linux:vars]
ansible_user=ansible
ansible_become=true

Confirm connectivity:

ansible -i inventory.ini linux -m ping

Step 2: Install the scanner and content

Ubuntu packages the scanner as openscap-scanner. The packaged SCAP Security Guide content can lag upstream, and some Ubuntu releases do not ship a datastream for the newest LTS. Check before assuming. If the packaged content lacks your release, download the current release from the ComplianceAsCode project instead.

# playbooks/prepare.yml
- hosts: linux
  tasks:
    - name: Install OpenSCAP scanner and packaged content
      ansible.builtin.apt:
        name:
          - openscap-scanner
          - ssg-base
          - ssg-debderived
        state: present
        update_cache: true
 
    - name: List available datastreams
      ansible.builtin.find:
        paths: /usr/share/xml/scap/ssg/content
        patterns: "ssg-ubuntu*-ds.xml"
      register: ds
 
    - name: Show datastreams found
      ansible.builtin.debug:
        msg: "{{ ds.files | map(attribute='path') | list }}"

If no ssg-ubuntu2404-ds.xml appears, fetch the upstream release into a path you control and set scap_datastream in the next step. Always verify the downloaded archive against the checksum published with the release.

Inspect the available profiles on one host:

oscap info /usr/share/xml/scap/ssg/content/ssg-ubuntu2404-ds.xml | grep -i "cis"

You should see profile IDs such as xccdf_org.ssgproject.content_profile_cis_level1_server.

Step 3: The scan playbook

# playbooks/scan.yml
- hosts: linux
  vars:
    scap_datastream: /usr/share/xml/scap/ssg/content/ssg-ubuntu2404-ds.xml
    scap_profile: xccdf_org.ssgproject.content_profile_cis_level1_server
    stamp: "{{ lookup('pipe', 'date +%Y%m%d') }}"
    remote_dir: /var/tmp/oscap
  tasks:
    - name: Create working directory
      ansible.builtin.file:
        path: "{{ remote_dir }}"
        state: directory
        mode: "0700"
 
    - name: Run CIS scan
      ansible.builtin.command: >
        oscap xccdf eval
        --profile {{ scap_profile }}
        --results {{ remote_dir }}/results.xml
        --report {{ remote_dir }}/report.html
        {{ scap_datastream }}
      register: oscap_run
      changed_when: false
      failed_when: oscap_run.rc not in [0, 2]
 
    - name: Fetch reports to control node
      ansible.builtin.fetch:
        src: "{{ remote_dir }}/{{ item }}"
        dest: "reports/{{ inventory_hostname }}/{{ stamp }}/"
        flat: true
      loop:
        - results.xml
        - report.html

Exit code semantics matter. oscap returns 0 when every rule passes, 2 when one or more rules fail, and 1 on an actual error. Treating 2 as a failure would stop your play on every non-compliant host, which defeats the purpose.

Run it:

ansible-playbook -i inventory.ini playbooks/scan.yml

Open reports/srv-test-01/<date>/report.html in a browser. A fresh Ubuntu install typically scores in the 50 to 70 percent range for Level 1 Server. That is your baseline.

Step 4: Extract a score you can graph

The HTML is for humans. For trends, parse the XML:

#!/usr/bin/env bash
# scripts/score.sh - print pass/fail counts per host
for f in reports/*/*/results.xml; do
  host=$(echo "$f" | cut -d/ -f2)
  day=$(echo "$f" | cut -d/ -f3)
  pass=$(grep -c '<result>pass</result>' "$f")
  fail=$(grep -c '<result>fail</result>' "$f")
  echo "$day,$host,$pass,$fail"
done | sort

Append the output to a CSV on each run. Graphing it in a spreadsheet or Grafana gives you the drift line that auditors like to see.

Step 5: Tailor the profile

Some CIS rules do not fit your environment. A host that legitimately runs a web server will fail the "no HTTP server installed" rule. Do not edit the datastream. Create a tailoring file instead.

oscap xccdf generate fix --help   # confirm your version's options

The simplest workflow is the Ubuntu Security Guide or SCAP Workbench to generate a tailoring file, which you then commit alongside a comment explaining each exclusion. Pass it to the scan:

      ansible.builtin.command: >
        oscap xccdf eval
        --tailoring-file /var/tmp/oscap/lab-tailoring.xml
        --profile {{ scap_profile }}_lab
        --results {{ remote_dir }}/results.xml
        --report {{ remote_dir }}/report.html
        {{ scap_datastream }}

Keep a short EXCEPTIONS.md listing each excluded rule, the reason, the owner, and a review date.

Step 6: Generate and review remediation

OpenSCAP can turn a scan result into an Ansible playbook for exactly the rules that failed:

oscap xccdf generate fix \
  --fix-type ansible \
  --result-id "" \
  --output remediation-srv-test-01.yml \
  reports/srv-test-01/20261125/results.xml

Read the file before running anything. Look specifically for:

  • SSH changes (PermitRootLogin, ciphers, AllowUsers) that could lock you out.
  • Firewall rules that default-deny inbound traffic.
  • Partition or mount option changes, which may need a reboot or cannot be applied to a live system.
  • Service removals your applications depend on.

Run it in check mode first and keep a second SSH session open:

ansible-playbook -i inventory.ini remediation-srv-test-01.yml --check --diff
ansible-playbook -i inventory.ini remediation-srv-test-01.yml

Then re-scan with scan.yml and compare scores. Rules that still fail after remediation usually need a manual change or a reboot.

Testing

  1. Baseline vs. post-remediation. The score should rise noticeably and the remaining failures should match your expectations.
  2. Deliberate drift. Re-enable root SSH login on a test host, then re-run the scan. The sshd_disable_root_login rule must fail again.
  3. Exit codes. Confirm the play continues on a non-compliant host (exit 2) and fails clearly when the datastream path is wrong (exit 1).
  4. Application smoke test. After remediation, verify your services still start and respond. Hardening that breaks the workload gets reverted by someone in a hurry.
  5. Idempotence. Run remediation twice. The second run should report zero changes.

Deployment

Make it routine rather than a one-off:

  • Run scan.yml weekly from cron or a CI schedule on the control node.
  • Store reports/ on storage with limited access. Scan results list every weakness on your hosts.
  • Alert on regressions: if a host's failure count rises versus last week, open a ticket.
  • Roll remediation out in rings: test hosts first, then a single production host, then the rest.
  • Pin the SCAP content version in your repository so a content update does not change scores unexpectedly. Review the changelog when you upgrade it.

Extensions and next steps

  • Add STIG or Level 2 profiles for hosts that need stricter baselines.
  • Ubuntu Security Guide. With an Ubuntu Pro entitlement, usg audit and usg fix provide Canonical-supported CIS and STIG content, which suits fleets that need vendor-backed profiles.
  • Compare with ansible-lockdown roles and decide whether you prefer scan-then-fix or apply-then-verify.
  • Feed results into a vulnerability platform such as DefectDojo, which accepts SCAP reports, so compliance findings sit beside scanner output.
  • Build a golden image. Harden a base image once, scan it in CI, and ship only images that meet a minimum score.
  • Cover containers. oscap-podman can scan images and containers using the same content.

Lessons learned

Compliance scores are a means, not a goal. A 100 percent score with undocumented exceptions is worse than 85 percent with every gap explained. The tailoring file and exception log are the most valuable artifacts this project produces.

References