Automated Compliance as Code

Automated compliance as code applies security, governance, and compliance requirements through machine-readable policies that automatically enforce standards across cloud infrastructure, CI/CD pipelines, containers, Kubernetes clusters, and applications. Instead of manually checking controls, compliance as code uses continuous automation to validate, report, and remediate deviations. This ensures every environment stays secure, compliant, and auditable at all times.

Understanding Compliance as Code

Compliance as code treats compliance rules the same way developers treat application code:

• version-controlled
• automated
• reusable
• testable
• continuously enforced

Policies become code files instead of documents. Automated engines evaluate cloud configurations, deployments, and workloads against these rules in real time.

This eliminates manual checklists and transforms compliance into a fully automated system.

Why Automated Compliance Matters

Traditional compliance is slow, manual, error-prone, and always outdated. Automated compliance as code solves this by:

• enforcing policies during development
• blocking insecure deployments
• continuously monitoring cloud resources
• automatically remediating violations
• generating evidence for audits
• detecting drift immediately
• scaling compliance across accounts

Compliance no longer slows development—automation makes it seamless.

Core Components of Compliance as Code

Policy Definition

Rules written in:

• OPA Rego
• CloudFormation Guard
• Sentinel
• Checkov policies
• AWS Config rules
• Terraform validate rules

Policies define required security configurations.

Policy Execution

Automated scanners evaluate resources against policy definitions:

• Checkov
• Terrascan
• KICS
• OPA Conftest
• AWS Config
• Azure Policy
• GCP Policy Controller

Continuous Monitoring

Tools track real-time drift across cloud resources:

• AWS Config
• Security Hub
• Azure Defender
• GCP SCC

Automated Remediation

When misconfiguration occurs, automation fixes it using:

• Lambda functions
• EventBridge
• Cloud Custodian
• custom webhooks
• Terraform automation

Compliance becomes self-healing.


Policy-as-Code Technologies

OPA (Open Policy Agent)

Generic policy engine for Kubernetes, Terraform, Docker, CI pipelines.

Conftest

OPA Rego for scanning config files (YAML, JSON, Terraform).

AWS CloudFormation Guard

Policy framework for enforcing AWS CloudFormation compliance.

Terraform Sentinel

Access control for Terraform Enterprise.

Checkov Custom Policies

Write YAML or Python-based custom compliance rules.

Terrascan Rego Policies

OPA-based compliance for IaC.

Cloud Custodian

Automated enforcement and remediation across cloud resources.


Compliance Categories Enforced

Identity and Access Management

• MFA required
• no wildcard IAM policies
• forbidden root usage
• restrict PassRole privileges

Data Protection

• encryption at rest
• encryption in transit
• KMS key enforcement

Networking

• deny 0.0.0.0/0 rules
• restrict public ELBs
• enforce firewall rules

Logging and Monitoring

• CloudTrail enabled
• VPC Flow Logs required
• S3 access logs enabled

Storage

• no public S3 buckets
• enforce block public access
• encryption required

Compute

• EC2 must be private
• container images must be scanned
• securityContext required in Kubernetes

Compliance as code allows all of these to be automated.


Policy-as-Code Examples

OPA Rego Example (Deny Public S3 Buckets)

package s3

deny[msg] {
  input.Properties.AccessControl == "PublicRead"
  msg = "Public S3 buckets are not allowed"
}

CloudFormation Guard Example (Encryption Required)

AWS::S3::Bucket {
  Properties.BucketEncryption.ServerSideEncryptionConfiguration exists
}

Terraform Sentinel Example (No 0.0.0.0/0)

deny if rule.security_groups.ingress.cidr_blocks contains "0.0.0.0/0"

Integrating Compliance as Code in CI/CD

• Scan IaC before merge
• Block PRs violating policies
• Validate container images
• Validate Kubernetes manifests
• Enforce policy with OPA in GitHub Actions

Example GitHub pipeline:

- name: Compliance Scan
  run: conftest test k8s/

Every commit becomes compliant before deployment.


Continuous Cloud Compliance

AWS

Use:

• AWS Config
• Security Hub
• GuardDuty
• Inspector

Config rules evaluate resources against best practices.

Azure

Use:

• Azure Policy
• Defender for Cloud
• Sentinel

GCP

Use:

• Policy Controller
• Security Command Center

Cloud-native tools continuously enforce and report compliance.


Automated Remediation Workflows

When a rule fails, automation fixes it:

AWS Example

EventBridge → Lambda:

• detect public S3 bucket
• Lambda applies block public access

Kubernetes Example

OPA Gatekeeper:

• deny deployment with privileged container

Terraform Example

Terraform Cloud Policy Override prevents apply.

Automation ensures systems never stay non-compliant.


Full-Length Practical Section

Extensive practicals for mastering compliance as code.


Practical 1: Install OPA and Conftest

Install OPA:

curl -L -o opa https://openpolicyagent.org/downloads/latest/opa_linux_amd64
chmod +x opa

Install Conftest:

curl -L https://github.com/open-policy-agent/conftest/releases/latest/download/conftest-linux-amd64 -o conftest
chmod +x conftest

Practical 2: Write a Basic Compliance Policy

Create policy:

package docker

deny[msg] {
  input.Config.User == ""
  msg = "Container must not run as root"
}

Test:

conftest test Dockerfile

Practical 3: Build Kubernetes Compliance Rules

Create rule:

deny[msg] {
  input.spec.containers[_].securityContext.runAsNonRoot != true
  msg = "Containers must run as non-root"
}

Test:

conftest test k8s/

Practical 4: Enforce Terraform Compliance

Write rule:

package tf

deny[msg] {
  input.resource.aws_security_group_rule.cidr_blocks[_] == "0.0.0.0/0"
  msg = "Open ingress not allowed"
}

Run:

conftest test terraform/

Practical 5: Scan CloudFormation With CloudFormation Guard

Rule:

AWS::RDS::DBInstance {
  Properties.StorageEncrypted == true
}

Check:

cfn-guard validate -r rules.guard -d template.yml

Practical 6: Check IaC With Checkov Custom Policies

Create custom YAML policy:

metadata:
  name: NoPublicS3
  guidelines: "S3 buckets must not be public"
definition:
  and:
    - cond_type: attribute
      resource_types:
        - AWS::S3::Bucket
      attribute: AccessControl
      operator: not_equals
      value: PublicRead

Run:

checkov -d .

Practical 7: Create Automated Remediation With Cloud Custodian

Policy:

policies:
  - name: s3-block-public
    resource: s3
    filters:
      - type: cross-account
    actions:
      - block-public-access

Run:

custodian run -s output policy.yml

Practical 8: Use Terraform Sentinel Enforcement

Add Sentinel policy requiring encryption.

Test in Terraform Enterprise workspace.


Practical 9: Deploy OPA Gatekeeper in Kubernetes

Install:

kubectl apply -f gatekeeper.yaml

Create constraint disallowing privileged pods.


Practical 10: Integrate Compliance in GitHub Actions

Step:

- name: Run compliance tests
  run: conftest test .

Blocks non-compliant PRs.


Practical 11: Scan With Terrascan

terrascan scan -d .

Evaluate OPA-based cloud policies.


Practical 12: CloudFormation Continuous Evaluation

Set CloudFormation Guard + CodePipeline to block insecure stacks.


Practical 13: Create Audit Dashboard With Security Hub

Enable Security Hub and ingest findings from:

• Config
• GuardDuty
• Inspector


Practical 14: Use EventBridge for Real-Time Compliance Alerts

Route Config non-compliant events to Lambda.


Practical 15: Auto-Fix Open Security Group Rules

Lambda script closes port 22/3389 if exposed to 0.0.0.0/0.


Practical 16: Policy Testing in Local Dev Flow

Add pre-commit hook:

conftest test .
checkov -d .
terrascan scan -d .

Practical 17: Multi-Cloud Compliance

Scan:

• AWS
• Azure ARM
• GCP Deployment Manager

With KICS or Terrascan.


Practical 18: Drift Detection

Use Config or Terraform Cloud to detect infrastructure drift.


Practical 19: Implement Compliance Waivers

Define conditions for exceptions using Conftest policy files.


Practical 20: Build Full Compliance-as-Code Architecture

Architecture includes:

• OPA Rego policy library
• Checkov scanning for IaC
• Terrascan for enterprise governance
• KICS for multi-cloud scanning
• AWS Config for real-time resource evaluation
• GuardDuty + Security Hub for continuous monitoring
• Cloud Custodian for auto-remediation
• CodePipeline/CircleCI/GitHub CI enforcement
• OPA Gatekeeper for Kubernetes admission control
• SBOM + signing for supply-chain compliance
• central Git repo for policy definitions

This creates a fully automated, audit-ready, continuously compliant environment.


Intel Dump

• Compliance as code replaces manual security checks with automated policies
• Use OPA, Conftest, Checkov, Terrascan, KICS, cfn-guard, Sentinel for enforcement
• Apply rules in CI, CD, Kubernetes admissions, and cloud runtime
• Use Config, Security Hub, GuardDuty, Inspector for continuous monitoring
• Auto-remediate misconfigurations using Lambda or Cloud Custodian
• Practicals include writing policies, scanning across IaC types, CI integration, cloud enforcement, and full compliance-as-code architecture

HOME LEARN COMMUNITY DASHBOARD