Lab 04 — Kubernetes Compliance Automation
Mission Information
Section titled “Mission Information”| Item | Details |
|---|---|
| Lab ID | K8S-COMPLIANCE-LAB-04 |
| Difficulty | Advanced |
| Estimated Time | 6–8 Hours |
| Environment | Kubernetes Training Cluster and CI/CD Environment |
| Platform | Kubernetes, kube-bench, Trivy, Kyverno, Gatekeeper, GitHub Actions or GitLab CI |
| Cost | Free for Local Tools / CI/CD Usage Limits May Apply |
| Primary Role | Kubernetes Security Engineer |
| Supporting Roles | DevSecOps Engineer, Cloud Security Engineer, Compliance Analyst, Platform Engineer, SOC Analyst |
| Module | Kubernetes Benchmarks & Compliance |
| Previous Lab | Lab 03 — Kyverno Policies |
| Next Lab | Lab 05 — Kubernetes Governance Assessment |
Mission Scenario
Section titled “Mission Scenario”CloudNova Technologies has implemented:
- CIS Kubernetes Benchmark assessments
- OPA Gatekeeper policies
- Kyverno validation and mutation policies
- Image vulnerability scanning
- Container-image signing
- Admission controls
- Registry governance
However, most compliance activities still depend on manual execution.
Security engineers currently perform the following tasks individually:
- Run kube-bench
- Export Kyverno PolicyReports
- Review Gatekeeper violations
- Scan deployment manifests
- Scan container images
- Collect cluster configuration evidence
- Create compliance reports
- Notify resource owners
- Track remediation manually
This approach creates several problems:
- Assessments are inconsistent.
- Evidence is collected in different formats.
- Compliance drift may remain undetected.
- Reports are delayed.
- Failed controls do not automatically block deployments.
- Security teams spend excessive time repeating operational tasks.
- Audit preparation requires manual reconstruction of evidence.
- Management has no central view of Kubernetes compliance status.
The CISO has directed Cloud Security Engineering to implement an automated compliance framework.
Your mission is to build an enterprise workflow that continuously evaluates Kubernetes security controls, records evidence, produces reports, blocks non-compliant changes, and supports remediation tracking.
Learning Objectives
Section titled “Learning Objectives”By completing this lab, you will learn how to:
- Design Kubernetes compliance automation
- Automate CIS Benchmark assessments
- Automate manifest configuration scanning
- Automate container-image scanning
- Export Kyverno policy results
- Export Gatekeeper violations
- Create CI/CD compliance gates
- Run scheduled Kubernetes assessments
- Store compliance evidence
- Generate machine-readable reports
- Build compliance summaries
- Define failure thresholds
- Track remediation ownership
- Design compliance dashboards
- Integrate compliance findings with security operations
- Produce an enterprise automation assessment
Enterprise Compliance Automation Architecture
Section titled “Enterprise Compliance Automation Architecture” Source Repository
│
▼
CI/CD Pipeline
┌──────────────────┼──────────────────┐ │ │ │
Manifest Scan Image Scan Policy Validation
│ │ │
└──────────────────┼──────────────────┘
│
Security Gate
┌─────────┴─────────┐ │ │
Pass Fail
│ │
▼ ▼
Deployment Pipeline Blocked
│
▼
Kubernetes Cluster
│
┌──────────────────┼──────────────────┐ │ │ │
kube-bench Kyverno Reports Gatekeeper Audit
│ │ │
└──────────────────┼──────────────────┘
│
▼
Compliance Evidence Store
│
┌─────────────┼─────────────┐ │ │ │
Dashboard SIEM Audit ReportCompliance Automation Workflow
Section titled “Compliance Automation Workflow”Discover
│
▼
Assess
│
▼
Validate
│
▼
Record Evidence
│
▼
Calculate Compliance
│
▼
Notify Owners
│
▼
Remediate
│
▼
ReassessAutomation Principles
Section titled “Automation Principles”The compliance workflow should follow these principles:
- Assess controls continuously rather than only before audits.
- Store evidence in consistent machine-readable formats.
- Use immutable timestamps for every assessment.
- Separate informational findings from deployment-blocking findings.
- Assign ownership to every failed control.
- Apply risk-based thresholds.
- Retain evidence according to compliance requirements.
- Test automation before applying it to production.
- Prevent pipeline bypass without approved exception.
- Protect compliance reports from unauthorised modification.
- Avoid storing credentials in workflow files.
- Make failed controls visible to both engineering and security teams.
Lab Outcomes
Section titled “Lab Outcomes”By the end of this lab, you will have:
- Created an automated compliance workspace
- Built a Kubernetes cluster inventory script
- Automated kube-bench execution
- Automated Trivy configuration scanning
- Automated container-image scanning
- Exported Kyverno PolicyReports
- Exported Gatekeeper violations
- Built compliance threshold logic
- Created a consolidated compliance report
- Created a Kubernetes CronJob for scheduled assessments
- Designed a CI/CD compliance pipeline
- Tested pipeline pass and failure conditions
- Created a remediation tracker
- Designed evidence-retention controls
- Produced an enterprise compliance-automation report
Important Security Notice
Section titled “Important Security Notice”Perform this lab only in an authorised Kubernetes environment.
Do not:
- Run privileged assessment containers in production without approval
- Store cluster administrator credentials in Git
- Upload confidential reports to public repositories
- Expose Kubernetes Secrets in pipeline logs
- Disable policy engines to make automation pass
- Alter findings without documenting the reason
- Automatically remediate production systems without change control
- Delete evidence associated with an investigation or audit
- Treat every automated finding as confirmed without validation
- Allow developers to modify compliance thresholds without governance
Prerequisites
Section titled “Prerequisites”Before starting, ensure that you have:
- A Kubernetes training cluster
kubectl- Helm
- Docker or Podman
- kube-bench
- Trivy
jq- Git
- Kyverno from Lab 03
- Gatekeeper from Lab 02 where retained
- Cluster administrator or approved read-only assessment access
- Visual Studio Code
- Git Bash or PowerShell
- Optional GitHub or GitLab repository
- Optional CI/CD runner
- Basic shell scripting knowledge
Tools Used
Section titled “Tools Used”| Tool | Purpose |
|---|---|
| kubectl | Cluster discovery and evidence collection |
| kube-bench | CIS Kubernetes Benchmark assessment |
| Trivy | Kubernetes configuration and image scanning |
| Kyverno | Policy validation and reporting |
| Gatekeeper | Policy enforcement and audit reporting |
| jq | JSON processing |
| Bash or PowerShell | Automation scripting |
| GitHub Actions or GitLab CI | CI/CD compliance gates |
| CronJob | Scheduled in-cluster assessments |
| Git | Version-controlled automation |
| SIEM or Dashboard | Central reporting and monitoring |
Recommended Lab File Structure
Section titled “Recommended Lab File Structure”lab-04-compliance-automation/├── scripts/│ ├── collect-cluster-inventory.sh│ ├── run-kube-bench.sh│ ├── scan-manifests.sh│ ├── scan-images.sh│ ├── export-kyverno-reports.sh│ ├── export-gatekeeper-violations.sh│ ├── evaluate-compliance.sh│ └── generate-summary.sh├── powershell/│ ├── Collect-ClusterInventory.ps1│ ├── Run-KubeBench.ps1│ └── Generate-ComplianceSummary.ps1├── manifests/│ ├── namespace.yaml│ ├── service-account.yaml│ ├── role.yaml│ ├── rolebinding.yaml│ ├── configmap.yaml│ ├── compliance-cronjob.yaml│ ├── compliant-deployment.yaml│ └── non-compliant-deployment.yaml├── policies/│ ├── compliance-thresholds.json│ ├── exception-register.yaml│ └── evidence-retention-policy.md├── pipeline/│ ├── github-actions-compliance.yaml│ └── gitlab-compliance.yml├── reports/│ ├── cluster-inventory.json│ ├── kube-bench.json│ ├── manifest-scan.json│ ├── image-scan.json│ ├── kyverno-policyreports.yaml│ ├── gatekeeper-violations.yaml│ ├── compliance-summary.json│ ├── remediation-tracker.md│ └── enterprise-compliance-report.md└── evidence/ ├── execution-log.txt ├── tool-versions.txt ├── assessment-timestamp.txt ├── pipeline-result.txt ├── cronjob-result.txt └── screenshots/Task 01 — Create the Lab Workspace
Section titled “Task 01 — Create the Lab Workspace”Git Bash
Section titled “Git Bash”mkdir -p lab-04-compliance-automation/{scripts,powershell,manifests,policies,pipeline,reports,evidence/screenshots}
cd lab-04-compliance-automationPowerShell
Section titled “PowerShell”New-Item -ItemType Directory -Force ` -Path lab-04-compliance-automation\scripts
New-Item -ItemType Directory -Force ` -Path lab-04-compliance-automation\powershell
New-Item -ItemType Directory -Force ` -Path lab-04-compliance-automation\manifests
New-Item -ItemType Directory -Force ` -Path lab-04-compliance-automation\policies
New-Item -ItemType Directory -Force ` -Path lab-04-compliance-automation\pipeline
New-Item -ItemType Directory -Force ` -Path lab-04-compliance-automation\reports
New-Item -ItemType Directory -Force ` -Path lab-04-compliance-automation\evidence\screenshots
Set-Location lab-04-compliance-automationTask 02 — Record Tool Versions
Section titled “Task 02 — Record Tool Versions”Run:
kubectl version --clienthelm versiontrivy versionkube-bench versionjq --versionSave the results.
{ kubectl version --client helm version trivy version kube-bench version jq --version} > evidence/tool-versions.txt 2>&1Task 03 — Record the Assessment Timestamp
Section titled “Task 03 — Record the Assessment Timestamp”Git Bash
Section titled “Git Bash”date -u +"%Y-%m-%dT%H:%M:%SZ" \ > evidence/assessment-timestamp.txtPowerShell
Section titled “PowerShell”(Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ") | Out-File evidence\assessment-timestamp.txtEvery automated assessment should include:
- Start time
- End time
- Cluster
- Environment
- Tool versions
- Automation version
- Operator or service identity
Task 04 — Validate Cluster Access
Section titled “Task 04 — Validate Cluster Access”kubectl cluster-infokubectl config current-contextkubectl auth can-i get pods --all-namespaceskubectl auth can-i get deployments --all-namespacesUse read-only permissions where possible.
Task 05 — Create the Compliance Namespace
Section titled “Task 05 — Create the Compliance Namespace”Create manifests/namespace.yaml.
apiVersion: v1kind: Namespacemetadata: name: compliance-automation labels: app: compliance-automation owner: cloud-security environment: training pod-security.kubernetes.io/enforce: restricted pod-security.kubernetes.io/audit: restricted pod-security.kubernetes.io/warn: restrictedApply it.
kubectl apply \ -f manifests/namespace.yamlTask 06 — Build the Cluster Inventory Script
Section titled “Task 06 — Build the Cluster Inventory Script”Create scripts/collect-cluster-inventory.sh.
#!/usr/bin/env bash
set -euo pipefail
OUTPUT_DIR="${1:-reports}"
mkdir -p "$OUTPUT_DIR"
CLUSTER_CONTEXT="$(kubectl config current-context)"TIMESTAMP="$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
kubectl version -o json \ > "$OUTPUT_DIR/kubernetes-version.json"
kubectl get nodes -o json \ > "$OUTPUT_DIR/nodes.json"
kubectl get namespaces -o json \ > "$OUTPUT_DIR/namespaces.json"
kubectl get deployments -A -o json \ > "$OUTPUT_DIR/deployments.json"
kubectl get pods -A -o json \ > "$OUTPUT_DIR/pods.json"
kubectl get networkpolicies -A -o json \ > "$OUTPUT_DIR/networkpolicies.json"
kubectl get clusterroles -o json \ > "$OUTPUT_DIR/clusterroles.json"
kubectl get clusterrolebindings -o json \ > "$OUTPUT_DIR/clusterrolebindings.json"
cat > "$OUTPUT_DIR/cluster-inventory.json" <<EOF{ "clusterContext": "$CLUSTER_CONTEXT", "assessmentTime": "$TIMESTAMP", "nodeCount": $(kubectl get nodes --no-headers | wc -l), "namespaceCount": $(kubectl get namespaces --no-headers | wc -l), "deploymentCount": $(kubectl get deployments -A --no-headers | wc -l), "podCount": $(kubectl get pods -A --no-headers | wc -l)}EOF
echo "Cluster inventory completed."Make it executable.
chmod +x scripts/collect-cluster-inventory.shRun it.
./scripts/collect-cluster-inventory.shTask 07 — Validate the Cluster Inventory
Section titled “Task 07 — Validate the Cluster Inventory”Review:
jq '.' reports/cluster-inventory.jsonConfirm that the inventory includes:
- Cluster context
- Assessment timestamp
- Kubernetes version
- Node count
- Namespace count
- Deployment count
- Pod count
- RBAC inventory
- NetworkPolicy inventory
Task 08 — Create the PowerShell Inventory Script
Section titled “Task 08 — Create the PowerShell Inventory Script”Create powershell/Collect-ClusterInventory.ps1.
param( [string]$OutputDirectory = "reports")
$ErrorActionPreference = "Stop"
New-Item -ItemType Directory -Force ` -Path $OutputDirectory | Out-Null
$Context = kubectl config current-context$Timestamp = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")
kubectl version -o json | Out-File "$OutputDirectory\kubernetes-version.json"
kubectl get nodes -o json | Out-File "$OutputDirectory\nodes.json"
kubectl get namespaces -o json | Out-File "$OutputDirectory\namespaces.json"
kubectl get deployments -A -o json | Out-File "$OutputDirectory\deployments.json"
kubectl get pods -A -o json | Out-File "$OutputDirectory\pods.json"
$Inventory = @{ clusterContext = $Context assessmentTime = $Timestamp nodeCount = (kubectl get nodes -o json | ConvertFrom-Json).items.Count namespaceCount = (kubectl get namespaces -o json | ConvertFrom-Json).items.Count deploymentCount = (kubectl get deployments -A -o json | ConvertFrom-Json).items.Count podCount = (kubectl get pods -A -o json | ConvertFrom-Json).items.Count}
$Inventory | ConvertTo-Json | Out-File "$OutputDirectory\cluster-inventory.json"
Write-Host "Cluster inventory completed."Task 09 — Automate the CIS Benchmark Assessment
Section titled “Task 09 — Automate the CIS Benchmark Assessment”Create scripts/run-kube-bench.sh.
#!/usr/bin/env bash
set -euo pipefail
OUTPUT_DIR="${1:-reports}"
mkdir -p "$OUTPUT_DIR"
kube-bench \ --json \ > "$OUTPUT_DIR/kube-bench.json"
kube-bench \ > "$OUTPUT_DIR/kube-bench.txt"
echo "kube-bench assessment completed."Make it executable.
chmod +x scripts/run-kube-bench.shRun it.
./scripts/run-kube-bench.shIf kube-bench must run on cluster nodes, use the approved platform-specific execution method.
Task 10 — Review kube-bench Automation Output
Section titled “Task 10 — Review kube-bench Automation Output”Review the JSON file.
jq '.' reports/kube-bench.jsonCount failed tests where supported by the output structure.
jq '[.. | objects | select(.status? == "FAIL")] | length' \ reports/kube-bench.jsonCount warnings.
jq '[.. | objects | select(.status? == "WARN")] | length' \ reports/kube-bench.jsonRecord:
PASS:
FAIL:
WARN:
INFO:
Benchmark Version:
Assessment Time:Task 11 — Automate Kubernetes Configuration Scanning
Section titled “Task 11 — Automate Kubernetes Configuration Scanning”Create scripts/scan-manifests.sh.
#!/usr/bin/env bash
set -euo pipefail
TARGET="${1:-manifests}"OUTPUT="${2:-reports/manifest-scan.json}"
trivy config \ --format json \ --output "$OUTPUT" \ "$TARGET"
echo "Manifest configuration scan completed."Make it executable.
chmod +x scripts/scan-manifests.shRun it.
./scripts/scan-manifests.sh manifestsTask 12 — Review Configuration Findings
Section titled “Task 12 — Review Configuration Findings”Review:
jq '.' reports/manifest-scan.jsonIdentify:
- Privileged containers
- Root execution
- Missing resource limits
- Missing seccomp profiles
- HostPath usage
- Excessive capabilities
- Missing read-only filesystems
- Mutable image tags
- Insecure Service Account token usage
Task 13 — Create a Non-Compliant Test Deployment
Section titled “Task 13 — Create a Non-Compliant Test Deployment”Create manifests/non-compliant-deployment.yaml.
apiVersion: apps/v1kind: Deploymentmetadata: name: non-compliant-application namespace: compliance-automationspec: replicas: 1 selector: matchLabels: app: non-compliant-application template: metadata: labels: app: non-compliant-application spec: containers: - name: application image: nginx:latest securityContext: privileged: trueDo not deploy this workload when admission policies would reject it.
Scan it locally.
trivy config \ manifests/non-compliant-deployment.yamlTask 14 — Create a Compliant Test Deployment
Section titled “Task 14 — Create a Compliant Test Deployment”Create manifests/compliant-deployment.yaml.
apiVersion: apps/v1kind: Deploymentmetadata: name: compliant-application namespace: compliance-automation labels: app: compliant-application owner: cloud-security environment: trainingspec: replicas: 2 selector: matchLabels: app: compliant-application template: metadata: labels: app: compliant-application owner: cloud-security environment: training spec: automountServiceAccountToken: false securityContext: runAsNonRoot: true runAsUser: 101 runAsGroup: 101 seccompProfile: type: RuntimeDefault containers: - name: application image: nginx:1.27-alpine ports: - name: http containerPort: 8080 securityContext: privileged: false allowPrivilegeEscalation: false readOnlyRootFilesystem: true capabilities: drop: - ALL resources: requests: cpu: 50m memory: 64Mi limits: cpu: 200m memory: 128Mi volumeMounts: - name: temporary-files mountPath: /tmp - name: cache mountPath: /var/cache/nginx - name: runtime mountPath: /var/run volumes: - name: temporary-files emptyDir: {} - name: cache emptyDir: {} - name: runtime emptyDir: {}Scan it.
trivy config \ manifests/compliant-deployment.yamlCompare the results.
Task 15 — Discover Running Container Images
Section titled “Task 15 — Discover Running Container Images”Create scripts/scan-images.sh.
#!/usr/bin/env bash
set -euo pipefail
OUTPUT_DIR="${1:-reports/images}"
mkdir -p "$OUTPUT_DIR"
kubectl get pods -A \ -o jsonpath='{range .items[*]}{range .spec.containers[*]}{.image}{"\n"}{end}{end}' \ | sort -u \ > "$OUTPUT_DIR/image-list.txt"
while IFS= read -r IMAGE; do SAFE_NAME="$(echo "$IMAGE" | tr '/:@' '____')"
trivy image \ --format json \ --output "$OUTPUT_DIR/${SAFE_NAME}.json" \ "$IMAGE" || truedone < "$OUTPUT_DIR/image-list.txt"
echo "Container-image scanning completed."Make it executable.
chmod +x scripts/scan-images.shRun it only against authorised images.
./scripts/scan-images.shTask 16 — Define Image-Scan Failure Thresholds
Section titled “Task 16 — Define Image-Scan Failure Thresholds”Create policies/compliance-thresholds.json.
{ "kubeBench": { "maximumFail": 0, "maximumWarn": 10 }, "manifestScan": { "maximumCritical": 0, "maximumHigh": 0, "maximumMedium": 10 }, "imageScan": { "maximumCritical": 0, "maximumHigh": 5 }, "kyverno": { "maximumCriticalFailures": 0, "maximumHighFailures": 0 }, "gatekeeper": { "maximumViolations": 0 }}Thresholds must be approved by:
- Cloud Security
- Application Security
- Platform Engineering
- Compliance
- Application Owner where applicable
Task 17 — Export Kyverno Policy Reports
Section titled “Task 17 — Export Kyverno Policy Reports”Create scripts/export-kyverno-reports.sh.
#!/usr/bin/env bash
set -euo pipefail
OUTPUT_DIR="${1:-reports}"
mkdir -p "$OUTPUT_DIR"
kubectl get policyreports -A -o yaml \ > "$OUTPUT_DIR/kyverno-policyreports.yaml"
kubectl get clusterpolicyreports -o yaml \ > "$OUTPUT_DIR/kyverno-clusterpolicyreports.yaml"
kubectl get clusterpolicies -o yaml \ > "$OUTPUT_DIR/kyverno-clusterpolicies.yaml"
echo "Kyverno reports exported."Make it executable.
chmod +x scripts/export-kyverno-reports.shRun it.
./scripts/export-kyverno-reports.shTask 18 — Summarise Kyverno Results
Section titled “Task 18 — Summarise Kyverno Results”Review:
kubectl get policyreports -ACreate a JSON summary where policy reports are available.
kubectl get policyreports -A -o json \ | jq '{ totalReports: (.items | length), pass: ([.items[].summary.pass // 0] | add), fail: ([.items[].summary.fail // 0] | add), warn: ([.items[].summary.warn // 0] | add), error: ([.items[].summary.error // 0] | add), skip: ([.items[].summary.skip // 0] | add) }' \ > reports/kyverno-summary.jsonTask 19 — Export Gatekeeper Violations
Section titled “Task 19 — Export Gatekeeper Violations”Create scripts/export-gatekeeper-violations.sh.
#!/usr/bin/env bash
set -euo pipefail
OUTPUT_DIR="${1:-reports}"
mkdir -p "$OUTPUT_DIR"
kubectl get constraints \ -o yaml \ > "$OUTPUT_DIR/gatekeeper-constraints.yaml"
kubectl get constraints \ -o json \ | jq '{ constraintCount: (.items | length), constraints: [ .items[] | { name: .metadata.name, kind: .kind, enforcementAction: .spec.enforcementAction, totalViolations: (.status.totalViolations // 0), violations: (.status.violations // []) } ] }' \ > "$OUTPUT_DIR/gatekeeper-violations.json"
echo "Gatekeeper violations exported."Make it executable.
chmod +x scripts/export-gatekeeper-violations.shRun it where Gatekeeper remains installed.
./scripts/export-gatekeeper-violations.shTask 20 — Review Gatekeeper Findings
Section titled “Task 20 — Review Gatekeeper Findings”Review:
jq '.' reports/gatekeeper-violations.jsonIdentify:
- Constraint
- Enforcement action
- Resource
- Namespace
- Violation message
- Total violation count
Task 21 — Create the Compliance Evaluation Script
Section titled “Task 21 — Create the Compliance Evaluation Script”Create scripts/evaluate-compliance.sh.
#!/usr/bin/env bash
set -euo pipefail
REPORT_DIR="${1:-reports}"THRESHOLD_FILE="${2:-policies/compliance-thresholds.json}"
EXIT_CODE=0
MAX_KUBEBENCH_FAIL="$(jq -r '.kubeBench.maximumFail' "$THRESHOLD_FILE")"MAX_MANIFEST_CRITICAL="$(jq -r '.manifestScan.maximumCritical' "$THRESHOLD_FILE")"MAX_MANIFEST_HIGH="$(jq -r '.manifestScan.maximumHigh' "$THRESHOLD_FILE")"
KUBEBENCH_FAIL="$( jq '[.. | objects | select(.status? == "FAIL")] | length' \ "$REPORT_DIR/kube-bench.json")"
MANIFEST_CRITICAL="$( jq '[.. | objects | select(.Severity? == "CRITICAL")] | length' \ "$REPORT_DIR/manifest-scan.json")"
MANIFEST_HIGH="$( jq '[.. | objects | select(.Severity? == "HIGH")] | length' \ "$REPORT_DIR/manifest-scan.json")"
echo "kube-bench failures: $KUBEBENCH_FAIL"echo "Manifest critical findings: $MANIFEST_CRITICAL"echo "Manifest high findings: $MANIFEST_HIGH"
if (( KUBEBENCH_FAIL > MAX_KUBEBENCH_FAIL )); then echo "FAIL: kube-bench threshold exceeded." EXIT_CODE=1fi
if (( MANIFEST_CRITICAL > MAX_MANIFEST_CRITICAL )); then echo "FAIL: Critical manifest threshold exceeded." EXIT_CODE=1fi
if (( MANIFEST_HIGH > MAX_MANIFEST_HIGH )); then echo "FAIL: High manifest threshold exceeded." EXIT_CODE=1fi
if (( EXIT_CODE == 0 )); then echo "Compliance evaluation passed."else echo "Compliance evaluation failed."fi
exit "$EXIT_CODE"Make it executable.
chmod +x scripts/evaluate-compliance.shTask 22 — Test the Compliance Evaluation
Section titled “Task 22 — Test the Compliance Evaluation”Run:
./scripts/evaluate-compliance.shCheck the exit code.
echo $?Expected:
0when thresholds are satisfied.
Expected:
1when thresholds are exceeded.
Task 23 — Test a Compliance Failure
Section titled “Task 23 — Test a Compliance Failure”Temporarily scan the non-compliant manifest.
trivy config \ --format json \ --output reports/manifest-scan.json \ manifests/non-compliant-deployment.yamlRun the evaluation.
./scripts/evaluate-compliance.shExpected:
Compliance evaluation failedRestore the full manifest scan afterward.
Task 24 — Generate a Consolidated Summary
Section titled “Task 24 — Generate a Consolidated Summary”Create scripts/generate-summary.sh.
#!/usr/bin/env bash
set -euo pipefail
REPORT_DIR="${1:-reports}"OUTPUT="$REPORT_DIR/compliance-summary.json"
TIMESTAMP="$(date -u +"%Y-%m-%dT%H:%M:%SZ")"CLUSTER="$(kubectl config current-context)"
KUBEBENCH_FAIL="$( jq '[.. | objects | select(.status? == "FAIL")] | length' \ "$REPORT_DIR/kube-bench.json")"
KUBEBENCH_WARN="$( jq '[.. | objects | select(.status? == "WARN")] | length' \ "$REPORT_DIR/kube-bench.json")"
MANIFEST_CRITICAL="$( jq '[.. | objects | select(.Severity? == "CRITICAL")] | length' \ "$REPORT_DIR/manifest-scan.json")"
MANIFEST_HIGH="$( jq '[.. | objects | select(.Severity? == "HIGH")] | length' \ "$REPORT_DIR/manifest-scan.json")"
cat > "$OUTPUT" <<EOF{ "assessmentTime": "$TIMESTAMP", "cluster": "$CLUSTER", "kubeBench": { "fail": $KUBEBENCH_FAIL, "warn": $KUBEBENCH_WARN }, "manifestScan": { "critical": $MANIFEST_CRITICAL, "high": $MANIFEST_HIGH }, "overallStatus": "$( if (( KUBEBENCH_FAIL == 0 && MANIFEST_CRITICAL == 0 && MANIFEST_HIGH == 0 )); then echo "PASS" else echo "FAIL" fi )"}EOF
echo "Compliance summary generated."Make it executable.
chmod +x scripts/generate-summary.shRun it.
./scripts/generate-summary.shReview:
jq '.' reports/compliance-summary.jsonTask 25 — Calculate a Compliance Score
Section titled “Task 25 — Calculate a Compliance Score”Use a simple weighted model for the lab.
Starting Score: 100
Each Critical Finding: -20
Each High Finding: -10
Each Medium Finding: -5
Each Low Finding: -1Example:
Critical Findings: 1
High Findings: 2
Medium Findings: 3
Low Findings: 4
Score:
100 - 20 - 20 - 15 - 4 = 41Suggested rating:
| Score | Rating |
|---|---|
| 90–100 | Effective |
| 75–89 | Mostly Effective |
| 60–74 | Partially Effective |
| 40–59 | Weak |
| Below 40 | Critical |
This score is a management summary and must not replace technical risk analysis.
Task 26 — Create the Compliance Service Account
Section titled “Task 26 — Create the Compliance Service Account”Create manifests/service-account.yaml.
apiVersion: v1kind: ServiceAccountmetadata: name: compliance-assessor namespace: compliance-automation labels: app: compliance-automation owner: cloud-securityApply it.
kubectl apply \ -f manifests/service-account.yamlTask 27 — Create the Read-Only Assessment Role
Section titled “Task 27 — Create the Read-Only Assessment Role”Create manifests/role.yaml.
apiVersion: rbac.authorization.k8s.io/v1kind: ClusterRolemetadata: name: compliance-assessorrules: - apiGroups: - "" resources: - pods - namespaces - nodes - serviceaccounts - configmaps - events verbs: - get - list - watch - apiGroups: - apps resources: - deployments - daemonsets - statefulsets - replicasets verbs: - get - list - watch - apiGroups: - networking.k8s.io resources: - networkpolicies - ingresses verbs: - get - list - watch - apiGroups: - kyverno.io resources: - clusterpolicies - policies - policyexceptions verbs: - get - list - watch - apiGroups: - wgpolicyk8s.io resources: - policyreports - clusterpolicyreports verbs: - get - list - watchTask 28 — Bind the Assessment Role
Section titled “Task 28 — Bind the Assessment Role”Create manifests/rolebinding.yaml.
apiVersion: rbac.authorization.k8s.io/v1kind: ClusterRoleBindingmetadata: name: compliance-assessorsubjects: - kind: ServiceAccount name: compliance-assessor namespace: compliance-automationroleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: compliance-assessorApply:
kubectl apply \ -f manifests/role.yamlkubectl apply \ -f manifests/rolebinding.yamlValidate:
kubectl auth can-i list pods \ --as=system:serviceaccount:compliance-automation:compliance-assessor \ --all-namespacesTask 29 — Create the Automation ConfigMap
Section titled “Task 29 — Create the Automation ConfigMap”Create manifests/configmap.yaml.
apiVersion: v1kind: ConfigMapmetadata: name: compliance-automation-config namespace: compliance-automationdata: assessment.sh: | #!/usr/bin/env sh
set -eu
TIMESTAMP="$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
echo "Compliance assessment started at ${TIMESTAMP}"
kubectl get nodes -o wide kubectl get namespaces kubectl get pods -A kubectl get deployments -A kubectl get policyreports -A || true kubectl get clusterpolicyreports || true
echo "Compliance assessment completed."Apply:
kubectl apply \ -f manifests/configmap.yamlTask 30 — Create the Scheduled Compliance CronJob
Section titled “Task 30 — Create the Scheduled Compliance CronJob”Create manifests/compliance-cronjob.yaml.
apiVersion: batch/v1kind: CronJobmetadata: name: kubernetes-compliance-assessment namespace: compliance-automation labels: app: compliance-automation owner: cloud-security environment: trainingspec: schedule: "0 2 * * *" concurrencyPolicy: Forbid successfulJobsHistoryLimit: 3 failedJobsHistoryLimit: 5 jobTemplate: spec: backoffLimit: 1 template: metadata: labels: app: compliance-automation spec: restartPolicy: Never serviceAccountName: compliance-assessor automountServiceAccountToken: true securityContext: runAsNonRoot: true runAsUser: 10001 runAsGroup: 10001 seccompProfile: type: RuntimeDefault containers: - name: compliance-assessor image: bitnami/kubectl:latest imagePullPolicy: IfNotPresent command: - /bin/sh - /scripts/assessment.sh securityContext: privileged: false allowPrivilegeEscalation: false readOnlyRootFilesystem: true capabilities: drop: - ALL resources: requests: cpu: 50m memory: 64Mi limits: cpu: 200m memory: 256Mi volumeMounts: - name: scripts mountPath: /scripts readOnly: true - name: temporary-files mountPath: /tmp volumes: - name: scripts configMap: name: compliance-automation-config defaultMode: 0555 - name: temporary-files emptyDir: {}For production:
- Replace mutable tags with approved digests.
- Use an internally approved image.
- Add secure evidence storage.
- Define retention and encryption.
- Add monitoring and alerts.
Task 31 — Apply and Validate the CronJob
Section titled “Task 31 — Apply and Validate the CronJob”Apply:
kubectl apply \ -f manifests/compliance-cronjob.yamlVerify:
kubectl get cronjob \ -n compliance-automationReview:
kubectl describe cronjob kubernetes-compliance-assessment \ -n compliance-automationTask 32 — Trigger a Manual Compliance Job
Section titled “Task 32 — Trigger a Manual Compliance Job”Create a Job from the CronJob.
kubectl create job \ --from=cronjob/kubernetes-compliance-assessment \ compliance-manual-test \ -n compliance-automationMonitor:
kubectl get jobs \ -n compliance-automationReview the Pod.
kubectl get pods \ -n compliance-automationTask 33 — Review Scheduled Assessment Logs
Section titled “Task 33 — Review Scheduled Assessment Logs”kubectl logs \ job/compliance-manual-test \ -n compliance-automationSave evidence.
kubectl logs \ job/compliance-manual-test \ -n compliance-automation \ > evidence/cronjob-result.txtTask 34 — Validate CronJob Security
Section titled “Task 34 — Validate CronJob Security”Review:
kubectl get cronjob kubernetes-compliance-assessment \ -n compliance-automation \ -o yamlValidate:
- Dedicated Service Account
- Read-only RBAC
- Non-root execution
- Seccomp enabled
- No privilege escalation
- Read-only root filesystem
- Capabilities dropped
- Resource limits configured
- Concurrency controlled
- Job history limited
Task 35 — Design the CI/CD Compliance Pipeline
Section titled “Task 35 — Design the CI/CD Compliance Pipeline”The pipeline should perform:
Checkout Source
│
▼
Validate YAML
│
▼
Scan Kubernetes Manifests
│
▼
Scan Container Image
│
▼
Evaluate Policies
│
▼
Generate Evidence
│
▼
Apply Compliance Threshold
│
┌───┴───┐
▼ ▼
Pass Fail
│ │
Deploy BlockTask 36 — Create a GitHub Actions Compliance Workflow
Section titled “Task 36 — Create a GitHub Actions Compliance Workflow”Create pipeline/github-actions-compliance.yaml.
name: Kubernetes Compliance Gate
on: pull_request: paths: - "manifests/**" - "policies/**" - "scripts/**" workflow_dispatch:
permissions: contents: read security-events: write
jobs: compliance: name: Kubernetes Compliance Assessment runs-on: ubuntu-latest
steps: - name: Checkout repository uses: actions/checkout@v4
- name: Install jq run: sudo apt-get update && sudo apt-get install -y jq
- name: Install Trivy run: | sudo apt-get update sudo apt-get install -y wget apt-transport-https gnupg lsb-release wget -qO - https://aquasecurity.github.io/trivy-repo/deb/public.key \ | gpg --dearmor \ | sudo tee /usr/share/keyrings/trivy.gpg > /dev/null
echo "deb [signed-by=/usr/share/keyrings/trivy.gpg] https://aquasecurity.github.io/trivy-repo/deb generic main" \ | sudo tee /etc/apt/sources.list.d/trivy.list
sudo apt-get update sudo apt-get install -y trivy
- name: Scan Kubernetes manifests run: | mkdir -p reports trivy config \ --format json \ --output reports/manifest-scan.json \ manifests
- name: Evaluate compliance thresholds run: | chmod +x scripts/evaluate-compliance.sh ./scripts/evaluate-compliance.sh reports policies/compliance-thresholds.json
- name: Upload compliance evidence if: always() uses: actions/upload-artifact@v4 with: name: kubernetes-compliance-evidence path: reports/ retention-days: 30Place the workflow in:
.github/workflows/kubernetes-compliance.yamlafter testing.
Task 37 — Create a GitLab CI Compliance Pipeline
Section titled “Task 37 — Create a GitLab CI Compliance Pipeline”Create pipeline/gitlab-compliance.yml.
stages: - validate - compliance - evidence
variables: REPORT_DIR: "reports"
validate-yaml: stage: validate image: alpine:3.20 script: - echo "Validate Kubernetes YAML files" rules: - changes: - manifests/**/* - policies/**/*
manifest-compliance: stage: compliance image: name: aquasec/trivy:latest entrypoint: [""] script: - mkdir -p "$REPORT_DIR" - trivy config --format json --output "$REPORT_DIR/manifest-scan.json" manifests artifacts: when: always paths: - reports/ expire_in: 30 days
compliance-gate: stage: compliance image: alpine:3.20 before_script: - apk add --no-cache bash jq script: - chmod +x scripts/evaluate-compliance.sh - ./scripts/evaluate-compliance.sh needs: - manifest-compliance
archive-evidence: stage: evidence image: alpine:3.20 script: - echo "Compliance evidence archived." artifacts: when: always paths: - reports/ expire_in: 90 daysReplace mutable CI images with approved digests in production.
Task 38 — Test the Pipeline with a Compliant Manifest
Section titled “Task 38 — Test the Pipeline with a Compliant Manifest”Commit only the compliant manifest and pipeline configuration.
Expected:
- Manifest scan completes.
- Threshold evaluation passes.
- Evidence artifact is created.
- Pipeline returns success.
- Deployment may continue.
Record:
Pipeline ID:
Commit:
Manifest:
Critical Findings:
High Findings:
Result:
Evidence Artifact:Task 39 — Test the Pipeline with a Non-Compliant Manifest
Section titled “Task 39 — Test the Pipeline with a Non-Compliant Manifest”Add:
manifests/non-compliant-deployment.yamlExpected:
- Critical or high findings are detected.
- Compliance gate returns non-zero.
- Pipeline fails.
- Deployment is blocked.
- Evidence remains available.
Record the result in:
evidence/pipeline-result.txtTask 40 — Add Policy Validation to CI/CD
Section titled “Task 40 — Add Policy Validation to CI/CD”Recommended pipeline policy checks include:
- Kyverno CLI validation
- Conftest or OPA checks
- Gatekeeper policy tests
- Kubernetes schema validation
- Helm template validation
- Image signature verification
- SBOM presence
- Vulnerability thresholds
Example conceptual command:
kyverno apply policies/ \ --resource manifests/ \ --policy-reportValidate command syntax against the installed Kyverno CLI version.
Task 41 — Add Signed-Image Verification
Section titled “Task 41 — Add Signed-Image Verification”Before deployment, verify the approved image.
cosign verify \ --key keys/cosign.pub \ "<registry>/<repository>@sha256:<digest>"Required pipeline decision:
Valid trusted signature: Continue
Missing signature: Fail
Unapproved identity: Fail
Incorrect digest: FailTask 42 — Add SBOM Verification
Section titled “Task 42 — Add SBOM Verification”Validate that:
- An SBOM exists.
- It matches the image digest.
- It uses an approved format.
- It is signed or attested.
- It contains required component metadata.
Example:
cosign verify-attestation \ --key keys/cosign.pub \ --type cyclonedx \ "<image-by-digest>"Task 43 — Design Compliance Evidence Storage
Section titled “Task 43 — Design Compliance Evidence Storage”Evidence must include:
- Assessment timestamp
- Cluster identity
- Tool version
- Input manifests
- Policy version
- Scan results
- Pipeline logs
- Approval decision
- Exception references
- Remediation status
Approved storage options may include:
- Encrypted object storage
- Compliance evidence repository
- SIEM
- Governance, risk and compliance platform
- Secured Git repository
- Artifact repository
Evidence must be:
- Access controlled
- Encrypted
- Time stamped
- Tamper evident
- Retained
- Searchable
- Associated with an owner
Task 44 — Create the Evidence Retention Policy
Section titled “Task 44 — Create the Evidence Retention Policy”Create policies/evidence-retention-policy.md.
Policy Name:Kubernetes Compliance Evidence Retention Policy
Scope:
Evidence Types:
Assessment Reports:
Pipeline Reports:
Policy Reports:
Benchmark Reports:
Image Scan Reports:
Admission Events:
Exceptions:
Approvals:
Default Retention Period:
Production Retention Period:
Regulated Workload Retention:
Legal Hold Procedure:
Encryption Requirements:
Access Control:
Deletion Approval:
Backup Requirements:
Audit Requirements:
Evidence Owner:Task 45 — Define Automated Compliance Notifications
Section titled “Task 45 — Define Automated Compliance Notifications”Create notification rules.
| Condition | Notification |
|---|---|
| Critical finding | SOC, Cloud Security and Platform Owner |
| High finding | Security and Application Owner |
| Compliance score below 60 | CISO or Risk Owner |
| Kyverno controller unavailable | Platform Engineering |
| Gatekeeper webhook failure | Kubernetes Security |
| Benchmark execution failure | Compliance Operations |
| Expired exception | Security Governance |
| Pipeline policy bypass attempt | SOC and DevSecOps |
| Evidence upload failure | Compliance Operations |
Notifications should include:
- Finding
- Severity
- Resource
- Cluster
- Owner
- Detection time
- Remediation deadline
- Evidence link
Task 46 — Create a Remediation Tracker
Section titled “Task 46 — Create a Remediation Tracker”Create reports/remediation-tracker.md.
| Finding ID | Control | Resource | Severity | Owner | Due Date | Status |
|---|---|---|---|---|---|---|
| K8S-COMP-001 | CIS 1.2.1 | API Server | Critical | Platform | Open | |
| K8S-COMP-002 | Require non-root | payment-api | High | App Team | Open | |
| K8S-COMP-003 | Image vulnerability | worker-image | High | DevSecOps | Open | |
| K8S-COMP-004 | Missing owner label | reporting-api | Medium | App Team | Open |
Supported statuses:
- Open
- Assigned
- In Progress
- Risk Accepted
- Remediated
- Verified
- Closed
Task 47 — Define Automated Remediation Boundaries
Section titled “Task 47 — Define Automated Remediation Boundaries”Safe automation examples:
- Add missing informational labels
- Generate PolicyReports
- Create remediation tickets
- Notify owners
- Quarantine non-production workloads
- Block non-compliant pull requests
- Re-run scans
- Expire temporary exceptions
High-risk automated actions requiring approval:
- Delete production workloads
- Restart production clusters
- Change control-plane configuration
- Rotate production credentials
- Remove registry images
- Modify admission webhooks
- Apply cluster-wide policies
- Change network controls
- Revoke signing identities
Task 48 — Create an Exception Register
Section titled “Task 48 — Create an Exception Register”Create policies/exception-register.yaml.
exceptions: - id: EXC-K8S-001 control: require-image-digests resource: approved-legacy-application namespace: legacy-apps justification: Temporary migration dependency requestedBy: application-owner approvedBy: cloud-security risk: High compensatingControls: - Registry tag immutability - Restricted deployment access - Continuous vulnerability scanning startDate: "2026-07-30" expirationDate: "2026-08-30" status: ActiveEvery exception must be:
- Specific
- Approved
- Time limited
- Risk assessed
- Monitored
- Reviewed before expiry
Task 49 — Review Compliance Drift
Section titled “Task 49 — Review Compliance Drift”Compare current findings with a previous assessment.
Track:
| Control | Previous | Current | Trend |
|---|---|---|---|
| CIS failures | 8 | 4 | Improving |
| Critical manifest findings | 3 | 0 | Improving |
| High image findings | 12 | 7 | Improving |
| Kyverno violations | 22 | 15 | Improving |
| Expired exceptions | 0 | 2 | Worsening |
Trend values:
- Improving
- Stable
- Worsening
- New
- Resolved
Task 50 — Design the Compliance Dashboard
Section titled “Task 50 — Design the Compliance Dashboard”Recommended dashboard indicators:
Overall Compliance Score
CIS Benchmark Pass Rate
Critical Findings
High Findings
Kyverno Violations
Gatekeeper Violations
Unsigned Images
Public Registry Images
Mutable Image Tags
Missing SBOMs
Expired Exceptions
Remediation Age
Assessment Coverage
Last Successful AssessmentDashboard filters:
- Cluster
- Environment
- Namespace
- Application
- Owner
- Severity
- Control framework
- Status
Task 51 — Define Compliance Metrics
Section titled “Task 51 — Define Compliance Metrics”Track:
| Metric | Description |
|---|---|
| Assessment coverage | Percentage of clusters assessed |
| Control pass rate | Percentage of controls passing |
| Mean time to remediate | Average time to close findings |
| Critical finding age | Age of unresolved critical risks |
| Policy enforcement rate | Percentage of critical policies enforced |
| Exception count | Active security exceptions |
| Expired exception count | Exceptions beyond expiry |
| Evidence completeness | Assessments with complete evidence |
| Automation success rate | Successful scheduled assessment percentage |
| Pipeline failure rate | Changes blocked by compliance controls |
Task 52 — Integrate with SIEM and SOC Operations
Section titled “Task 52 — Integrate with SIEM and SOC Operations”Send relevant events to the SIEM:
- Critical compliance findings
- Admission denials
- Policy-engine failures
- Unauthorised exception changes
- Registry-policy changes
- Benchmark failures
- Signed-image verification failures
- Evidence-storage failures
- Pipeline bypass attempts
SOC correlation examples:
High-risk Kubernetes configuration
+
Unexpected deployment identity
+
Image from unapproved registry
=
Potential supply chain incidentTask 53 — Create the Compliance Run Schedule
Section titled “Task 53 — Create the Compliance Run Schedule”Recommended schedule:
| Activity | Frequency |
|---|---|
| Manifest scan | Every commit |
| Image scan | Every build |
| Signature verification | Before deployment |
| Kyverno validation | Every admission request |
| Gatekeeper validation | Every admission request |
| Policy-report export | Daily |
| CIS Benchmark assessment | Weekly or monthly |
| Full compliance report | Monthly |
| Exception review | Weekly |
| Executive reporting | Monthly or quarterly |
| Compliance framework review | Quarterly |
Task 54 — Perform the Enterprise Automation Assessment
Section titled “Task 54 — Perform the Enterprise Automation Assessment”Complete the assessment.
| Security Domain | Expected Control | Status |
|---|---|---|
| Cluster inventory | Automated | |
| CIS Benchmark | Automated | |
| Manifest scanning | Automated | |
| Image scanning | Automated | |
| Policy validation | Automated | |
| Kyverno reporting | Exported automatically | |
| Gatekeeper reporting | Exported automatically | |
| Compliance thresholds | Approved | |
| CI/CD gate | Enforced | |
| Scheduled assessment | Configured | |
| Evidence storage | Protected | |
| Notifications | Configured | |
| Remediation ownership | Assigned | |
| Exceptions | Time limited | |
| Drift analysis | Implemented | |
| Dashboard | Designed or active | |
| SIEM integration | Configured | |
| Automation logs | Retained | |
| Failure handling | Documented | |
| Change control | Enforced |
Rate each area as:
- Effective
- Partially Effective
- Ineffective
- Not Applicable
Task 55 — Assign the Compliance Automation Risk Rating
Section titled “Task 55 — Assign the Compliance Automation Risk Rating”Critical Risk
Section titled “Critical Risk”Examples:
- Compliance pipeline can be bypassed without approval
- Critical findings do not block production deployments
- Assessment credentials are exposed
- Compliance evidence can be altered without detection
- Automation uses unrestricted cluster administrator access
- Policy engines are unavailable without alerting
- Audit evidence is deleted or falsified
High Risk
Section titled “High Risk”Examples:
- CIS assessments are not automated
- Image scans are not part of CI/CD
- Critical Kyverno policies remain in Audit mode
- Exceptions have no expiry
- Compliance results are not retained
- Scheduled assessments repeatedly fail
- No remediation ownership exists
- Public images are not detected
Medium Risk
Section titled “Medium Risk”Examples:
- Dashboard is incomplete
- Some reports require manual consolidation
- Notification routing is inconsistent
- Tool versions are not recorded
- Drift reporting is absent
- Evidence-retention rules are unclear
Low Risk
Section titled “Low Risk”Examples:
- Report naming inconsistency
- Missing informational metadata
- Minor dashboard formatting issue
- Documentation improvement
Task 56 — Create the Enterprise Compliance Automation Report
Section titled “Task 56 — Create the Enterprise Compliance Automation Report”Create reports/enterprise-compliance-report.md.
Assessment Title:Enterprise Kubernetes Compliance Automation Assessment
Assessment Date:
Assessor:
Cluster:
Environment:
Kubernetes Version:
Automation Version:
Assessment Scope:
Tools Used:
Cluster Inventory:
CIS Benchmark Result:
CIS Pass Count:
CIS Fail Count:
CIS Warning Count:
Manifest Critical Findings:
Manifest High Findings:
Image Critical Findings:
Image High Findings:
Kyverno Pass Count:
Kyverno Fail Count:
Gatekeeper Violations:
Signed Image Verification:
SBOM Verification:
CI/CD Gate Status:
Scheduled Assessment Status:
Last Successful Assessment:
Evidence Storage:
Evidence Retention:
Notification Integration:
SIEM Integration:
Active Exceptions:
Expired Exceptions:
Compliance Score:
Compliance Rating:
Critical Risks:
High Risks:
Medium Risks:
Low Risks:
Required Remediation:
Residual Risk:
Overall Assessment:
Production Decision:
Approved
Conditionally Approved
Rejected
Approvals:
Kubernetes Security:
Cloud Security:
DevSecOps:
Platform Engineering:
Compliance:
Risk Owner:Task 57 — Collect Evidence
Section titled “Task 57 — Collect Evidence”Collect:
- Tool versions
- Cluster context
- Assessment timestamp
- Cluster inventory
- Kubernetes version
- Node inventory
- kube-bench JSON
- kube-bench text output
- Manifest scan
- Image scan
- Kyverno PolicyReports
- Gatekeeper violations
- Compliance thresholds
- Compliance summary
- CronJob configuration
- Manual Job result
- CI/CD pipeline configuration
- Pipeline pass result
- Pipeline failure result
- Exception register
- Remediation tracker
- Evidence-retention policy
- Automation assessment
- Enterprise report
Suggested filenames:
01-tool-versions.txt02-cluster-context.txt03-assessment-timestamp.txt04-cluster-inventory.json05-kubernetes-version.json06-node-inventory.json07-kube-bench.json08-kube-bench.txt09-manifest-scan.json10-image-scan.json11-kyverno-policyreports.yaml12-gatekeeper-violations.json13-compliance-thresholds.json14-compliance-summary.json15-compliance-cronjob.yaml16-manual-job-result.txt17-cicd-pipeline.yaml18-pipeline-pass.txt19-pipeline-failure.txt20-exception-register.yaml21-remediation-tracker.md22-evidence-retention-policy.md23-automation-assessment.md24-enterprise-compliance-report.mdTask 58 — Clean Up the Manual Test Job
Section titled “Task 58 — Clean Up the Manual Test Job”kubectl delete job compliance-manual-test \ -n compliance-automation \ --ignore-not-foundTask 59 — Decide Whether to Retain the CronJob
Section titled “Task 59 — Decide Whether to Retain the CronJob”Retain the CronJob when:
- Later labs depend on compliance evidence.
- The cluster is used for ongoing training.
- Scheduled assessments are being evaluated.
- Reports are integrated with a dashboard or SIEM.
Delete it only when the training environment is temporary.
kubectl delete cronjob kubernetes-compliance-assessment \ -n compliance-automationTask 60 — Clean Up Lab Resources
Section titled “Task 60 — Clean Up Lab Resources”Delete the assessment RBAC only when no later lab requires it.
kubectl delete clusterrolebinding compliance-assessorkubectl delete clusterrole compliance-assessorDelete the namespace.
kubectl delete namespace compliance-automationDo not remove Kyverno or Gatekeeper when the next lab depends on them.
Enterprise Compliance Automation Checklist
Section titled “Enterprise Compliance Automation Checklist”| Control | Status |
|---|---|
| Compliance workspace created | ☐ |
| Tool versions recorded | ☐ |
| Assessment timestamp recorded | ☐ |
| Cluster inventory automated | ☐ |
| Kubernetes version collected | ☐ |
| Node inventory collected | ☐ |
| CIS Benchmark automated | ☐ |
| Benchmark results exported as JSON | ☐ |
| Manifest scanning automated | ☐ |
| Image scanning automated | ☐ |
| Kyverno reports exported | ☐ |
| Gatekeeper violations exported | ☐ |
| Compliance thresholds approved | ☐ |
| Evaluation script tested | ☐ |
| Pass condition validated | ☐ |
| Failure condition validated | ☐ |
| Compliance summary generated | ☐ |
| Read-only Service Account created | ☐ |
| Least-privilege RBAC configured | ☐ |
| Compliance CronJob created | ☐ |
| Manual Job tested | ☐ |
| CronJob security validated | ☐ |
| CI/CD compliance gate created | ☐ |
| Compliant pipeline test passed | ☐ |
| Non-compliant pipeline test failed | ☐ |
| Signature verification included | ☐ |
| SBOM verification included | ☐ |
| Evidence storage defined | ☐ |
| Retention policy documented | ☐ |
| Notifications defined | ☐ |
| Remediation tracker created | ☐ |
| Exception register created | ☐ |
| Compliance drift reviewed | ☐ |
| Dashboard metrics defined | ☐ |
| SIEM integration designed | ☐ |
| Enterprise report completed | ☐ |
Remediation Priorities
Section titled “Remediation Priorities”Immediate
Section titled “Immediate”- Remove exposed automation credentials.
- Block pipeline bypass paths.
- Restore failed policy engines.
- Enforce critical compliance thresholds.
- Protect compliance evidence from alteration.
- Remove expired exceptions.
- Investigate failed scheduled assessments.
- Restrict assessment identities to least privilege.
Short-Term
Section titled “Short-Term”- Automate kube-bench execution.
- Add manifest and image scanning to CI/CD.
- Export Kyverno and Gatekeeper findings automatically.
- Implement central evidence storage.
- Configure compliance notifications.
- Assign remediation ownership.
- Build compliance drift reporting.
- Integrate critical events with the SIEM.
Long-Term
Section titled “Long-Term”- Implement multi-cluster compliance automation.
- Build executive compliance dashboards.
- Automate exception expiry.
- Integrate findings with ticketing systems.
- Add automatic control mapping.
- Implement policy-as-code testing.
- Add signed evidence and tamper detection.
- Establish continuous Kubernetes compliance monitoring.
- Add automated remediation for low-risk findings.
Skills Developed
Section titled “Skills Developed”By completing this lab, you will be able to:
- Design Kubernetes compliance automation
- Automate cluster inventory collection
- Automate CIS Benchmark assessments
- Scan Kubernetes manifests
- Scan running container images
- Export Kyverno reports
- Export Gatekeeper violations
- Define compliance thresholds
- Build compliance evaluation scripts
- Generate consolidated reports
- Configure scheduled Kubernetes assessments
- Create least-privilege assessment RBAC
- Build CI/CD compliance gates
- Test pass and failure conditions
- Manage evidence retention
- Track remediation
- Manage policy exceptions
- Design compliance dashboards
- Integrate compliance with SOC operations
- Produce enterprise compliance reports
Knowledge Check
Section titled “Knowledge Check”Question 1
Section titled “Question 1”Why should Kubernetes compliance assessments be automated?
Answer: Automation improves consistency, detects configuration drift faster, creates repeatable evidence, reduces manual effort, and supports continuous compliance.
Question 2
Section titled “Question 2”Why should compliance tools generate machine-readable reports?
Answer: Machine-readable formats such as JSON allow findings to be processed, correlated, scored, stored, displayed, and integrated with CI/CD or SIEM platforms.
Question 3
Section titled “Question 3”What is the purpose of a compliance threshold?
Answer: A compliance threshold defines the maximum acceptable number or severity of findings before an automated process fails or blocks deployment.
Question 4
Section titled “Question 4”Why should a compliance assessment Service Account use least privilege?
Answer: Assessment automation normally requires read-only access, and excessive permissions could allow a compromised automation process to modify or disrupt the cluster.
Question 5
Section titled “Question 5”What is the purpose of a Kubernetes CronJob in compliance automation?
Answer: A CronJob runs scheduled assessments inside the cluster to collect configuration, policy, or compliance evidence at defined intervals.
Question 6
Section titled “Question 6”Why should critical findings block a CI/CD pipeline?
Answer: Blocking prevents known high-risk or non-compliant configurations from reaching production before remediation or formal risk approval.
Question 7
Section titled “Question 7”Why must compliance evidence be protected?
Answer: Evidence supports audit, investigation, and management decisions, so unauthorised alteration or deletion would undermine its reliability.
Question 8
Section titled “Question 8”Why should exceptions have expiration dates?
Answer: Expiration prevents temporary security bypasses from becoming permanent unmanaged weaknesses.
Question 9
Section titled “Question 9”Does a high compliance score guarantee that a cluster is secure?
Answer: No. A score summarises control results but must be combined with technical analysis, threat monitoring, vulnerability management, and operational security.
Question 10
Section titled “Question 10”What should happen when the automated assessment process itself fails?
Answer: The failure should generate an alert, preserve available logs, prevent silent approval, and be investigated before production changes continue.
Lab Summary
Section titled “Lab Summary”In this lab, you built an enterprise Kubernetes compliance-automation framework.
You automated:
- Cluster inventory collection
- CIS Benchmark assessment
- Kubernetes manifest scanning
- Container-image scanning
- Kyverno PolicyReport export
- Gatekeeper violation export
- Compliance threshold evaluation
- Compliance summary generation
- Scheduled in-cluster assessments
- CI/CD security gates
- Evidence collection
- Remediation tracking
- Exception governance
- Compliance reporting
You also implemented a least-privilege Service Account, configured a Kubernetes CronJob, tested compliant and non-compliant pipeline conditions, designed evidence-retention requirements, defined dashboard metrics, and prepared SIEM integration.
Compliance automation transforms Kubernetes governance from an occasional manual review into a repeatable security process that can:
- Detect configuration drift
- Block unsafe deployments
- Preserve audit evidence
- Notify resource owners
- Track remediation
- Support management reporting
- Improve security consistency across clusters
What’s Next?
Section titled “What’s Next?”Next Lab: Lab 05 — Kubernetes Governance Assessment
In the next lab, you will perform a complete enterprise governance assessment covering cluster ownership, policy frameworks, admission controls, namespace governance, RBAC responsibilities, exception management, compliance reporting, change control, multi-cluster consistency, operational accountability, and production-governance readiness.