KCSA — Compliance Automation

7 minute read

Compliance Automation

Manual compliance checking does not scale. Modern Kubernetes environments require automated, continuous compliance — verifying security controls on every change, not just during periodic audits. For the KCSA exam, you must understand the concepts behind compliance automation, the tools available, and how GitOps enables continuous compliance.


Why Automate Compliance?

Traditional compliance involves periodic audits — perhaps quarterly or annually. Between audits, the cluster can drift from its compliant state without anyone noticing.

Approach Frequency Gap Detection Scale Audit Trail
Manual Audit Quarterly/Annually Only during audit windows Limited by human effort Manual documentation
Automated Compliance Continuous (every change) Immediate Scales to thousands of clusters Automatic and complete

Automated compliance solves four key problems:

  1. Scale — organizations with hundreds of clusters cannot audit manually
  2. Consistency — automated checks apply the same rules everywhere, every time
  3. Speed — violations are detected in seconds, not months
  4. Audit trail — every check, result, and remediation is automatically recorded

Compliance automation shifts from “prove we were compliant during the last audit” to “prove we are compliant right now.”


Policy-as-Code

Policy-as-Code is the practice of defining compliance rules, security policies, and governance requirements as machine-readable code rather than human-readable documents.

Key Principles

Principle Description
Declarative Policies describe the desired state, not the steps to achieve it
Version-controlled Policies live in Git, with full history and review process
Testable Policies can be unit-tested before deployment
Reusable Policy libraries can be shared across teams and clusters
Auditable Every policy change is tracked in source control

Policy-as-Code vs Traditional Policy

Aspect Traditional Policy Policy-as-Code
Format PDF document, wiki page Rego, YAML, Python, or JSON
Enforcement Manual review, human judgment Automated admission control, CI/CD gates
Updates Document revision, email notification Git commit, pull request, automated deployment
Verification Periodic audit Continuous scanning
Consistency Varies by reviewer Identical enforcement every time

Example: Policy-as-Code with OPA/Gatekeeper

A traditional policy document might state: “All containers must run as non-root.”

As code (Gatekeeper ConstraintTemplate):

apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
  name: k8srequirenonroot
spec:
  crd:
    spec:
      names:
        kind: K8sRequireNonRoot
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package k8srequirenonroot
        violation[{"msg": msg}] {
          container := input.review.object.spec.containers[_]
          not container.securityContext.runAsNonRoot
          msg := sprintf("Container %v must set runAsNonRoot to true", [container.name])
        }

The code-based policy is enforceable — Kubernetes will automatically reject non-compliant workloads at admission time.


Tools for Compliance Automation

The Kubernetes ecosystem offers multiple tools for compliance automation, each with different approaches and strengths.

Tool Type Policy Language Scope Enforcement Point
OPA/Gatekeeper Admission + Audit Rego K8s resources Admission webhook + periodic audit
Kyverno Admission + Audit YAML (native K8s) K8s resources Admission webhook + background scan
Checkov IaC scanning Python rules + YAML Terraform, K8s manifests, Helm CI/CD pipeline
Trivy Misconfiguration scanning Rego + built-in rules K8s, Docker, IaC files CI/CD pipeline + cluster scan
Kubaudit Cluster audit Built-in rules Running cluster CLI / CI/CD

OPA/Gatekeeper

Open Policy Agent (OPA) is a general-purpose policy engine. Gatekeeper is the Kubernetes-native integration of OPA that acts as an admission controller.

Feature Description
Policy language Rego (declarative query language)
Enforcement Validating admission webhook — blocks non-compliant resources
Audit mode Scans existing resources for violations (not just new resources)
Constraint system Templates define policy logic; Constraints apply templates to specific resources
Ecosystem Large library of community-maintained policies

Gatekeeper’s audit mode is critical for compliance — it catches resources that were created before a policy was deployed.

Kyverno

Kyverno is a Kubernetes-native policy engine that uses YAML policies instead of a separate language.

Feature Description
Policy language YAML — same language as Kubernetes manifests
Enforcement Validating and mutating admission webhooks
Generate Can automatically create resources (e.g., NetworkPolicy for every new namespace)
Background scan Scans existing resources for compliance
Policy reports Generates Kubernetes-native PolicyReport resources

Example Kyverno policy — require non-root containers:

apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: require-run-as-nonroot
spec:
  validationFailureAction: Enforce
  rules:
  - name: run-as-non-root
    match:
      any:
      - resources:
          kinds:
          - Pod
    validate:
      message: "Containers must run as non-root."
      pattern:
        spec:
          containers:
          - securityContext:
              runAsNonRoot: true

Checkov

Checkov is a static analysis tool that scans infrastructure-as-code for misconfigurations.

Feature Description
Scope Terraform, CloudFormation, Kubernetes YAML, Helm charts, Dockerfiles
Policy format Python-based rules and YAML-based custom policies
Integration CI/CD pipelines (GitHub Actions, GitLab CI, Jenkins)
Built-in checks Hundreds of built-in rules for common misconfigurations

Checkov catches compliance issues before deployment — in the CI/CD pipeline.

Trivy

Trivy (from Aqua Security) is a comprehensive scanner that covers vulnerabilities, misconfigurations, secrets, and licenses.

Feature Description
Scope Container images, K8s manifests, Terraform, Dockerfiles, Git repos
Misconfiguration scanning Built-in rules + custom Rego policies
Kubernetes operator Trivy Operator runs continuous scanning inside the cluster
CI/CD integration Runs in pipelines as a pre-deployment gate

Kubaudit

Kubaudit audits a running Kubernetes cluster against a set of built-in security rules.

Feature Description
Scope Running cluster security audit
Checks Privileged containers, root users, capabilities, host networking, default SA tokens
Output Findings with severity levels
Modes Cluster mode (live scan) and manifest mode (static scan)

Continuous Compliance

Continuous compliance means verifying security controls on every change, not just during scheduled audits.

Continuous Compliance Architecture

┌──────────────┐    ┌──────────┐    ┌───────────────┐    ┌─────────────┐
│  Developer    │───▶│  Git     │───▶│  CI/CD        │───▶│  Kubernetes │
│  writes YAML  │    │  Repo    │    │  Pipeline     │    │  Cluster    │
└──────────────┘    └──────────┘    └───────────────┘    └─────────────┘
                                          │                      │
                                    ┌─────▼──────┐      ┌───────▼────────┐
                                    │  Checkov   │      │  Gatekeeper/   │
                                    │  Trivy     │      │  Kyverno       │
                                    │  kubesec   │      │  (Admission)   │
                                    └────────────┘      └────────────────┘
                                    Pre-deploy scan     Runtime enforcement

Three Layers of Continuous Compliance

Layer When Tools What It Catches
Pre-commit Before code is committed Pre-commit hooks, local scanning Obvious misconfigurations, secrets in code
CI/CD Pipeline Before deployment Checkov, Trivy, kubesec Policy violations, vulnerabilities, misconfigurations
Runtime Admission At deployment time OPA/Gatekeeper, Kyverno Non-compliant resources trying to enter the cluster

A defense-in-depth approach uses all three layers — catching issues as early as possible while still enforcing at the cluster level.


Drift Detection

Drift occurs when the actual state of a cluster diverges from the desired state defined in source control.

Common Causes of Drift

  • Manual kubectl edit or kubectl patch commands that bypass Git
  • Emergency hotfixes applied directly to the cluster
  • External controllers or operators modifying resources
  • Automated scaling or mutation webhooks changing resource specs

Detecting Drift

Method How It Works
GitOps reconciliation ArgoCD or Flux continuously compares cluster state to Git — highlights drift
Gatekeeper audit Scans existing resources against policies — finds resources that violate current rules
Kyverno background scan Checks existing resources in the background — reports violations
Infrastructure scanning Trivy Operator or Checkov scan running cluster state

Responding to Drift

Strategy Description
Auto-remediate GitOps tool automatically reverts changes to match Git (ArgoCD auto-sync)
Alert and manual fix Detection triggers an alert; human reviews and decides
Block at admission Prevent drift-causing changes with admission controllers

GitOps for Compliance

GitOps uses Git as the single source of truth for infrastructure and application configuration. This naturally supports compliance because:

GitOps Property Compliance Benefit
Version control Complete audit trail of every change
Pull requests Mandatory review before any change reaches the cluster
Immutable history Git log serves as proof of who changed what and when
Reconciliation Continuous drift detection — cluster always matches Git
Rollback Any change can be reverted to a known-good state

Git becomes your compliance evidence — auditors can review the Git history to verify that all changes went through proper approval processes.


Compliance Dashboards and Reporting

Automated compliance generates data that should be presented through dashboards and reports.

Key Metrics

Metric Description
Compliance score Percentage of checks passing (e.g., “87% CIS compliant”)
Violation trend Number of violations over time (should decrease)
Mean time to remediation Average time from violation detection to fix
Policy coverage Percentage of resources covered by policies
Drift events Number of times cluster state diverged from Git

Reporting for Different Audiences

Audience Report Type Content Focus
Security team Technical detail Specific violations, affected resources, remediation steps
Management Executive summary Compliance scores, trends, risk posture
Auditors Evidence package Policy definitions, enforcement logs, change history
Developers Actionable feedback What failed, why, and how to fix it

Key Takeaways for the Exam

Concept What to Remember
Policy-as-Code Compliance rules defined as machine-readable code, version-controlled in Git
OPA/Gatekeeper General-purpose policy engine using Rego; admission control + audit mode
Kyverno Kubernetes-native policy engine using YAML; validate, mutate, and generate
Checkov IaC scanner for CI/CD pipelines — catches issues before deployment
Trivy Comprehensive scanner: vulnerabilities, misconfigurations, secrets, licenses
Continuous compliance Three layers: pre-commit, CI/CD pipeline, runtime admission
Drift detection Actual state vs desired state — caught by GitOps reconciliation, Gatekeeper audit, Kyverno background scan
GitOps Git as single source of truth = built-in audit trail, review process, and rollback
Compliance dashboards Track compliance score, violation trends, remediation time, policy coverage

Next: Regulatory & Data Protection

Updated: