## Intro

Securing a Kubernetes cluster in a CI/CD workflow means making security checks repeatable, version-controlled, and resistant to manual mistakes. Teams often treat cluster security as a one-time hardening task, then watch drift accumulate until a misconfiguration reaches production. The alternative is to treat every RBAC binding, NetworkPolicy, and container image as a pipeline artifact: scanned, validated, and rolled back with the same rigor as application code.

This guide is written for developers, DevOps consultants, and technical startup teams. It assumes you can run `kubectl` and have a basic deployment pipeline, but it does not assume you already have security automation in place. You will learn how to:

- Inventory your cluster version and tooling before changing anything
- Add container image scanning and policy checks to a pipeline
- Automate RBAC and NetworkPolicy changes with dry-run and diff verification
- Detect failures early and roll back safely
- Avoid the most common misconfigurations that create false confidence

Every step includes a concrete command, the expected output, and a recovery path when that output does not appear. The examples use a fictional company, `acme-corp`, with resources in the `production` namespace. Replace these names with your own values, but keep the verification habits.

## Version and Environment Inventory

Before automating security, you need to know the exact Kubernetes version, container runtime, and admission controller state of every cluster the pipeline targets. A security policy written for Kubernetes 1.29 may fail silently on 1.25 if you do not pin the API versions.

Start with a read-only inventory. These commands do not modify the cluster and can be run from a laptop with valid kubeconfig credentials:

```bash
kubectl version --short
kubectl get nodes -o wide
kubectl api-resources --api-group=rbac.authorization.k8s.io
kubectl api-resources --api-group=networking.k8s.io
```

Expected output for a healthy cluster shows the control plane and node versions matching exactly. For example:

```text
Client Version: v1.29.2
Server Version: v1.29.2
```

If the client is newer than the server by more than one minor version, stop and align your local tooling before applying any manifest. A policy object using `flowcontrol.apiserver.k8s.io/v1` will be rejected on a cluster that only serves `v1beta3`, and the error will not appear until mid-rollout.

Record the inventory in a Git-backed file, for example `cluster-inventory/acme-prod.txt`. Update this file at least quarterly or immediately after any cluster upgrade. The owner of this inventory should be a single engineer, not a shared mailbox. In a small startup, that person is often the platform lead, for example Priya Shah, who reviews the file during the same sprint as the upgrade.

Investigate the admission controller list as well:

```bash
kubectl get validatingwebhookconfiguration,mutatingwebhookconfiguration
```

If your pipeline plans to inject sidecars or enforce Pod Security Standards, the webhook list tells you whether another controller might reject the change first. Write down the webhook names and their failure policies. A `failurePolicy: Fail` webhook that is not in your inventory will cause phantom denial errors during pipeline runs.

Finally, test local access to a non-production namespace with a port-forward before touching a load balancer:

```bash
kubectl create deployment hello --image=nginx:1.25 -n dev
kubectl port-forward deployment/hello 8080:80 -n dev
```

Browse to `http://localhost:8080`. If you get an nginx welcome page, your local routing and service account permissions work. If you get `403 Forbidden`, check RBAC before proceeding. Keep this test small: one deployment, one replica, no persistent volumes.

## Safe Configuration Path

Automating security configuration requires a path from intent to verified change without human guessing. The safe path has four stages: manifest diff, dry-run, apply with a label, and post-apply verification. Each stage has a single accountable owner who approves the change before it advances.

### Stage 1: Manifest diff with GitOps

Keep all security manifests in a Git repository. Before merging a pull request, diff the rendered YAML against the cluster:

```bash
git diff origin/main...feature/network-policy | kubectl diff -f -
```

`kubectl diff` fetches the live object and prints a human-readable difference. For example, adding a deny-all NetworkPolicy to the `production` namespace shows:

```text
+apiVersion: networking.k8s.io/v1
+kind: NetworkPolicy
+metadata:
+  name: default-deny
+  namespace: production
+spec:
+  podSelector: {}
+  policyTypes:
+  - Ingress
+  - Egress
```

If the diff is empty, the cluster already matches the desired state, and the merge is a no-op. If the diff shows unexpected deletions (a `-` line removing an existing egress rule), stop the merge. The reviewer for this stage is the security engineer on call, for example Alex Chen, who must approve the diff in the pull request and write a short comment explaining why the deletion is intended.

### Stage 2: Server-side dry-run

Client-side diff can miss admission webhook rejections. Use `--dry-run=server` to run the full admission chain without persisting anything:

```bash
kubectl apply -f networkpolicy/ --dry-run=server
```

Expected output:

```text
networkpolicy.networking.k8s.io/default-deny created (server dry run)
```

If a webhook rejects the manifest, you see the webhook name and rejection reason in stderr. Treat that as a requirement change, not a pipeline failure. Update the manifest to satisfy the webhook, then repeat the dry-run.

### Stage 3: Apply with a change label

After dry-run passes, apply the change with a label that ties it to the pipeline run and the commit SHA:

```bash
kubectl apply -f networkpolicy/ -l security.acme.io/pipeline-run=2431,security.acme.io/commit=9f2b1c
```

This label lets you list all objects changed by a single pipeline run, even days later:

```bash
kubectl get networkpolicy -n production -l security.acme.io/pipeline-run=2431
```

The owner of the apply step is the release manager on duty. This role should be a named engineer, for example Maria Gonzalez, not a service account used by unrelated jobs. Maria applies only after seeing both the diff approval and the dry-run text in the pipeline logs. She repeats the apply at most once per change; if it fails, she rolls back and investigates instead of retrying blindly.

### Stage 4: Post-apply verification

Immediately after applying, run a read-only check that the policy is live and has the expected effect:

```bash
kubectl get networkpolicy default-deny -n production -o yaml | grep -A3 podSelector
kubectl rollout status deployment/api-server -n production
```

The rollout status must finish with `successfully rolled out`. If the api-server deployment has a failing readiness probe, the policy may have blocked its egress to a database. To test without disrupting production, create a temporary pod with a curl container:

```bash
kubectl run nettest --rm -it --image=curlimages/curl -- sh
curl -I https://api.internal.acme.com
```

A `200 OK` means the egress allow rule exists. A timeout means the deny-all is still too broad and needs an additional egress rule for port 443. Fix the manifest, rerun stages 1-3, and only then return to normal operations.

## Pipeline Integration with Image Scanning

Container images are the most common attack surface, yet many teams only scan them before the first deployment and never again. A production-grade pipeline scans on every push, blocks on critical vulnerabilities, and records the scan results next to the image SHA.

Use Trivy in a CI job. The following GitLab CI fragment scans an image built earlier in the pipeline and fails the job if any critical or high severity vulnerability has a fix available:

```yaml
scan-image:
  stage: security
  image: aquasec/trivy:0.50.1
  script:
    - trivy image --severity CRITICAL,HIGH --ignore-unfixed
        --exit-code 1
        registry.acme.com/myapp:${CI_COMMIT_SHORT_SHA}
  artifacts:
    reports:
      dependency_scanning: trivy.json
```

The `--exit-code 1` flag makes the job fail when vulnerabilities are found, which blocks the deploy stage. The `--ignore-unfixed` flag prevents false positives for vulnerabilities with no available patched image. The artifact `trivy.json` is stored with the pipeline run, so the security team can audit why a build was blocked without re-running the scan.

For a real example, suppose the scan finds `CVE-2024-21626` in the base image with a fixed version `1.25.4`. The pipeline output shows:

```text
registry.acme.com/myapp:9f2b1c (alpine 3.18.6)
Total: 2 (CRITICAL: 1, HIGH: 1)

CVE-2024-21626: runc container breakout (CRITICAL)
Fixed version: 1.1.12
```

The recovery path is to update the Dockerfile's `FROM alpine:3.18` to `FROM alpine:3.18.7`, rebuild, and re-run the pipeline. The owner of this decision is the application team lead, for example Samir Patel, who must approve the base image change in the same pull request that triggered the scan. Samir reviews the scan every time the base image changes, which in practice is monthly or whenever a critical fix appears in the alpine advisory feed.

When a scan fails, never disable the job with `allow_failure: true` just to unblock a deploy. Instead, mark the vulnerability as accepted in a separate allowlist file, with an expiry date. For example:

```yaml
# trivy-ignore.yaml
vulnerabilities:
  - id: CVE-2024-21626
    statement: Exploit requires privileged container; we run as non-root.
    expires: 2025-03-01
```

Pass this file to Trivy with `--ignorefile trivy-ignore.yaml`. The allowlist owner is the security lead, not the application team, and the expiry date forces a revisit at least once per quarter.

## Automating RBAC with Least Privilege

RBAC drift is invisible: an engineer adds a broad `cluster-admin` binding during a debugging session and forgets to remove it. Automating RBAC means defining the desired bindings in Git and continuously reconciling the cluster to match.

Create a Git repository `acme-rbac` with directories per cluster and namespace. Example `production/api-team.yaml`:

```yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: api-team-edit
  namespace: production
subjects:
- kind: Group
  name: api-devs
- kind: User
  name: priya.shah@acme.com
roleRef:
  kind: ClusterRole
  name: edit
  apiGroup: rbac.authorization.k8s.io
```

This binding grants the `edit` ClusterRole (which excludes `create` on `clusterroles` and `clusterrolebindings`) to the API team group and one named user in the `production` namespace. The owner of this binding is the application lead, Priya Shah, who reviews the group membership monthly with the platform team.

In the pipeline, first check that the live binding matches the Git file:

```bash
kubectl get rolebinding api-team-edit -n production -o yaml | kubectl diff -f production/api-team.yaml -
```

If the diff shows an extra subject, for example a contractor who left the company, push a fix. The expected diff for a removal shows:

```text
 subjects:
 - kind: Group
   name: api-devs
-- kind: User
-  name: temp.contractor@acme.com
```

Apply the fix with `kubectl apply -f`, then verify:

```bash
kubectl auth can-i create deployments --as temp.contractor@acme.com -n production
```

Expected output after removal:

```text
no
```

If the answer is still `yes`, the user is bound through another RoleBinding or a ClusterRoleBinding. Use `kubectl auth reconcile` to remove stale subjects automatically, but always review the reconcile diff in a pull request first:

```bash
kubectl auth reconcile -f production/ --dry-run=client
```

The reconciliation owner is the platform security engineer, Alex Chen, who runs this check weekly and opens a corrective pull request within 24 hours if drift is found.

For `cluster-admin` specifically, bind it only to a break-glass group with no standing members. Example `break-glass-cluster-admin.yaml`:

```yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: break-glass-cluster-admin
subjects:
- kind: Group
  name: break-glass-admins
roleRef:
  kind: ClusterRole
  name: cluster-admin
  apiGroup: rbac.authorization.k8s.io
```

The group `break-glass-admins` is empty in your identity provider. Access is granted temporarily with a ticket and revoked after 60 minutes via an IAM policy. The owner of this binding is the CTO, who reviews the group membership every Monday in the security stand-up.

## NetworkPolicy as Code

NetworkPolicy is the most often skipped security control because a default deny can break application dependencies that nobody documented. Implementing it in CI/CD requires first discovering existing traffic, then codifying it as allow rules, then enforcing the default deny.

Run a network visibility tool in audit mode for two weeks before enforcing. If you use Cilium, enable Hubble and record flows:

```bash
cilium connectivity test --flow-export file=flows.json
```

From the flow logs, build a matrix of allowed connections. Example for a three-tier app:

| Source | Destination | Port | Protocol | Needed for |
|---------|-------------|------|----------|------------|
| api-server | postgres-db | 5432 | TCP | Primary database |
| web-frontend | api-server | 8080 | TCP | REST API |
| api-server | redis-cache | 6379 | TCP | Session cache |
| api-server | auth-service | 8443 | TCP | Token validation |

The owner of this traffic matrix is the application architect, for example Lena Fischer. She updates it after any service addition or topology change, and the pipeline fails if a NetworkPolicy change introduces a connection not in the matrix.

Create a `netpol/api-server.yaml` with an explicit egress allow:

```yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: api-server-egress
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: api-server
  policyTypes:
  - Egress
  egress:
  - to:
    - podSelector:
        matchLabels:
          app: postgres-db
    ports:
    - protocol: TCP
      port: 5432
  - to:
    - podSelector:
        matchLabels:
          app: redis-cache
    ports:
    - protocol: TCP
      port: 6379
  - to:
    - podSelector:
        matchLabels:
          app: auth-service
    ports:
    - protocol: TCP
      port: 8443
```

Apply with the same four-stage safe path as RBAC. After applying, test the actual connection from a pod:

```bash
kubectl run pg-test --rm -it --image=postgres:16 -n production -- \
  psql -h postgres-db -U app_user -c 'SELECT 1;'
```

Expected output:

```text
 ?column? 
----------
        1
```

If the connection times out, the egress rule is missing or the DNS name resolves to a different pod label. Use `kubectl describe networkpolicy api-server-egress -n production` to confirm the rule is bound, then check that the `postgres-db` pod actually has the `app: postgres-db` label.

Only after all required egress rules are in place should you add the default deny:

```yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny
  namespace: production
spec:
  podSelector: {}
  policyTypes:
  - Ingress
  - Egress
```

Apply this last, and immediately run the pipeline's integration test suite. Any failing test indicates an unmodeled dependency. Roll back the default deny, add an egress rule, and re-apply. The owner of the default-deny rollout is the release manager, Maria Gonzalez, who retains the authority to roll back without a new change request if production traffic is impacted.

## Verification and Diagnostics

Verification is not a single post-deploy check; it is a continuous set of read-only signals that should be green before, during, and after a security change. The minimum set:

1. **Pod status and readiness.** Use `kubectl get pods -n production -l app=api-server -o wide`. All pods must be `Running` and `1/1` ready. If a pod is `CrashLoopBackOff`, inspect with `kubectl logs <pod> --previous -n production`. The previous container logs often show a missing secret reference or a denied egress.

2. **Event stream.** Use `kubectl get events -n production --sort-by=.lastTimestamp | tail -20`. Look for `FailedCreate`, `FailedScheduling`, or `FailedMount`. For example, a `FailedMount` on a secret named `api-db-creds` means the pipeline's secret injection stage did not run. Fix the pipeline to create the secret before the deployment.

3. **Rollout status.** Use `kubectl rollout status deployment/api-server -n production`. If the command times out, the deployment is likely stuck with a non-ready new replica. Use `kubectl describe deployment api-server -n production` and look for the condition `ProgressDeadlineExceeded` with a message. Do not proceed until the rollout is complete.

4. **Policy audit.** Use `kubectl get networkpolicy -n production --show-labels`. Confirm that the `default-deny` policy has the same pipeline label as the rollback release. If labels are missing, the policy may have been created manually outside the pipeline, which breaks the automatic reconciliation.

All four checks should run in the pipeline after every apply. Put them in a script `verify-security.sh` in the security repo, so they are versioned with the changes they verify. The owner of this script is the platform security engineer, Alex Chen, who updates it when a new resource type is added to the cluster. The script runs automatically on every merge to the main branch.

For diagnostics, map each failure to a known cause. A table of common ones:

| Symptom | Likely cause | First diagnostic command | Fix |
|---------|--------------|--------------------------|-----|
| Pod stuck in `ContainerCreating` | Image pull denied or registry auth missing | `kubectl describe pod <name> -n production` shows `Failed to pull image` | Add registry pull secret to the service account |
| Pod `CrashLoopBackOff` | App cannot connect to database due to new egress deny | `kubectl logs <pod> --previous -n production` shows connection timeout | Add egress rule for database port |
| Deployment rollout timeout | New SecurityContext `runAsNonRoot` fails because image expects root | `kubectl describe deployment` shows `Error: container has runAsNonRoot and image will run as root` | Rebuild image with non-root user in Dockerfile |
| NetworkPolicy not enforced | CNI plugin does not support NetworkPolicy (e.g. Flannel without network policy) | `kubectl get pods -n kube-system` and check for `calico-node` or `cilium` | Install a compatible CNI or use a different policy mechanism |

The table owner is the on-call security engineer, who updates a new row each time a novel failure is diagnosed. The table is reviewed monthly in the post-incident review meeting.

## Failure Modes and Recovery

Security changes fail in two ways: they fail to apply, leaving the cluster unchanged, or they apply but break legitimate traffic. Recovery must be planned for both.

### Failed apply: rollback to last known good commit

Because all security manifests live in Git, a failed `kubectl apply` means the live cluster still matches the previous commit. The pipeline should automatically `git revert` the offending commit and re-apply only the reverted manifests. For example, if a bad NetworkPolicy commit `9f2b1c` fails with `Error from server (Forbidden): error when creating`, the pipeline logs show the exact object. The revert commit re-applies the old policy, and the `kubectl apply -f` of that revert produces no diff.

Run a post-revert verification:

```bash
kubectl rollout status deployment/api-server -n production
kubectl get networkpolicy -n production -l security.acme.io/commit=9f2b1c
```

The second command should return no resources, confirming the bad commit's objects are removed. The owner of the revert decision is the release manager, Maria Gonzalez, who approves the revert within 10 minutes of the failure being detected by the pipeline.

### Applied but breaking traffic: targeted rollback

If the apply succeeds but user traffic fails, you may need to roll back only the security object that caused the failure, not the entire commit. For example, a `default-deny` NetworkPolicy applied successfully, but now the `web-frontend` cannot reach the `api-server`. Roll back the `default-deny`:

```bash
kubectl delete networkpolicy default-deny -n production
```

Then immediately test the frontend-to-api connection:

```bash
kubectl run curl-test --rm -it --image=curlimages/curl -- \
  curl -I http://api-server.production.svc.cluster.local:8080/health
```

Expected output: `HTTP/1.1 200 OK`. If the connection still fails, the problem is elsewhere, and the rollback was not the cause. The owner of this rollback action is the application team lead, Samir Patel, who must be paged through the normal on-call rotation and has 15 minutes to decide between rollback and adding an egress rule.

### State validation after any rollback

After any rollback, confirm that the cluster matches the last known good Git commit. Use `kubectl diff` against the Git HEAD:

```bash
git checkout main
kubectl diff -f production/ --recursive
```

An empty diff means the cluster is in sync. A non-empty diff shows exactly which objects remain changed. Record the diff in the incident ticket and schedule a follow-up to either restore the intended security change or accept the live drift with a new commit. The owner of the state validation is the platform security engineer, Alex Chen, who performs it before closing any security incident.

## Common Pitfalls and How to Avoid Them

**1. Scanning but not blocking.** A pipeline that reports vulnerabilities but always exits 0 provides false comfort. Avoid this by setting `--exit-code 1` in the scanner and requiring a human override with an expiry date. Review the override allowlist every month. The owner of the override list is the security lead.

**2. Broad network allow rules.** Writing `podSelector: {}` in an egress rule allows all pods, effectively disabling namespace isolation. Instead, use explicit pod selectors and namespace selectors. Example of a correctly scoped egress to a database in another namespace:

```yaml
egress:
- to:
  - namespaceSelector:
      matchLabels:
        name: data-plane
    podSelector:
      matchLabels:
        app: postgres-db
  ports:
  - protocol: TCP
    port: 5432
```

**3. RBAC role bindings with no namespace.** Creating a `RoleBinding` in the `default` namespace for a service account that runs in `production` has no effect. Always verify with `kubectl auth can-i --as <sa> -n <namespace>`. The pipeline should include this check as a smoke test before deploying the application.

**4. Ignoring certificate rotation in the pipeline.** If your pipeline manages TLS certificates for ingress, a failed rotation can take down all HTTPS traffic. Use a short-lived certificate manager like cert-manager with automatic renewal and a webhook to notify before expiry. The pipeline should have a scheduled job that runs `kubectl get certificate -A` weekly and fails if any certificate has less than 7 days to expiry. The owner of this job is the platform lead.

**5. Assuming Pod Security Standards are enforced.** Many clusters on older versions have no Pod Security Admission configured. A pod with `privileged: true` can still be created if no policy blocks it. Add a validating webhook or enable Pod Security Admission with the `restricted` profile in all namespaces except `kube-system` and `istio-system`. The pipeline should run `kubectl label namespace production pod-security.kubernetes.io/enforce=restricted` as part of the bootstrap, and the owner is the platform security engineer.

Each pitfall above is logged in the team's runbook with a concrete example of a past incident. The runbook is reviewed quarterly with the CTO. If a pitfall recurs, the runbook entry gets a higher priority label and a mandatory training session.

## Operations Checklist

Use the following checklist as a template for any security change. Each item has a single owner and a review frequency. Copy it into your ticketing system and fill in the names and dates.

1. **Inventory verified** (Owner: platform lead, Priya Shah, monthly). Confirm cluster version, CNI plugin, and admission webhooks match the inventory file. Run the read-only commands from the Version and Environment Inventory section.
2. **Image scan result reviewed** (Owner: application team lead, Samir Patel, per build). Check the scan artifact for new critical vulnerabilities. Approve any allowlist entries with an expiry date.
3. **RBAC diff approved** (Owner: security engineer, Alex Chen, per pull request). Review the `kubectl diff` output for the proposed RBAC change. Ensure no wider permission than necessary.
4. **NetworkPolicy traffic matrix updated** (Owner: application architect, Lena Fischer, on service change). The matrix file in Git must include the new connection before the policy is applied.
5. **Dry-run passed** (Owner: release manager, Maria Gonzalez, per deploy). The pipeline log shows `(server dry run)` with no webhook rejection.
6. **Post-apply verification green** (Owner: release manager, Maria Gonzalez, per deploy). All four checks in Verification and Diagnostics return expected output.
7. **Rollback tested** (Owner: platform security engineer, Alex Chen, quarterly). In a staging environment, deliberately apply a bad policy and verify the pipeline can revert to the last good commit within 10 minutes.

The checklist is stored in the security repository under `ops/checklist.md`. The platform lead is responsible for keeping it current. At the end of every sprint, the team reviews which items were skipped and why. Any item skipped for two consecutive sprints triggers an automatic security review with the CTO.

## Conclusion

Automating Kubernetes cluster security with CI/CD is not about running a single scanner or enforcing a one-time policy. It is about building a system where every security artifact has a life cycle: expressed in Git, diffed against the live cluster, applied with a dry-run, verified with read-only checks, and rolled back with a known good commit. The practices in this guide treat RBAC, NetworkPolicy, and image scanning as first-class pipeline citizens, not manual chores.

The most important habit is to verify before and after every change. If a command cannot show you the current state and the expected result side by side, it is not an operations procedure, it is a guess. Start with one low-risk item from the checklist: run the inventory commands, record the output, and compare it to your expectations. Then add the image scanning job to your pipeline and make it block on critical vulnerabilities. Finally, introduce the default-deny NetworkPolicy only after you have modeled the traffic matrix and tested the rollback path.

Security automation is never finished. Revisit the allowlists, RBAC bindings, and traffic matrix at the intervals described here. Assign owners to each artifact and keep the checklists in the same repository as the code. When an incident occurs, the recovery path should already be documented and rehearsed. A reliable technical workflow makes failure visible, protects sensitive values, limits changes to the intended resource, and defines recovery verification before an incident forces the decision.