Skip to content

Lab 04 — Kubernetes Compliance Automation

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

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.

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 Report
Discover
Assess
Validate
Record Evidence
Calculate Compliance
Notify Owners
Remediate
Reassess

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.

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

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

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
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
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/
Terminal window
mkdir -p lab-04-compliance-automation/{scripts,powershell,manifests,policies,pipeline,reports,evidence/screenshots}
cd lab-04-compliance-automation
Terminal window
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-automation

Run:

Terminal window
kubectl version --client
Terminal window
helm version
Terminal window
trivy version
Terminal window
kube-bench version
Terminal window
jq --version

Save the results.

Terminal window
{
kubectl version --client
helm version
trivy version
kube-bench version
jq --version
} > evidence/tool-versions.txt 2>&1

Task 03 — Record the Assessment Timestamp

Section titled “Task 03 — Record the Assessment Timestamp”
Terminal window
date -u +"%Y-%m-%dT%H:%M:%SZ" \
> evidence/assessment-timestamp.txt
Terminal window
(Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ") |
Out-File evidence\assessment-timestamp.txt

Every automated assessment should include:

  • Start time
  • End time
  • Cluster
  • Environment
  • Tool versions
  • Automation version
  • Operator or service identity
Terminal window
kubectl cluster-info
Terminal window
kubectl config current-context
Terminal window
kubectl auth can-i get pods --all-namespaces
Terminal window
kubectl auth can-i get deployments --all-namespaces

Use read-only permissions where possible.

Task 05 — Create the Compliance Namespace

Section titled “Task 05 — Create the Compliance Namespace”

Create manifests/namespace.yaml.

apiVersion: v1
kind: Namespace
metadata:
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: restricted

Apply it.

Terminal window
kubectl apply \
-f manifests/namespace.yaml

Task 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.

Terminal window
chmod +x scripts/collect-cluster-inventory.sh

Run it.

Terminal window
./scripts/collect-cluster-inventory.sh

Task 07 — Validate the Cluster Inventory

Section titled “Task 07 — Validate the Cluster Inventory”

Review:

Terminal window
jq '.' reports/cluster-inventory.json

Confirm 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.

Terminal window
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.

Terminal window
chmod +x scripts/run-kube-bench.sh

Run it.

Terminal window
./scripts/run-kube-bench.sh

If 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.

Terminal window
jq '.' reports/kube-bench.json

Count failed tests where supported by the output structure.

Terminal window
jq '[.. | objects | select(.status? == "FAIL")] | length' \
reports/kube-bench.json

Count warnings.

Terminal window
jq '[.. | objects | select(.status? == "WARN")] | length' \
reports/kube-bench.json

Record:

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.

Terminal window
chmod +x scripts/scan-manifests.sh

Run it.

Terminal window
./scripts/scan-manifests.sh manifests

Review:

Terminal window
jq '.' reports/manifest-scan.json

Identify:

  • 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/v1
kind: Deployment
metadata:
name: non-compliant-application
namespace: compliance-automation
spec:
replicas: 1
selector:
matchLabels:
app: non-compliant-application
template:
metadata:
labels:
app: non-compliant-application
spec:
containers:
- name: application
image: nginx:latest
securityContext:
privileged: true

Do not deploy this workload when admission policies would reject it.

Scan it locally.

Terminal window
trivy config \
manifests/non-compliant-deployment.yaml

Task 14 — Create a Compliant Test Deployment

Section titled “Task 14 — Create a Compliant Test Deployment”

Create manifests/compliant-deployment.yaml.

apiVersion: apps/v1
kind: Deployment
metadata:
name: compliant-application
namespace: compliance-automation
labels:
app: compliant-application
owner: cloud-security
environment: training
spec:
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.

Terminal window
trivy config \
manifests/compliant-deployment.yaml

Compare 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" || true
done < "$OUTPUT_DIR/image-list.txt"
echo "Container-image scanning completed."

Make it executable.

Terminal window
chmod +x scripts/scan-images.sh

Run it only against authorised images.

Terminal window
./scripts/scan-images.sh

Task 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

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.

Terminal window
chmod +x scripts/export-kyverno-reports.sh

Run it.

Terminal window
./scripts/export-kyverno-reports.sh

Review:

Terminal window
kubectl get policyreports -A

Create a JSON summary where policy reports are available.

Terminal window
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.json

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.

Terminal window
chmod +x scripts/export-gatekeeper-violations.sh

Run it where Gatekeeper remains installed.

Terminal window
./scripts/export-gatekeeper-violations.sh

Review:

Terminal window
jq '.' reports/gatekeeper-violations.json

Identify:

  • 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=1
fi
if (( MANIFEST_CRITICAL > MAX_MANIFEST_CRITICAL )); then
echo "FAIL: Critical manifest threshold exceeded."
EXIT_CODE=1
fi
if (( MANIFEST_HIGH > MAX_MANIFEST_HIGH )); then
echo "FAIL: High manifest threshold exceeded."
EXIT_CODE=1
fi
if (( EXIT_CODE == 0 )); then
echo "Compliance evaluation passed."
else
echo "Compliance evaluation failed."
fi
exit "$EXIT_CODE"

Make it executable.

Terminal window
chmod +x scripts/evaluate-compliance.sh

Task 22 — Test the Compliance Evaluation

Section titled “Task 22 — Test the Compliance Evaluation”

Run:

Terminal window
./scripts/evaluate-compliance.sh

Check the exit code.

Terminal window
echo $?

Expected:

0

when thresholds are satisfied.

Expected:

1

when thresholds are exceeded.

Temporarily scan the non-compliant manifest.

Terminal window
trivy config \
--format json \
--output reports/manifest-scan.json \
manifests/non-compliant-deployment.yaml

Run the evaluation.

Terminal window
./scripts/evaluate-compliance.sh

Expected:

Compliance evaluation failed

Restore 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.

Terminal window
chmod +x scripts/generate-summary.sh

Run it.

Terminal window
./scripts/generate-summary.sh

Review:

Terminal window
jq '.' reports/compliance-summary.json

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: -1

Example:

Critical Findings: 1
High Findings: 2
Medium Findings: 3
Low Findings: 4
Score:
100 - 20 - 20 - 15 - 4 = 41

Suggested 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: v1
kind: ServiceAccount
metadata:
name: compliance-assessor
namespace: compliance-automation
labels:
app: compliance-automation
owner: cloud-security

Apply it.

Terminal window
kubectl apply \
-f manifests/service-account.yaml

Task 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/v1
kind: ClusterRole
metadata:
name: compliance-assessor
rules:
- 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
- watch

Create manifests/rolebinding.yaml.

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: compliance-assessor
subjects:
- kind: ServiceAccount
name: compliance-assessor
namespace: compliance-automation
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: compliance-assessor

Apply:

Terminal window
kubectl apply \
-f manifests/role.yaml
Terminal window
kubectl apply \
-f manifests/rolebinding.yaml

Validate:

Terminal window
kubectl auth can-i list pods \
--as=system:serviceaccount:compliance-automation:compliance-assessor \
--all-namespaces

Task 29 — Create the Automation ConfigMap

Section titled “Task 29 — Create the Automation ConfigMap”

Create manifests/configmap.yaml.

apiVersion: v1
kind: ConfigMap
metadata:
name: compliance-automation-config
namespace: compliance-automation
data:
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:

Terminal window
kubectl apply \
-f manifests/configmap.yaml

Task 30 — Create the Scheduled Compliance CronJob

Section titled “Task 30 — Create the Scheduled Compliance CronJob”

Create manifests/compliance-cronjob.yaml.

apiVersion: batch/v1
kind: CronJob
metadata:
name: kubernetes-compliance-assessment
namespace: compliance-automation
labels:
app: compliance-automation
owner: cloud-security
environment: training
spec:
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:

Terminal window
kubectl apply \
-f manifests/compliance-cronjob.yaml

Verify:

Terminal window
kubectl get cronjob \
-n compliance-automation

Review:

Terminal window
kubectl describe cronjob kubernetes-compliance-assessment \
-n compliance-automation

Task 32 — Trigger a Manual Compliance Job

Section titled “Task 32 — Trigger a Manual Compliance Job”

Create a Job from the CronJob.

Terminal window
kubectl create job \
--from=cronjob/kubernetes-compliance-assessment \
compliance-manual-test \
-n compliance-automation

Monitor:

Terminal window
kubectl get jobs \
-n compliance-automation

Review the Pod.

Terminal window
kubectl get pods \
-n compliance-automation

Task 33 — Review Scheduled Assessment Logs

Section titled “Task 33 — Review Scheduled Assessment Logs”
Terminal window
kubectl logs \
job/compliance-manual-test \
-n compliance-automation

Save evidence.

Terminal window
kubectl logs \
job/compliance-manual-test \
-n compliance-automation \
> evidence/cronjob-result.txt

Review:

Terminal window
kubectl get cronjob kubernetes-compliance-assessment \
-n compliance-automation \
-o yaml

Validate:

  • 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 Block

Task 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: 30

Place the workflow in:

.github/workflows/kubernetes-compliance.yaml

after 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 days

Replace 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.yaml

Expected:

  • 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.txt

Task 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:

Terminal window
kyverno apply policies/ \
--resource manifests/ \
--policy-report

Validate command syntax against the installed Kyverno CLI version.

Before deployment, verify the approved image.

Terminal window
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: Fail

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:

Terminal window
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

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

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: Active

Every exception must be:

  • Specific
  • Approved
  • Time limited
  • Risk assessed
  • Monitored
  • Reviewed before expiry

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 Assessment

Dashboard filters:

  • Cluster
  • Environment
  • Namespace
  • Application
  • Owner
  • Severity
  • Control framework
  • Status

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 incident

Task 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”

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

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

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

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:

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.txt
02-cluster-context.txt
03-assessment-timestamp.txt
04-cluster-inventory.json
05-kubernetes-version.json
06-node-inventory.json
07-kube-bench.json
08-kube-bench.txt
09-manifest-scan.json
10-image-scan.json
11-kyverno-policyreports.yaml
12-gatekeeper-violations.json
13-compliance-thresholds.json
14-compliance-summary.json
15-compliance-cronjob.yaml
16-manual-job-result.txt
17-cicd-pipeline.yaml
18-pipeline-pass.txt
19-pipeline-failure.txt
20-exception-register.yaml
21-remediation-tracker.md
22-evidence-retention-policy.md
23-automation-assessment.md
24-enterprise-compliance-report.md
Terminal window
kubectl delete job compliance-manual-test \
-n compliance-automation \
--ignore-not-found

Task 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.

Terminal window
kubectl delete cronjob kubernetes-compliance-assessment \
-n compliance-automation

Delete the assessment RBAC only when no later lab requires it.

Terminal window
kubectl delete clusterrolebinding compliance-assessor
Terminal window
kubectl delete clusterrole compliance-assessor

Delete the namespace.

Terminal window
kubectl delete namespace compliance-automation

Do 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
  • 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.
  • 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.
  • 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.

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

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.

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.

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.

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.

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.

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.

Why must compliance evidence be protected?

Answer: Evidence supports audit, investigation, and management decisions, so unauthorised alteration or deletion would undermine its reliability.

Why should exceptions have expiration dates?

Answer: Expiration prevents temporary security bypasses from becoming permanent unmanaged weaknesses.

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.

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.

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

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.