Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 629 of 8029. CI/CD Pipeline EngineeringFree lesson

Enforcing Immutable Infrastructure Policies

Apply automated checks to ensure that container configurations remain immutable and do not drift from hardened security baselines during deployment.

In this lesson, you will learn how to automate guardrails in your pipeline to ensure that your container configurations remain immutable and drift-free from your security baselines.

The Problem: Configuration Drift

In a high-velocity CI/CD environment, "configuration drift" occurs when container runtime settings—such as running as root, mounting sensitive host paths, or granting privileged capabilities—are modified after the image is built or during the deployment phase. Even if you secure your image build process, a loose Kubernetes manifest or a faulty kubectl command can bypass those protections, creating an insecure "mutable" environment.

Enforcing Immutability via Policy-as-Code

To prevent this, we shift our focus from "fixing" containers to "enforcing" them using Admission Controllers like OPA (Open Policy Agent) or Kyverno. By treating our infrastructure policies as code, we can reject any deployment that deviates from our hardened baseline before it ever reaches the cluster.

Instead of relying on manual audits, you integrate a policy-checking step directly into your deployment pipeline. If a developer attempts to deploy a Pod that lacks readOnlyRootFilesystem: true or attempts to run as a non-UID 0 user, the CI/CD pipeline triggers an immediate failure.

Implementation Example

Consider a snippet of a policy definition that enforces an immutable root filesystem:

apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: restrict-root-filesystem
spec:
  validationFailureAction: enforce
  rules:
  - name: validate-read-only-root
    match:
      resources:
        kinds:
          - Pod
    validate:
      pattern:
        spec:
          containers:
            - securityContext:
                readOnlyRootFilesystem: true

By setting the validationFailureAction to enforce, the Kubernetes API server will reject any workload that fails this check. This ensures that even if a developer modifies a manifest locally, the cluster remains a "source of truth" that strictly adheres to the hardened security baseline. Your pipeline should automate the application of these policies across all namespaces, ensuring that immutability is not just a goal, but a structural requirement for deployment.

Key Takeaway: Immutable infrastructure is enforced by shifting from manual verification to automated Admission Control policies that reject any deployment drifting from your hardened security standards.