Compliance

Compliance as Code: Implementation Guide for Security Teams

Compliance as code transforms audit requirements into automated checks. This guide covers frameworks, tooling, and practical implementation for security teams.

Nayan Dey
DevSecOps Engineer
8 min read

Compliance work in most organizations follows a depressing pattern: auditors arrive, they ask for evidence, teams scramble to produce screenshots and spreadsheets, everyone agrees the findings are accurate, and remediation plans are drafted that no one follows until the next audit cycle. The entire process is manual, reactive, and disconnected from the engineering workflows where the actual security controls live.

Compliance as code breaks this cycle by expressing compliance requirements as executable code that runs continuously in your development and deployment pipelines. Instead of checking a box once a quarter, you verify every commit, every build, and every deployment against your compliance requirements in real time.

What Compliance as Code Actually Means

The concept has three layers:

Policy definition: Compliance requirements are written as code -- not in Word documents, but in a policy language that can be version-controlled, tested, and reviewed. When a regulation says "all data at rest must be encrypted," that requirement becomes a code rule that checks whether encryption is configured on every storage resource.

Automated evaluation: Policies are evaluated automatically against your infrastructure, applications, and processes. Every Terraform plan, every container image, every deployment manifest is checked against the policy set before it reaches production.

Continuous evidence collection: The results of policy evaluations are recorded as audit evidence. Instead of producing screenshots during audit season, you have a continuous stream of compliance data that shows your posture at any point in time.

Policy Languages and Frameworks

Open Policy Agent (OPA) / Rego

OPA is the most widely adopted general-purpose policy engine. It evaluates policies written in Rego, a declarative query language designed for policy decisions.

OPA's strength is its generality. The same policy engine can evaluate Kubernetes admission requests, Terraform plans, API authorization decisions, and SBOM compliance checks. This means you can express policies from multiple compliance frameworks in a single, consistent language.

A simple Rego policy to enforce container image signing:

package kubernetes.admission

deny[msg] {
    input.request.kind.kind == "Pod"
    container := input.request.object.spec.containers[_]
    not container_signed(container.image)
    msg := sprintf("Container image %v is not signed", [container.image])
}

Chef InSpec

InSpec is a compliance-as-code framework that excels at infrastructure testing. It was designed specifically for compliance use cases and has a large library of pre-built profiles for common frameworks (CIS Benchmarks, NIST 800-53, SOC 2).

InSpec profiles read naturally:

control 'aws-s3-encryption' do
  impact 1.0
  title 'S3 buckets should have encryption enabled'
  describe aws_s3_bucket(bucket_name: 'my-bucket') do
    it { should have_default_encryption_enabled }
  end
end

InSpec's advantage is readability. Auditors who do not write code can still read and understand InSpec profiles, which bridges the gap between compliance and engineering teams.

HashiCorp Sentinel

Sentinel is HashiCorp's policy-as-code framework, integrated with Terraform Cloud, Vault, Consul, and Nomad. If you are in the HashiCorp ecosystem, Sentinel provides the tightest integration for infrastructure policy enforcement.

AWS Config Rules / Azure Policy / Google SCC

Each major cloud provider has a native policy engine. These are useful for cloud-specific compliance but do not extend to application-level or cross-cloud requirements.

Mapping Compliance Frameworks to Code

The hardest part of compliance as code is not writing the policies -- it is mapping regulatory requirements to testable assertions.

Take NIST 800-53 control AC-6 (Least Privilege). The control text says the organization "employs the principle of least privilege, allowing only authorized accesses for users." How do you test that?

You decompose the control into specific, measurable assertions:

  • IAM policies do not use wildcard actions (Action: "*")
  • IAM policies do not use wildcard resources (Resource: "*")
  • Service accounts have role bindings scoped to specific namespaces, not cluster-wide
  • Database users have access only to the tables their service requires
  • Lambda functions have IAM roles scoped to the specific resources they access

Each assertion becomes a policy rule. Collectively, the rules provide evidence that AC-6 is implemented. This decomposition is where compliance expertise and engineering expertise must collaborate.

Framework Coverage

Common compliance frameworks and their code-testable coverage:

SOC 2: 60-70% of criteria can be directly tested through infrastructure and application controls. The remainder (organizational controls, HR processes) require non-technical evidence.

PCI DSS: High automation potential for network segmentation, encryption, access control, and logging requirements. Physical security and governance controls remain manual.

HIPAA: Technical safeguards (access control, audit logging, encryption, integrity controls) are highly automatable. Administrative safeguards are less so.

NIST 800-171/CMMC: Many controls around access control, configuration management, and system integrity can be automated. Risk assessment and planning controls require human judgment.

FedRAMP: Similar to NIST 800-53 with additional continuous monitoring requirements that are naturally suited to compliance as code.

CI/CD Integration

Pre-Commit Checks

Run lightweight policy checks as pre-commit hooks. This gives developers immediate feedback on policy violations before code is even committed. Keep these checks fast (under 10 seconds) to avoid developer friction.

Pull Request Checks

Run the full policy suite on every pull request. Present results as PR status checks with clear descriptions of what failed and how to fix it. Block merges on critical policy violations.

Build Pipeline Gates

Integrate policy evaluation as a pipeline stage. Every build is evaluated against the current policy set, and violations at specified severity levels block the pipeline.

Deployment Admission

For Kubernetes environments, use admission controllers (OPA Gatekeeper, Kyverno) to enforce policies at deployment time. This is the last line of defense before a non-compliant resource reaches production.

Continuous Monitoring

Run policy evaluations on a schedule against your running infrastructure. This catches drift -- resources that were compliant at deployment but have been modified since.

SBOM Compliance Policies

Software supply chain compliance is an increasingly important domain for compliance as code. Common SBOM-related policies include:

License compliance: All components must have approved licenses. Deny components with copyleft licenses in proprietary products. Flag components with no declared license.

Vulnerability thresholds: No components with critical CVEs in production. No components on the CISA KEV list without documented risk acceptance. Maximum EPSS score threshold for automated blocking.

Provenance requirements: All components must have verifiable provenance. Container images must be signed. Packages must come from approved registries.

Age and maintenance: Flag components that have not been updated in over 2 years. Alert on components with no active maintainers. Require review for components with fewer than a threshold number of contributors.

These policies can be expressed in OPA/Rego and evaluated against SBOM data in the CI/CD pipeline.

Evidence Management

Compliance as code generates evidence continuously. Managing this evidence is as important as generating it.

Store evaluation results immutably. Every policy evaluation -- pass or fail -- should be stored in a tamper-evident log. This provides the audit trail that demonstrates continuous compliance.

Link evidence to specific artifacts. Each evaluation result should reference the specific commit, build, or deployment it applies to. This traceability is essential for incident investigation and audit response.

Generate compliance reports automatically. Map stored evaluation results back to the compliance framework controls they satisfy. This produces audit-ready reports without manual effort.

Retain evidence according to regulatory requirements. Different frameworks have different retention requirements. SOC 2 requires evidence from the audit period. HIPAA requires 6 years. PCI DSS requires 1 year.

Organizational Change Management

The technical implementation is the easier half. The harder half is organizational.

Get compliance team buy-in early. If your compliance team does not trust automated evidence, the effort is wasted. Involve them in policy development so they understand and validate the automated checks.

Start with a single framework. Do not try to automate SOC 2, PCI DSS, and HIPAA simultaneously. Pick one, demonstrate value, and expand.

Accept partial automation. Not every compliance requirement can be automated. Aim for 60-70% automation in the first iteration and increase coverage over time.

Invest in the mapping. The mapping from regulatory language to testable assertions is the intellectual core of the program. Rushing this step produces policies that are technically sound but do not actually satisfy the compliance requirement.

How Safeguard.sh Helps

Safeguard.sh provides compliance-as-code capabilities for software supply chain requirements. Policy gates in Safeguard.sh let you define compliance rules for vulnerability thresholds, license restrictions, provenance requirements, and component age -- all evaluated automatically against every SBOM in your pipeline.

The audit trail captures every policy evaluation, every vulnerability finding, and every remediation action, producing the evidence stream that compliance as code requires. When auditors ask for evidence of your vulnerability management process, you do not scramble for screenshots. You generate a report from Safeguard.sh that shows every evaluation from the audit period, with full traceability from policy to finding to remediation.

Never miss an update

Weekly insights on software supply chain security, delivered to your inbox.