Compliance and Audit Logging in Kubernetes
How to keep a trustworthy diary of everything that happens in a cluster, so that you can answer "who did what, when, and from where" for an auditor, an investigator or your own peace of mind.
Think of a bank. Every time someone opens a safe, moves money or changes a rule, a record is made: who it was, what they did, and at what time. Nobody finds this annoying, because everybody understands that without such a record, trust would be impossible. If a vault is found empty, the first thing investigators ask for is the book.
A Kubernetes cluster is a vault of a modern kind. It holds the programs that run a business, the secrets they use, and the settings that decide who may do what. Dozens of people and hundreds of automated programs are constantly changing it. If something goes wrong, or if a regulator asks how you control access to customer data, you need a book to open.
This guide is about that book. We will see what Kubernetes records by itself, how to choose what to record, how to protect and store the records, how to watch them for trouble, and how to turn them into the evidence that auditors ask for. Each idea comes with an everyday comparison, and there is no code to copy, just the thinking that makes the settings sensible.
1Why Audit Logs Matter
An audit log is a trustworthy record of actions. It answers questions that no other tool can.
The four questions
Almost every audit or investigation boils down to four questions: who did it, what did they do, when did it happen and from where did the request come? Add a fifth, was it allowed, and you have the core of what a good audit trail provides.
Three reasons teams need it
Detect and investigate
When someone steals a credential or a program misbehaves, the log shows the trail: which account, which actions, which targets. Without it, you only know that something is wrong.
Prove control
Rules and standards require you to show who has access and what they do. The audit log is the main proof that your controls work in practice, not only on paper.
Explain changes
“The service broke at 14:05. What changed at 14:04?” Audit logs answer this, and cut the time to find the cause of an outage.
Deter misuse
People who know that their actions are recorded are more careful. Insiders are discouraged from abusing their access.
What happens without it
Many clusters run for years with no audit logging at all, because the feature is not always switched on by default in self-managed installations. The first time anyone notices is during an incident or an audit, when the question “who deleted that namespace?” has no answer. The records cannot be recreated after the fact. A log you did not turn on is a log you will never have.
Compliance is not the same as security
Passing an audit and being secure overlap but are different. An audit checks that you have the controls you promised and can show evidence for them. Security asks whether attackers can actually get in. A good audit logging program serves both: it satisfies the auditor and gives defenders real visibility. A weak one satisfies neither: it produces mountains of data that nobody reads and that would not help in a real investigation.
Consider the security cameras and the sign-in book at an office. The cameras and the book do not stop a thief by themselves. But they let the company find out what happened, show the police what they need, and prove to the insurer that the premises were properly controlled. The same is true of audit logs.
2Audit Logs, Application Logs, Metrics and Events
Kubernetes produces several kinds of records. Mixing them up is the first source of confusion.
| Kind | What it records | Who writes it | Good for |
|---|---|---|---|
| Audit log | Each request made to the API server, with who, what, when, from where and the result | The API server | Accountability, security investigation, compliance evidence |
| Application logs | What a program says about its own work | Your applications | Debugging application behavior |
| Node and system logs | Events of the operating system, kubelet and container runtime | The nodes | Diagnosing machine-level problems and some security events |
| Kubernetes events | Short notes about things like scheduling, image pulls and probe failures | Cluster components | Understanding why a Pod is not starting; they expire quickly |
| Metrics | Numbers over time, such as CPU use and request counts | Components and exporters | Capacity, performance, alerting |
| Runtime security events | Suspicious behavior inside containers, such as an unexpected shell | Runtime security tools | Detecting attacks on running workloads |
| Cloud audit logs | Actions on cloud resources such as machines, networks and storage | The cloud provider | Seeing changes outside the cluster that affect it |
What is special about the audit log
Application logs are written by programs and describe what they chose to say. The audit log is written by the API server about every request it receives, regardless of what the caller wanted. The caller cannot opt out. That independence is what makes it useful as evidence: the record of the action is made by the gatekeeper, not by the person acting.
What the audit log does not show
- Anything done inside a container after someone gets a shell. The audit log shows that a shell was opened (an exec request), but not the commands typed inside.
- The contents of your application data, such as database rows.
- Actions that never touch the API server, for example a process on a node talking directly to the container runtime, or one container talking to another over the network.
- Changes in the cloud account outside Kubernetes, such as editing a firewall rule, which are covered by the cloud provider’s own logs.
A complete picture therefore combines several sources, and later chapters show how.
The audit log is the bank’s record of who entered the vault and what they signed for. The application logs are what each teller writes in their own notebook. The security cameras inside the vault are the runtime security tools. The three tell different parts of the story, and an investigator wants all of them.
Kubernetes events are not audit logs. They are short-lived notes, kept for about an hour by default, and are not designed to be evidence. If you need a lasting record, rely on audit logs.
3The Compliance Landscape in Plain Words
Many standards touch Kubernetes. They use different words, but they ask similar things about logging.
Common frameworks and what they want from logs
| Framework | What it is about | Typical expectations about logging |
|---|---|---|
| SOC 2 | Trust criteria for service organizations, assessed by an auditor | Monitor systems for unusual activity, record changes and access, review and respond to events |
| ISO/IEC 27001 | An information security management standard | Log user activity and security events, protect the logs, synchronize clocks, review regularly |
| PCI DSS | Protecting payment card data | Record access to systems and cardholder data environments, protect and keep logs for a defined period, review daily by automated means |
| HIPAA | Protecting health information in the United States | Audit controls that record and examine activity in systems holding protected health information |
| GDPR | Personal data protection in the European Union | Accountability and security of processing; logs help show who accessed personal data, while logs themselves must respect data minimization |
| NIST guidance | US government security controls and cloud-native guidance | Audit event selection, content, storage capacity, protection and review |
| CIS Kubernetes Benchmark | A checklist of secure settings | Enable API server audit logging, set a policy, keep logs for a suitable time |
| Internal policy | Your own company rules | Often stricter than any outside standard |
Themes that repeat
- Record the right events: logins, access to sensitive data, changes to permissions and configuration, and failures.
- Include the right details: who, what, when, where and the outcome.
- Protect the records: from change, from deletion and from unauthorized reading.
- Keep them long enough: retention periods are often a year or more, with some period readily available for quick search.
- Review them: someone or something must actually look, regularly, and act on findings.
- Keep clocks accurate: timestamps must be reliable across systems to reconstruct a sequence.
- Show it works: be ready to provide evidence on request.
Shared responsibility
Standards usually apply to your whole environment, and cloud providers have their own certifications for their part. A managed Kubernetes service may handle the control plane’s logging infrastructure, but you must still enable, configure, retain and review those logs for your own workloads. Responsibility for what runs in the cluster always remains yours.
A note on specifics
Requirements, retention numbers and wording vary between versions of each standard and between assessors. Treat the table as a general guide, and confirm exact requirements with your compliance team or assessor before designing retention and review processes.
Different countries have different traffic laws, but nearly all ask drivers to carry a license, follow signs and keep records of accidents. A compliance framework is like a country’s rulebook: the details differ, but the habits that satisfy one tend to satisfy most others.
Designing logging for one auditor’s checklist, and then discovering that another framework requires a longer retention or a different review step. Start with the strictest expectations you may face, and design once.
4Where Audit Events Are Born: The Request Journey
To understand audit logs, follow a single request from a person to the cluster’s memory.
flowchart LR
U["Person, tool or program"] -->|"request"| AUTHN["1. Authentication: who are you?"]
AUTHN --> AUDIT["Audit layer: records the request"]
AUDIT --> AUTHZ["2. Authorization: are you allowed?"]
AUTHZ --> MUT["3. Mutating admission: modify request"]
MUT --> VAL["4. Validation and policy admission"]
VAL --> ETCD[("5. Stored in etcd")]
ETCD --> RESP["Response to caller"]
RESP --> AUDIT2["Audit layer: records the result"]
AUDIT --> BACKEND["Audit backend: log file or webhook"]
AUDIT2 --> BACKEND
Reading the diagram
Every request to the cluster, whether from a human typing a command or a program calling the API, passes through the same series of gates. First, authentication decides who the caller is. Then, authorization checks whether that caller may do this action. Next, admission steps may change the request or reject it on policy grounds. If everything passes, the object is stored in the cluster’s memory, etcd, and a response is returned.
The audit layer sits near the front. It notes the request as soon as the caller’s identity is known, and again when the request completes. That placement is important: even requests that are denied at authorization or rejected by policy are recorded. The failed attempts are often the most interesting part of an investigation.
What is and is not captured
| Event | Audited? | Comment |
|---|---|---|
| Creating, changing or deleting an object | Yes | Includes the user, the object and the outcome |
| Reading or listing objects | Yes, if the policy asks for it | Reads are noisy; choose carefully |
| A request denied by authorization | Yes | Marked with the decision and the reason |
| A request rejected by an admission policy | Yes | The response shows the rejection |
| Failed authentication | Often only as an anonymous or unauthenticated request | Depends on the setup; also check the identity provider’s own logs |
| Opening a shell in a Pod (exec) | Yes, as a request on the Pod’s exec subresource | Shows who opened it, but not what was typed |
| A watch connection | Yes, at start and end | Long-running requests produce an extra stage |
| Health checks and system noise | Possibly; usually filtered out by policy | These dominate volume if not excluded |
Who calls the API server
Not only people. The kubelets on every node, the controllers inside the control plane, the scheduler, your operators, your CI tools and your monitoring agents all make requests, thousands per minute. The great majority of audit events come from these system components, not from people. A good audit policy separates the routine chatter from the human and sensitive activity.
The audit layer is like the receptionist at a company’s front desk. Everybody who comes in has to pass the desk: employees, delivery people, visitors. The receptionist notes who came, what they asked for and whether they were let in, including the people who were turned away.
When you review audit events, learn to recognize the system accounts of your cluster first. Once you know what normal machine chatter looks like, human actions and unusual requests stand out.
5Stages of an Audited Request
A single request can produce more than one audit event, one for each stage of its life.
The four stages
RequestReceived
Generated as soon as the audit layer sees the request, before any processing. It shows that someone knocked on the door, even if the request later fails or hangs.
ResponseStarted
Generated only for long-running requests such as watches, once the response headers are sent but before the body is complete.
ResponseComplete
Generated when the response body has been sent and the request is finished. This one carries the final status code and is usually the most useful.
Panic
Generated if the server hits an internal failure while handling the request.
Why stages matter for volume and clarity
If you record every stage of every request, the log doubles or triples in size and each action appears several times. Most teams omit the RequestReceived stage, since the ResponseComplete event already includes everything needed. The omit-stages setting in the audit policy controls this. Keep the first stage only if you specifically need to prove that requests that never finished were still seen.
A unique thread: the audit ID
Every request gets a unique audit identifier, and all events from the same request share it. If you do keep several stages, that identifier ties them together. It also lets you correlate across systems, for example by seeing the same identifier in a webhook’s logs or a proxy’s logs.
Timing information
Each event carries timestamps for when the request was received and when the stage finished. The difference shows how long the request took. Unusually slow requests can point to performance problems or to heavy use such as someone listing every Secret in the cluster.
| Stage | Keep it? | Reason |
|---|---|---|
| RequestReceived | Usually omit | Doubles volume; the complete event has the details |
| ResponseStarted | Rarely needed | Mostly of interest for long watch connections |
| ResponseComplete | Keep | Contains the outcome |
| Panic | Keep | Indicates server problems and possible attempts to crash it |
A courier delivery has several scans: picked up, out for delivery, delivered. For most customers, the final “delivered” scan is what matters, and the others only add clutter. But if a package goes missing, the earlier scans tell you where it got lost.
6Audit Levels: How Much Detail to Record
For each request, you choose how much of it goes into the log. The choice balances usefulness, volume and the risk of recording sensitive data.
The four levels
Do not record
The request leaves no audit event. Used for noise such as health checks and routine system calls.
Who, what, when
Records the user, the verb, the resource, the time and the result, but not the contents of the request or response. Safe and small.
Plus the request body
Adds the content sent by the caller, such as the object they tried to create or change. Not available for the response.
Plus both bodies
Adds the object returned in the response too. Most detailed, largest, and the riskiest for sensitive data.
What each level lets you answer
| Question | Metadata | Request | RequestResponse |
|---|---|---|---|
| Who deleted this Deployment? | Yes | Yes | Yes |
| What exactly did they change in the Deployment? | No | Yes, the new version they sent | Yes |
| What did the system store after defaults and policies applied? | No | No | Yes |
| Which Secrets did this account list? | Yes | Yes | Yes, but contents are exposed |
| What were the secret values? | Not recorded, which is what you want | Recorded, which is a risk | Recorded, which is a risk |
The Secret trap
If you log request or response bodies for Secrets, the log will contain the secrets themselves: passwords, tokens, keys. That turns your audit log into a rich target for attackers, and defeats the purpose of controlling who can read secrets. The standard rule is to record Secrets, ConfigMaps that may hold tokens, and authentication-related objects at Metadata level only. You still learn who touched them and when, without copying the contents.
Choosing levels sensibly
- Metadata for most things: a good default for reads and routine changes.
- Request or RequestResponse for key configuration changes: RBAC objects, admission policies, network policies and workload definitions in sensitive namespaces, where the exact change matters.
- None for pure noise: health endpoints, the routine lease renewals of system components and node status updates.
- Metadata for anything with secret content: Secrets, service account tokens, token review and certificate signing requests.
The front-desk log can say “Maria entered the records room at 10:02” (Metadata), or also list the files she picked up (Request), or even photocopy those files for the log (RequestResponse). Photocopying confidential files into the visitor book would create a bigger leak than the one you were trying to prevent.
Setting the whole cluster to RequestResponse “to be safe” produces enormous logs filled with secrets, and costs the API server performance. More detail is not automatically better; it must be chosen for a reason.
7Designing an Audit Policy
The audit policy is the rulebook that decides, request by request, what level to record. Writing it well is the single most important step.
How the policy works
A policy is an ordered list of rules. Each rule describes a kind of request, matching on things such as the user, the user group, the verb (get, create, delete and so on), the resource type, the namespace or a URL pattern, and assigns a level. When a request arrives, the rules are checked from the top, and the first rule that matches decides its level. If no rule matches, the request is not recorded at all, so a policy should end with a catch-all rule.
The order matters
Because the first match wins, specific rules must come before general ones. If a general rule saying “record everything at Metadata” sits at the top, none of the later, more specific rules will ever be reached. A well-ordered policy places the exclusions of noise first, then the special handling of sensitive objects, then rules for important changes, and finally a catch-all.
A sensible order, described in words
Silence the noise
Do not record the health and version endpoints, the frequent status updates from nodes, and the routine lease updates of control plane components.
Reduce known high-volume readers
System components such as the proxy and the controller manager read and watch many objects continuously. Skip or minimize those reads.
Protect secrets
Record Secrets, ConfigMaps and token-related requests at Metadata only, for every user.
Capture sensitive changes in detail
Record changes to RBAC objects, admission configuration, network policies, workload definitions and custom resources that matter, at Request or RequestResponse level.
Record everything else at Metadata
A final catch-all rule means nothing slips through unrecorded.
Choosing what to exclude
| Candidate for exclusion | Why | Caution |
|---|---|---|
| Health and readiness endpoints | Hit constantly, no security value | None, but confirm that these are only checks |
| Lease objects for leader election | Updated every few seconds | Only for system accounts |
| Node and Pod status updates from kubelets | Huge volume | Keep other kubelet actions that matter, such as reading secrets |
| Watch and list requests from system controllers | Thousands per minute | Match by user so that humans doing the same are still recorded |
| Event objects | High volume and low value | Reconsider if you need them for investigations |
The omit-stages and omit-managed-fields settings
Policies can also drop the RequestReceived stage, as discussed, and omit managed fields, which are bookkeeping data about who set each field and make request bodies much larger without adding evidence value. Using both of these cuts volume significantly with little loss.
Start from a known example, then adapt
The Kubernetes project and cloud providers publish example policies. Cloud-managed clusters often come with a fixed or semi-fixed policy, and some allow configuration of what is sent. For self-managed clusters, begin with a published example and adapt it with your own namespaces, custom resources and sensitive objects. Test the policy in a non-production cluster, measure the volume and review a sample of events before rolling it out.
Treat the policy as code
Keep the audit policy in version control, review changes like any other security change and record who approved them. The policy itself is audit evidence: auditors will ask what you log and why, and a reviewed document with history is a strong answer.
A policy is like the instruction card at a security desk: “Don’t note staff passing through the main door. Always write down visitors to the server room. For the vault, note who entered and when, but never photocopy the contents.” The guard reads from the top and applies the first instruction that fits.
After deploying a new policy, count events per hour grouped by user and resource for a day. The top few lines usually reveal the noise you forgot to silence.
8Audit Backends: Log Files and Webhooks
Once an event is created, it must be sent somewhere. The API server offers two built-in destinations.
Log file backend
The API server writes events as lines of structured text to a file on the control plane machine. You control the path, the maximum age of files, the number of old files kept and the maximum size before rotation. A log shipper running on the machine then reads the file and sends it onward. This method is simple and reliable, since the API server does not depend on anything remote to keep running, but it ties you to the control plane machine’s disk and requires running and securing the shipper there.
Webhook backend
The API server sends events over the network to a service you operate, in batches. The service receives them and does what you decide: store, forward, filter or alert. It removes the need to run an agent on the control plane machine, but it creates a dependency: if the receiver is slow or down, the API server may buffer events, drop them, or in blocking mode slow down. Several settings control batching, buffer size, retry behavior and whether sending blocks the request.
Log file backend
- Independent of network health
- Easy to inspect on the machine
- Well understood, with standard shippers
- Needs an agent on control plane nodes
- Not available on managed control planes you cannot reach
Webhook backend
- Centralized by design
- No file on the node to protect
- Flexible processing on the receiver side
- Depends on the receiver being healthy and reachable
- Misconfiguration can drop events or add latency
Batching and blocking modes
Backends can run in batch mode, where events are collected in memory and sent in groups, or in blocking mode, where each event must be written before the request continues. Blocking gives the strongest guarantee that an action is recorded, since no action completes without a record, but it adds delay to every request and makes the API server depend on the backend. Batch mode is faster, with a small risk that events are lost if the server crashes or the buffer overflows. Most clusters choose batch mode with generous buffers and monitoring of dropped events.
What happens when the backend struggles
- With a full buffer in batch mode, the API server drops events and counts the drops in its own metrics. You must watch this metric.
- With blocking mode, requests slow down or fail until the backend recovers.
- With the file backend, a full disk can cause trouble for the control plane machine. Size and rotate the files, and monitor the disk.
The shipping path
Whatever backend you choose, the goal is the same: get the events off the control plane quickly into a protected, centralized place. A record that stays only on the machine where it was written can be tampered with by anyone who compromises that machine, and it vanishes if the machine does. Later chapters cover the full pipeline.
Writing to a local file is like keeping the visitor book in a drawer at the front desk: always there, but only as safe as the desk. The webhook is like phoning each visit in to head office as it happens: a central copy, but dependent on the phone line working. Cautious companies do both.
Setting up a webhook receiver on the same cluster that it audits creates a loop: audit events generate traffic that generates more audit events, and when the cluster is in trouble the receiver may be down exactly when you need it. Run the receiver outside the cluster, or in a separate, protected one.
9Managed Kubernetes: Audit Logging on EKS, GKE and AKS
On managed services you cannot edit the API server’s settings directly, so audit logging works through the provider’s own features.
The general pattern
The provider runs the control plane and collects its audit events. You decide whether to switch on delivery of those logs into your account, where they land, and how long they are kept. The policy is largely chosen by the provider, so you accept what is recorded, with some control over what you retain and alert on.
| Area | Amazon EKS | Google GKE | Azure AKS |
|---|---|---|---|
| Audit log delivery | Control plane logging can be enabled per log type, including audit, delivering to the provider’s logging service | Admin activity audit logs are on by default; data access logs and detailed settings can be enabled | Diagnostic settings send the audit log categories to a workspace, storage account or event stream |
| Where to store | The logging service, with export to object storage for long retention | The cloud logging service, with sinks to storage, analytics or messaging | A log analytics workspace, with archive to storage |
| Cloud-level activity | Separate cloud audit trail for actions on the cluster resource itself | Cloud audit logs cover cluster management | The activity log covers resource management operations |
| Identity mapping | Cloud identities map into cluster users and groups through a configured mapping | Cloud identities and groups integrate with cluster authorization | Directory identities integrate with cluster authorization |
| Cost note | Ingestion and storage are billed; high-volume audit logs can be expensive | Some audit categories are free while others are billed | Ingestion and retention are billed |
Always check these things
- Is audit log delivery switched on? On some services it is off by default for the Kubernetes audit category, and you must enable it deliberately.
- How long are logs kept by default? Often much shorter than compliance requires. Export to long-term storage with your own retention.
- What is in the events? Check whether the cloud identity appears in the user field, or only a mapped role name. This affects how well you can attribute an action to a person.
- What levels does the provider record? Providers may record at Metadata or Request level, and may filter certain requests. Read the documentation so you know what evidence you actually have.
- Who can read, change or delete them? Apply tight access controls on the log destination.
Two layers, not one
On managed services, two audit trails exist and both matter. The Kubernetes audit log records requests to the cluster’s API. The cloud audit trail records actions on the cloud resources: creating or deleting the cluster, changing node groups, altering network rules, modifying permissions of the cloud accounts. Someone could weaken the cluster’s security without ever touching the Kubernetes API, for example by changing a firewall or granting a cloud role. Collect and review both.
Features change
Each provider adds and renames audit features regularly. The table is a map of the general approach, not a substitute for current documentation. Before an audit, re-read the provider’s current guidance and confirm what your configuration really records.
Renting an office in a managed building, the landlord keeps the logs of who enters the building, and you keep the logs of who enters your suite. A burglar could get to your suite by bypassing the lobby, or by persuading the landlord’s staff. A careful tenant asks to see both records.
Audit logs from managed control planes are normally delivered with a small delay, often seconds to minutes. For real-time response, plan for that delay and combine with runtime detection on the nodes.
10Reading an Audit Event Field by Field
An audit event is a small structured record. Learning to read it quickly is the core skill of every investigator.
The fields that matter most
| Field | What it tells you | Why it matters |
|---|---|---|
| Audit ID | A unique identifier of the request | Links all stages of one request, and lets you refer to it unambiguously |
| Stage | Which stage this event records | Tells you whether you are looking at the final outcome |
| Request timestamp and stage timestamp | When the request arrived and when this stage ended | Ordering events and measuring duration |
| Verb | The action: get, list, watch, create, update, patch, delete | Distinguishes reading from changing |
| Request URI | The address that was called | Shows the exact path, including namespace and object name |
| Object reference | Resource type, namespace, name and subresource | Shows what was targeted, such as a Pod’s exec subresource |
| User | The authenticated name, plus groups and extra attributes | The “who” |
| Impersonated user | Present when someone acted as another identity | Reveals that the visible user is not the real actor |
| Source IPs | Network addresses the request came from, including forwarding hops | The “from where” |
| User agent | The client software that made the call | Distinguishes a person using a command-line tool from a script or a library |
| Response status | Result code and message | Success, forbidden, not found, conflict, and so on |
| Request and response objects | The bodies, only if the level asks for them | Exact content of the change |
| Annotations | Extra notes added during processing, such as the authorization decision and its reason, or the admission decisions | Explains why a request was allowed or denied |
Reading one event, in words
Suppose an event says: verb “delete,” resource “deployments” in namespace “payments,” name “checkout,” user “alice@example.com” in group “platform-admins,” source address from the office network, user agent a command-line tool, response code 200, and an annotation saying that authorization allowed it through a particular role binding. In plain English: Alice, from the office, using the standard tool, deleted the checkout Deployment in the payments namespace, and she was allowed to because of her membership in the platform admins group. In one line, you have the four questions answered, plus the fifth.
Response codes worth recognizing
Success
The action happened. For changes, this is the line that proves a change was made.
Unauthorized
The caller could not be authenticated. Repeated 401s may indicate password or token guessing, or an expired credential in a script.
Forbidden
The caller was known but not allowed. A burst of 403s from a single account may mean exploration of what it can do.
Not found
The object does not exist. Many 404s on guessed names can be probing.
Conflict
The object changed meanwhile or already exists. Usually benign.
Server error
The API server failed. Investigate for stability and for attempts to overload it.
Annotations as explanations
The authorization annotations record the decision made and the reason, often naming the role or binding that granted access. This is gold for compliance: it tells an auditor not only that an action was allowed, but which rule allowed it. Admission-related annotations, depending on your configuration, record which policies were applied or which webhooks modified the request.
Group and extra fields
The user’s groups explain much of their access. The extra attributes may hold information supplied by the identity provider, such as the cloud identity behind a mapped role. Look at these to see through generic names to the actual person.
An audit event is like a receipt from a shop: date and time, who served you, what you bought, the amount and the payment result. Once you have learned where each item sits on a receipt, you can scan a pile of receipts in seconds and spot the odd one.
Build a saved search or dashboard in your log tool that displays only the fields above, in that order. Raw event text is hard to read at speed, and a clean table of who, what, where and result makes reviews much faster.
11Identity: Making “Who” Mean a Real Person
An audit log is only as good as the identities in it. If everyone shares the same account, the log says “admin did it,” which proves nothing.
How Kubernetes identifies callers
Kubernetes has no built-in user database. It accepts identities from several sources and records whatever name the source supplies:
- Client certificates: the name inside the certificate becomes the user, and the organization fields become groups.
- Bearer tokens from an identity provider (OIDC): the user and groups come from claims in the token issued by your company’s login system.
- Service account tokens: programs running in the cluster, named after their namespace and service account.
- Cloud provider authenticators: cloud identities mapped to cluster users.
- Webhook token authentication and proxies: custom systems that vouch for a caller.
- Anonymous requests: callers with no credentials, if allowed at all.
The shared-account problem
Many clusters start with an administrator certificate in a shared file, used by several people. Every action then appears under the same name. The audit log cannot say which person did it. Compliance frameworks usually require individual accountability, so shared credentials are a common audit finding.
Good identity practice
- Every person logs in through the company identity provider
- Credentials are short-lived and tied to the person
- Groups come from the directory, so access follows job roles
- Multi-factor authentication happens at the identity provider
- When someone leaves, access ends automatically
Identity practice to avoid
- Shared administrator certificates
- Long-lived certificates and tokens copied to laptops
- Local accounts that are not tied to HR records
- Service account tokens used by humans
- Anonymous access left on
Service accounts: the non-human callers
Programs in the cluster use service accounts. Each should have its own, with only the access it needs, so that the audit log shows which program did what. A single default service account used by dozens of applications blurs attribution and encourages excess permissions. Newer versions favor short-lived, automatically rotated tokens bound to a Pod, rather than permanent tokens stored in secrets, which are both safer and easier to attribute.
Impersonation
Kubernetes lets an authorized user act as another user or group. This is useful for testing permissions, but it can also hide the true actor. The audit event records the impersonated identity in a separate field. Auditors and defenders should watch for impersonation, restrict who may do it, and make sure the real actor remains visible in the log.
Break-glass access
Sometimes administrators need emergency access that bypasses normal approvals. Handle this with a documented break-glass process: a special, strongly protected account or role, granted for a short time after approval, with every use alerted and reviewed afterwards. The audit log is the evidence that break-glass access was used only when justified.
The special administrator group
Kubernetes treats members of a special built-in administrators group as all-powerful: authorization checks are bypassed for them, so even a missing role binding does not stop them. Credentials for this group, for instance the initial administrator certificate of a self-managed cluster, must be locked away, rarely used, and every use should raise an alert.
An office where all employees use one shared key card cannot tell who entered the server room on Tuesday night. Giving each person a personal card, and keeping one emergency master card in a sealed envelope whose opening is itself recorded, lets the log mean something.
Assuming that the identity provider’s own logs are enough. They show logins, not what the person did in the cluster. You need both, tied together by the username or email that appears in each.
12RBAC Review: Using Logs to Right-Size Permissions
Role-based access control decides who may do what. Audit logs show who actually does what. Comparing the two is a powerful compliance practice.
The permission gap
Most users and service accounts have far more permission than they ever use. Roles are granted for convenience, “just give them admin for now,” and never trimmed. The gap between granted and used permission is unneeded risk. Audit logs reveal the used side: for each identity, which verbs on which resources they have really exercised in the past months.
A review cycle
List what is granted
For each person, group and service account, list the roles and bindings that apply, including those inherited through groups.
List what is used
From the audit log, summarize the actions each identity has performed over the review period, say ninety days.
Compare
Find permissions that were never used, accounts that were never active and powerful roles used only for simple tasks.
Propose reductions
Draft smaller roles that match actual use, with owners confirming that rare tasks, such as quarterly jobs, are still covered.
Apply and monitor
Make the changes, perhaps first in a warning mode, and watch the 403 responses for legitimate needs that were missed.
Record the review
Keep the outcome and approvals as evidence for the access review that most standards require.
Permissions to scrutinize first
| Permission | Why it is risky |
|---|---|
| Cluster-wide administrator role | Can do anything anywhere |
| Reading Secrets | Exposes passwords and tokens; even “list” shows contents |
| Creating or editing roles and bindings | Allows a user to grant themselves more power |
| Executing into Pods or attaching to them | Gives a shell inside workloads, bypassing application controls |
| Creating Pods in sensitive namespaces | Can mount secrets, run privileged containers or reach node resources |
| Impersonation | Can act as another identity |
| Modifying admission policies and webhooks | Can switch off the guardrails |
| Access to the node proxy or kubelet API | Reach into nodes and workloads |
| Creating tokens for service accounts | Can obtain the powers of that account |
Reading authorization decisions
The authorization annotations in audit events name the rule that allowed or denied the request. Use them to find which bindings are doing the real work, and which are idle. A role that never appears as a reason for an allow decision in months is a candidate for removal.
Tools that help
Several open-source tools can analyze roles and bindings, show who can do what, and suggest policies based on audit data. They differ in features and maturity, so evaluate them in a test cluster. The principle is the same whichever you pick: compare declared access to observed use, and trim the difference.
A janitor with a master key that opens every room in the building might use only three doors in a year. A security review looks at the door log, notices that only three doors were opened, and issues a key for those three, while keeping a procedure for borrowing the master key on rare occasions.
Schedule the access review quarterly, and attach the result to your compliance calendar. A review that happens on schedule is far easier to defend than one rushed together the week before an audit.
13What Not to Log: Secrets, Personal Data and Privacy
Logging is also a risk. Logs can leak the very data you are trying to protect, and privacy laws apply to logs too.
The sensitive things that creep in
Passwords and keys
If request bodies are logged for Secrets, tokens and credentials end up in plain text inside the log.
Authentication material
Token review and certificate requests can carry credentials. Record only their metadata.
Hidden credentials
ConfigMaps and environment variables in workload definitions sometimes hold keys or connection strings by mistake.
Names and identifiers
Usernames, email addresses and IP addresses are personal data under many privacy laws. Custom resources may hold customer information.
Custom objects
Custom resources can store application records. Full request logging copies that data into the log.
Principles for safe logging
- Metadata first. Use Metadata level wherever the content is not needed to answer a real question.
- Exclude by resource type. Treat Secrets, tokens, certificates and any custom resource that holds personal data as Metadata-only.
- Reduce at the source, in the policy, rather than hoping to clean the data later.
- Scrub in the pipeline for anything that slips through: filters that mask patterns such as tokens and card numbers.
- Control who reads the logs, since even metadata reveals who accessed what and when.
- Apply retention limits so personal data in logs is not kept forever without need.
Privacy law and logs
Under data protection laws such as the European GDPR, logs that contain personal data are themselves personal data. This means they need a lawful basis, protection, limited retention, and sometimes a way to respond to a person’s request. Security logging is generally accepted as a legitimate purpose, but it should be proportionate: record what you need for security and accountability, and not more. Discuss specifics with your privacy officer.
Application logs are the bigger risk
The most common source of leaks is not the audit log but application logs, where programs print request details, tokens, user data or error messages containing sensitive values. Developers should be guided to avoid logging secrets and personal data, and pipelines should detect and mask them. Scan logs periodically for patterns that look like credentials, and treat a found secret as a security incident: rotate it.
| Data | Safe approach |
|---|---|
| Secret objects | Metadata only |
| Service account tokens | Metadata only, and short-lived tokens |
| User identifiers | Keep for accountability; restrict access and retention |
| Custom resources with customer data | Metadata only, or Request level with masking |
| Workload definitions | Request level in sensitive namespaces; scan for embedded credentials |
| Application log content | Teach developers to avoid; mask in the pipeline |
A visitor book that also records visitors’ passwords would help a thief more than it helps the company. The skill in record-keeping is to write down enough to know what happened, and not so much that the record itself becomes treasure.
Turning on the most detailed audit level during an incident “to see everything” and forgetting to turn it back. Weeks later, the log holds secrets and personal data that nobody intended to store. Make any temporary change expire automatically.
14Beyond the API Server: Node, Runtime and Application Evidence
The audit log sees the front door. Much of what an attacker or an insider does happens inside, where the API server never looks.
The layers of evidence
| Layer | Examples of what it shows | How to collect |
|---|---|---|
| API audit log | Who created, changed or deleted objects; who opened a shell | Audit backend to central storage |
| Node operating system | Logins to the node, use of administrative commands, changes to files, kernel messages | System logging and the operating system’s audit facility, shipped by an agent |
| Kubelet and container runtime | Container starts and stops, image pulls, runtime errors | System journal collected from each node |
| Container activity | Processes launched, files touched, network connections made | Runtime security tools using kernel-level sensors |
| Network | Connections between workloads and to the outside | Flow logs from the cloud network, the network plugin or a service mesh |
| Application | Business events, such as a user viewing a record | Application logs, ideally structured and with user identity |
| Cloud account | Changes to machines, networks, storage, identity and keys | The cloud provider’s audit trail |
| Supply chain | Image builds, signatures, who pushed what to the registry | Registry and pipeline logs |
Why the node layer matters
Anyone who obtains access to a node, whether by logging in or by escaping from a container, can act outside the reach of the Kubernetes audit log. They may read other containers’ files, steal credentials or tamper with processes. Node-level logging and file integrity monitoring are the safety nets. Limit direct logins to nodes, and treat any login as an event to review.
Tying the evidence together
To follow an incident across layers, you need common keys: timestamps that agree, Pod and namespace names, node names, container identifiers, user names and source addresses. Enrich logs with Kubernetes metadata at collection time, such as labels, namespace and Pod name, so that an event on a node can be connected to the workload that caused it.
Application-level audit
Standards that care about data access, such as those for health and payment data, want to know who viewed or changed a specific customer record. The Kubernetes audit log cannot tell you that; only the application can. A mature program therefore asks application teams to produce their own audit events, with user identity, action and object, in a structured format that flows into the same pipeline.
The front-desk log shows who entered the building. Cameras in the corridors show where they walked, and the file clerk’s register shows which folders they opened. A thorough investigation of a missing document uses all three, joined by the time of day.
You do not need every layer on day one. Start with the API audit log and cloud audit trail, add node and runtime layers for sensitive environments, and extend to application audit for systems holding regulated data.
15Runtime Detection: Watching What Happens Inside Containers
Runtime security tools fill the gap that audit logs leave. They watch behavior inside running workloads.
What they see
Runtime tools use operating system features, such as kernel hooks, to observe system calls made by containers: starting programs, opening files, making network connections, changing permissions. They compare behavior against rules or learned baselines and emit events when something looks wrong.
Typical detections
Unexpected shell in a container
A production web server that suddenly runs a shell is rarely doing something good.
Sensitive file reads
A process reading credential files, service account tokens or system password files.
New programs written and run
Downloading and running a tool inside a container, which immutable images should never need.
Unusual outbound connections
Connections to unknown addresses, cryptocurrency mining pools or the cloud metadata service.
Escalation attempts
Changes to permissions, mounting of host directories or use of dangerous system calls.
Misuse of the API from inside
A container using its service account token to list secrets or create new Pods.
How they pair with the audit log
The two sources complement one another well. Imagine an attacker exploits a web application, opens a shell in the container, steals the Pod’s service account token and uses it to list secrets. The runtime tool shows the shell and the file read. The audit log shows the service account’s unusual list request from that Pod’s address. Together they give the full story and a clear timeline.
Operating a runtime tool well
- Start in observation mode, reviewing alerts for a few weeks to learn normal behavior and tune out false positives.
- Send events to the same central store as audit logs, with Kubernetes metadata attached.
- Write rules that fit your workloads. A rule that suits a web server may flood alerts on a build runner.
- Decide response in advance: alert only, isolate the Pod, or kill it, and who decides.
- Protect the tool itself, since attackers will try to disable it.
Performance and trade-offs
Kernel-level sensors add some overhead and need elevated privileges on nodes. Choose a mature tool, test it on representative workloads, and weigh its coverage against its cost.
If the audit log is the sign-in book, runtime detection is the guard walking the corridors, noticing that someone is trying a locked door at night, even though they signed in properly. Each catches what the other cannot.
Make containers read-only and remove shells from production images where possible. Then any shell or new binary becomes a very clear, high-confidence signal for your runtime tool.
16The Logging Pipeline: Collect, Ship, Store, Search, Alert
Records are only useful if they reach a safe place, in order, in full, and can be searched when it matters.
flowchart LR
subgraph SRC["Sources"]
A1["API server audit events"]
A2["Node and system logs"]
A3["Runtime security events"]
A4["Application logs"]
A5["Cloud audit trail"]
end
subgraph COL["Collect and enrich"]
C1["Agents on nodes and webhook receiver"]
C2["Add cluster, namespace and workload labels"]
C3["Mask secrets and sensitive patterns"]
end
subgraph TRN["Transport"]
T1["Buffered, encrypted delivery"]
end
subgraph STO["Storage"]
S1[("Hot: searchable, recent")]
S2[("Archive: immutable, long term")]
end
subgraph USE["Use"]
U1["Dashboards and search"]
U2["Detection rules and alerts"]
U3["Compliance reports and evidence"]
end
SRC --> COL --> TRN --> STO --> USE
Reading the diagram
Read it from left to right. On the left are the different sources. The next stage gathers events, labels them with the cluster, namespace and workload they came from, and masks anything sensitive. A transport layer carries them to storage, buffering when the destination is unavailable and encrypting data in transit. Storage has two tiers: a hot tier where recent events can be searched quickly, and an archive tier for long-term, protected retention. On the right, the data is used for dashboards, for detection and alerting and for compliance reports.
Design principles
- Get logs off the machine fast. The shorter the time an event lives only on a node, the smaller the window for loss or tampering.
- Buffer and retry. Networks fail. The pipeline should hold events and deliver them later, without gaps.
- Separate duties. The team that runs the cluster should not have unchecked power to delete the logs that record their own actions.
- Centralize across clusters, so one search covers the whole fleet, with fields identifying each cluster and environment.
- Structure the data. Keep audit events as structured records with consistent field names, so that searches and rules are reliable.
- Monitor the pipeline. Alert when events stop arriving, when delays grow, or when the API server reports dropped events. A silent log is as worrying as a noisy one.
Choosing storage
| Tier | Purpose | Typical retention | Characteristics |
|---|---|---|---|
| Hot | Daily search, alerts, investigation | Weeks to a few months | Fast, more costly, indexed |
| Warm | Occasional search of older data | A few months to a year | Slower, cheaper |
| Archive | Compliance retention, rare investigation | One to several years, set by rules | Cheapest, immutable, slow to query |
Heartbeat checks
Add a periodic, known test action, for example a harmless object created and deleted by an automated job, and verify that its audit events appear in the central store within a short time. This end-to-end test proves the whole pipeline works, and its failure triggers an alert long before anyone needs the logs in an emergency.
Think of the post office. Letters are collected from boxes, labeled, sorted, carried in sealed bags, stored in the right depot and delivered to the right desk. A test letter sent weekly shows the whole chain is working. A chain with one broken link looks fine until the day a letter matters.
Discovering during an audit that the log shipper stopped three months ago because of a full buffer or an expired certificate. Monitor the pipeline itself, and test end to end regularly.
17Integrity, Retention and Immutability
A log that can be quietly edited or deleted is worthless as evidence. The value of an audit trail rests on trust that nobody tampered with it.
Threats to the record
- An attacker covering tracks by deleting or editing entries after gaining access.
- An insider with administrator rights erasing evidence of their own actions.
- Accidents, such as a wrongly configured retention rule that removes data early.
- Loss through failure, such as a full disk or a deleted bucket.
- Clock errors that make the order of events uncertain.
Protection measures
Store in a separate account
Keep archives in an account or project that cluster administrators cannot reach, so they cannot delete their own trail.
Immutable storage
Use object storage features that prevent changes or deletion for a locked period, often called write-once-read-many.
Hashes and signatures
Create cryptographic checksums of log files or batches, and store them separately, so tampering can be detected.
Least privilege and review
Few people can read; fewer can administer; none can alter. Every access is itself logged.
In transit and at rest
Protect data on the wire and on disk, with keys managed outside the logging team’s day-to-day reach.
Reliable clocks
Synchronize all systems with trusted time sources and monitor for drift, so the order of events can be trusted.
Retention
Retention is how long you keep logs. It must satisfy the longest requirement among the rules that apply to you, but not exceed what privacy law and business need justify. A common structure keeps recent logs immediately searchable for several months and the full set archived for a year or more. Write the policy down, apply it with automated lifecycle rules and test that data is neither deleted early nor kept forever.
Legal hold
If an investigation or legal matter begins, normal deletion must pause for the relevant logs. Have a way to place a hold, and a person who can authorize it, before you need it.
Proving integrity to an auditor
Be ready to explain: where logs are stored, who can access them, what prevents alteration, how you would detect tampering, and how you know that no gaps exist. Evidence such as the storage lock configuration, access reports and the heartbeat test results turns these answers into proof.
A company’s financial ledger is kept in ink, in numbered pages, with copies stored at the bank. Corrections are made by adding a new line, never by erasing. The same attitude, applied to audit logs, makes them acceptable evidence.
Ask a colleague on another team to try to delete a day of archived logs using their normal permissions. If they can succeed, you have found the gap before an attacker or an auditor does.
18What to Watch For: Detection Use Cases
Collecting logs is only half the work. The other half is noticing the few events that matter among millions.
High-value detections from audit logs
| Behavior | What to look for | Why it matters |
|---|---|---|
| Privilege escalation | Creation or edit of roles and bindings granting administrator or wide powers; a user binding themselves to a stronger role | The classic step after gaining a foothold |
| Use of the administrator group | Any request from the all-powerful built-in group | Should be rare and always explained |
| Secret access | Reads or lists of Secrets by humans, or by accounts that normally do not read them | Credential theft |
| Shell into workloads | Exec or attach requests, especially in production namespaces | Hands-on access to running systems |
| Privileged Pods | Creation of Pods with host access, privileged mode or sensitive host paths | Route to taking over a node |
| Anonymous access | Any successful request by an unauthenticated caller | Misconfiguration or attack |
| Failed access bursts | Many 401 or 403 results from one identity or address in a short time | Guessing or exploring permissions |
| Weakening guardrails | Deleting or editing admission policies, webhooks, network policies or audit settings | Preparing for an attack, or covering tracks |
| Impersonation | Events with an impersonated user | Hidden actors |
| Token creation | New service account tokens or long-lived credentials | Persistence for an attacker |
| Unusual source | Administrative requests from new networks, unusual countries or from inside workload Pods | Stolen credentials |
| Unusual time | Sensitive changes outside working hours without a change ticket | Unauthorized or rushed changes |
| Mass deletion | Many delete requests in a short period | Sabotage or runaway automation |
| Namespace or cluster-level changes | Creation of new namespaces, custom resource definitions, or cluster roles | Structural changes that deserve review |
Good alerts are specific and actionable
- An alert should tell the responder who, what, where and why it matters, with a link to the full event.
- It should have an owner and a documented first response.
- Alerts that fire constantly and are ignored train people to ignore alerts. Tune or remove them.
- Combine signals. “Shell opened in a container” alone is a weak alert; “shell opened in a container, followed by a Secret listing from the same Pod’s address” is a strong one.
Tiers of response
High confidence, high impact
Use of the administrator group outside break-glass, anonymous success, weakened audit settings.
Needs review soon
New cluster-admin bindings, privileged Pods, exec in production without a ticket.
Trends and oddities
Denied-request patterns, new service accounts, unused powerful roles.
Baselines
Alerts are most precise when they know what is normal. Learn the usual activity of each system account and each team: which namespaces they touch, at what times, from which networks. Then deviations become obvious. Start with simple, high-value rules, and add baselining as your data grows.
A night guard does not react to every door opening. The guard knows the cleaners’ routine and responds to the unusual: a door opened at 3 a.m. in a room that is never used, or three failed attempts on the same lock. Good detection teaches the machine to know the routine as well as the guard does.
Test your detections. Perform each suspicious action deliberately in a test cluster, such as binding a user to cluster administrator, and confirm that the alert fires and reaches the right person. An untested alert is a hope.
19Investigating an Incident with Audit Logs
When an alert fires or someone reports a problem, a calm, structured search turns scattered events into a story.
The investigation flow
Anchor on a starting fact
An alert, a deleted object, a strange Pod, a suspicious address. Fix its time as the anchor of the search.
Identify the actor
Find the user or service account behind the event, including any impersonation and the source addresses.
Widen around the actor
List everything that identity did in the hours before and after: what it read, what it created, what it changed, what was denied.
Widen around the target
List every identity that touched the affected object or namespace in the same period, in case more than one actor is involved.
Follow the credentials
Find how the actor obtained access: a token, a certificate, a login. Look in the identity provider’s logs and in secret access events.
Cross-check other layers
Bring in node logs, runtime events, network flows and cloud audit trails for the same times and workloads.
Build the timeline
Order the events, mark what is proven and what is guessed, and note gaps in the data.
Contain and recover
Revoke credentials, remove persistence, restore changed objects, and verify that the actor has no remaining access.
Questions the audit log helps answer
- Which account created this suspicious Pod, and from which address?
- Did the same account read Secrets before creating it?
- Which role binding gave it permission to do so, and who created that binding?
- Were other namespaces touched?
- Did the actor try things that were denied before finding something that worked?
- When did the activity start, and is it still going on?
An illustrative chain
An investigator starts from a cryptocurrency-mining Pod found in a development namespace. The audit log shows it was created by a CI service account at 02:14 from an unfamiliar address. Earlier that night, the same account listed Secrets in three namespaces, and before that, a request from the same address used a stolen token to authenticate. The identity provider shows the token was created for a build job two weeks earlier. The fix: rotate the token, delete the Pod, tighten the CI account’s permissions, and add alerts for CI accounts making requests from outside the build network.
Preserve evidence
Before cleaning up, make copies of relevant logs and object definitions, note times and commands, and keep a record of every action you take. Cleaning up too soon can erase evidence that you need later. If legal action is possible, involve your legal and security response teams early and follow their handling rules.
Prepare before it happens
Write a playbook for common scenarios, practice it in an exercise, and have saved searches ready that retrieve an identity’s activity or an object’s history in seconds. During a real incident, nobody enjoys inventing queries.
A detective starts from the crime scene, finds the first clue, follows it to a suspect, then widens the search to everything the suspect did, everyone they met and how they got in. The audit log is the witness list and the timeline: reliable only if it was kept carefully and not tampered with.
Rebuilding a compromised cluster quickly and losing the evidence. Take snapshots and log copies first, even if it adds an hour. Without the story of how the attacker got in, the same door stays open.
20Admission Control and Policy as Compliance Evidence
Logs tell you what happened. Policies prevent bad things from happening at all, and their decisions are evidence too.
Preventive and detective controls
Auditors speak of two kinds of controls. Preventive controls stop a violation before it happens, such as a rule that blocks privileged containers. Detective controls notice a violation after the fact, such as an alert on a privileged container that slipped through. A strong program uses both, and audit logging is the backbone of the detective side.
Admission policy engines
Policy engines hook into admission and check each request against rules written by your security team: images must come from approved registries, containers must not run as the administrator user, every workload must have an owner label, namespaces must have resource quotas, and so on. Built-in policy features in newer Kubernetes versions offer similar checks without a separate service.
Policy decisions as evidence
| Evidence | What it proves |
|---|---|
| The policy documents in version control | That a rule exists, who approved it and when it changed |
| Audit events showing rejections | That the rule was enforced and violations were blocked |
| Policy engine reports on existing objects | That the current state of the cluster conforms, or lists exceptions |
| Exception records | That deviations were requested, approved and time-limited |
| Test results of policies | That the rules behave as intended before release |
Modes of enforcement
- Audit mode: the policy records violations but does not block. Useful when introducing a rule, to see its impact first.
- Warn mode: the user sees a message but the request proceeds.
- Enforce mode: violating requests are rejected.
The usual path is to start in audit mode, fix the findings, warn for a while, then enforce. Each mode produces its own evidence of progress.
Built-in pod security standards
Kubernetes includes standard security profiles for Pods, from permissive to restricted, which can be applied per namespace in audit, warn or enforce modes. Their audit-mode violations show up as annotations on audit events, making them a handy, low-cost compliance signal.
Protecting the guardrails
Because policies are only as good as their integrity, treat changes to them as sensitive. Restrict who may edit policy objects and webhook configurations, send every change to the audit log at Request level and alert on edits. Attackers frequently try to disable policy enforcement before acting.
A security gate that turns away people without badges is a preventive control. The camera that records who walked through the gate and the review of those recordings is a detective control. Auditors like to see both, and like to see that the gate’s settings cannot be quietly changed.
Policy engines add webhooks to the request path, so they inherit the reliability concerns of any webhook. Run them with several replicas and think carefully about their failure behavior, balancing security against availability.
21GitOps and Change Management as an Audit Trail
Where changes come through pull requests, the repository history tells the “why” that audit logs cannot.
Two views of the same change
The audit log says that a service account applied a change to a Deployment at 11:03. The Git history says that Priya proposed the change, Omar reviewed and approved it against ticket 4812, and the automation applied it. The first is a technical fact; the second is a business justification with approvals. Auditors want both, and a link between them.
How GitOps helps compliance
Every change is approved
Pull request rules require reviews, and branch protection prevents direct pushes.
Complete record
Version control keeps a permanent history of what changed, by whom, and why.
Cluster changes by automation
If only the GitOps controller may change the cluster, humans no longer need write access to it, and the audit log becomes simpler.
Detect unapproved changes
Differences between the repository and the cluster signal changes made outside the process.
Restore known states
Reverting a commit restores a previous, approved state.
Connecting the dots
- Have the automation add annotations to the objects it applies, such as the commit identifier and the pull request, so audit events and cluster objects point back to the source.
- Use a consistent identity for the automation, so its actions are easy to recognize and separate from human ones.
- Alert on changes made by humans in environments that should be changed only by automation. Those are either emergencies, which should be documented, or violations.
- Keep the repository protected: branch rules, required reviewers, signed commits where possible and tight access to the settings.
Emergency changes
Real life includes emergencies when someone must change the cluster directly. Allow it through the break-glass process described earlier, but demand that the change be recorded afterwards, brought back into the repository and reviewed. The audit log shows the direct change; the follow-up ticket shows the justification.
Segregation of duties
Many standards require that the person who writes a change is not the only person who approves and deploys it. Pull request approvals and separate deployment automation naturally create this separation, and the logs show that it was respected.
In a building project, the architect’s signed drawings (the repository) explain why a wall was moved, while the site diary (the audit log) records when the workers actually moved it. A walk-in inspector wants to see that the two agree.
Make the answer to “show me the approval for this production change” a one-click path from the audit event to the pull request. When the link is easy, audits become short.
22Secrets, Encryption and Key Management Evidence
Protecting sensitive data is a core part of most standards. Showing that you protect it requires evidence at several levels.
Where secrets live and what can leak
By default, Kubernetes Secrets are stored in etcd in an encoded but not encrypted form. Anyone who can read etcd or its backups, or who is allowed to read Secrets through the API, can see them. Several layers protect them:
- Access control: few identities may read Secrets, and every read is logged at Metadata level.
- Encryption at rest: the API server can encrypt Secrets, and optionally other resources, before writing them to etcd, using keys it holds or keys held by an external key management service.
- External secret stores: sensitive values live in a dedicated secrets manager, and the cluster fetches them when needed, so that long-lived copies are not stored in the cluster.
- Rotation: secrets and keys are replaced regularly, limiting the value of any stolen copy.
- Backups: etcd snapshots must be encrypted and access-controlled, because they hold everything.
Evidence to collect
| Control | Evidence an auditor can accept |
|---|---|
| Encryption at rest enabled | The API server’s encryption configuration, with the resource list and provider type, kept in reviewed configuration |
| Keys protected by a key management service | Key policies showing who can use and administer keys, and the logs of key use |
| Rotation performed | Records of key and secret rotation with dates, and the process followed |
| Limited read access to Secrets | Role definitions and review results; audit queries showing which identities have read Secrets lately |
| Backups encrypted and access-controlled | Storage settings, access lists and restore test records |
| Secrets not stored in source repositories | Scanner results for repositories and pipelines |
| Transport encryption inside and outside the cluster | Certificate configuration, mutual TLS settings, and ingress configurations |
Key use logs
When an external key management service is used, it keeps its own log of each use of a key: which identity asked to decrypt, when and why. These logs, combined with the Kubernetes audit log, show the whole story of a secret’s access: the API read request on one side and the key use on the other.
Audit questions to prepare for
- Who can read Secrets in production, and how do you know that list is complete?
- When was each important secret last rotated?
- If a developer’s laptop is stolen, what can the thief reach?
- Can you show every read of this secret in the last ninety days?
A safe-deposit room has three protections: who is allowed in (access control), a locked box inside the room (encryption), and a record of every key use (key logs). The bank can show an inspector all three, and replaces locks regularly (rotation).
Assuming that Secrets are encrypted by default. In many setups they are only base64 encoded, which is not protection at all. Check your configuration and prove, with evidence, that encryption at rest is truly on.
23Network and Data Access Evidence
Standards care about who can reach sensitive systems and data. Several records show whether network boundaries really exist.
Network policy as segmentation
By default, Pods in a cluster can talk to one another freely. Network policies restrict that, allowing only the connections that are needed. For standards that require separation of sensitive environments, such as payment data, network policies and the network plugin’s enforcement are primary controls. Evidence includes the policies in version control, test results proving that blocked paths are really blocked, and logs of denied connections where the plugin supports it.
Flow logs
Many network plugins, service meshes and cloud networks can record connections: source, destination, port, bytes, and often an allow or deny verdict. Flow logs answer questions such as “which workloads talked to the database last week?” and “did anything outside the payment namespace reach the payment service?” They can be voluminous, so sample or aggregate them where appropriate, and keep the sensitive segments in full.
Ingress and egress
| Direction | Controls | Evidence |
|---|---|---|
| Ingress from outside | Ingress controller rules, web application firewall, load balancer settings, authentication at the edge | Access logs from the ingress and load balancer, firewall logs, certificate records |
| Traffic inside the cluster | Network policies, mutual TLS, service mesh authorization | Policy definitions, mesh access logs, flow logs, test results |
| Egress to outside | Egress policies, gateways, firewall allow lists, DNS controls | Egress gateway logs, firewall and DNS logs |
| Access to the API server | Private endpoints, allowed source ranges, identity provider integration | Audit logs, endpoint configuration, network rules |
Data access evidence
For systems holding regulated data, the question “who looked at this record?” belongs to the application and database. Database audit features record queries, logins and changes. Combine them with the cluster evidence to show that only authorized workloads and people could reach the data store, and that every access was logged.
Access to nodes and the control plane
- Keep the API server endpoint private or limited to known address ranges, and record the configuration.
- Use bastion hosts or identity-aware proxies for administrator access to nodes, with session recording.
- Disable direct login to nodes where possible, and treat the exceptions as logged, approved events.
In a hospital, a records room has a locked door, a list of who may enter, and a camera on the corridor. Auditors check all three: the lock is the network policy, the list is the access control and the camera is the flow log. A door with no lock or a lock with no record would both raise questions.
Regularly run a harmless test that tries to connect from an unauthorized namespace to a protected service, and keep the result. A passing “blocked” test, repeated monthly, is lovely evidence that your segmentation holds.
24Mapping Controls to Evidence
Auditors do not ask for logs for their own sake. They ask whether a control works and want evidence. A mapping from controls to evidence makes audits predictable.
A sample map
| Control objective | How the cluster meets it | Evidence to show |
|---|---|---|
| Individual accountability | Identity provider login, no shared accounts | Authentication configuration; audit events with personal usernames; list of service accounts and owners |
| Least privilege | Narrow roles, regular reviews | Role definitions, quarterly review records, comparison of granted and used permissions |
| Change management | GitOps with reviewed pull requests | Repository settings, sample change with approval and linked audit event |
| Logging of access and changes | API audit policy, node and application logs | Policy file, sample events, pipeline architecture, heartbeat test |
| Protection of logs | Immutable, separate storage | Lock configuration, access lists, integrity checks |
| Log retention | Lifecycle rules matching requirements | Retention policy, lifecycle configuration, proof that old logs exist |
| Log review and monitoring | Detection rules, alerts, regular review | Alert definitions, sample incident tickets, review sign-offs |
| Incident response | Playbooks and exercises | Playbooks, exercise reports, a real incident timeline |
| Vulnerability and configuration management | Scanners, benchmarks, policy engine reports | Scan results, remediation tickets, policy reports |
| Encryption of sensitive data | Encryption at rest and in transit; key management | Encryption configuration, key policies, certificate inventory |
| Network segmentation | Network policies, private endpoints | Policies, test results, flow logs |
| Time synchronization | Trusted time sources on all nodes | Configuration and drift monitoring |
| Access termination | Directory-driven group membership | Offboarding records and proof that access ended |
How to use the map
- Keep it as a living document in version control, owned by a named person.
- For each row, link to the real artifacts, such as the saved query that produces a report, the dashboard, the policy file.
- Where possible, generate evidence automatically on a schedule so that it is always fresh.
- Mark gaps honestly, with a plan and a date. Auditors respect known and managed gaps far more than hidden ones.
Benchmarks and scanners
Tools that check a cluster against the CIS Kubernetes Benchmark or similar standards produce reports that map neatly to many controls. Run them on a schedule, track failures to resolution and keep the reports as evidence of continuous checking.
Before a home inspection, a careful owner prepares a folder: the warranty for the roof, the receipt for the new boiler, the electrician’s certificate. The inspector then finds each claim backed by a paper. The mapping table is that folder for your cluster.
25Preparing for an Audit and Staying Ready
Audit stress comes from scrambling. Teams that treat compliance as a daily habit find audits a routine event.
Continuous compliance
Instead of collecting evidence once a year, build automation that checks controls all the time and records the results. Examples: a nightly job that verifies the audit policy matches the approved version, a weekly report of new administrator bindings, a monthly test that archives are immutable, and a dashboard showing the pipeline’s health. When the auditor arrives, the evidence already exists.
The audit calendar
Months before
Confirm scope with the auditor, and run your own readiness check using the evidence map. Fix gaps found.
Weeks before
Collect samples of logs, reports, tickets and approvals. Prepare short explanations of architecture and processes. Brief the people who will be interviewed.
During
Provide evidence promptly, answer honestly, record every request and keep one point of contact so that nothing gets lost.
After
Review findings, plan fixes with owners and dates, and update processes so that the same finding does not return.
What auditors commonly ask for
- A list of users and service accounts with access, and the justification for privileged ones.
- Samples of audit events for specific actions chosen by the auditor, such as “show me who changed this role last March.”
- Proof that logs are retained for the required time, and cannot be altered.
- Evidence of regular log review, with examples of alerts and what was done about them.
- Change records with approvals, and their link to what was deployed.
- Records of access reviews and of removal of departed staff.
- Results of incident exercises.
Be able to answer from the logs quickly
Prepare saved queries for common requests: all actions by a named user between two dates, all changes to roles and bindings in a year, all Secret reads in production, all use of break-glass accounts. Test that they run fast against the archive as well as the hot store. Pulling a year of data from cold storage can take hours; know this ahead of time.
Culture
The best audit posture is an honest one. Teams that explain their controls clearly, show their evidence and admit gaps with a plan build trust. Teams that hide problems or invent stories lose it. Encourage engineers to see auditors as colleagues who test the system from another angle.
Students who study a little every day are calm on exam day, while those who cram the night before are not. Continuous compliance is daily study; the audit is the exam that you already know you can pass.
Run a mock audit once a year with someone from outside the team who plays the auditor. Their questions expose unclear evidence much more cheaply than a real audit would.
26Many Clusters, Many Teams: Multi-Tenancy and Fleet Logging
The picture gets more complex when clusters are shared by several teams, or when there are many clusters across environments and regions.
Multi-tenant clusters
When several teams share a cluster, the audit log shows all of their actions mixed together. Each team should see its own events, but not others’. A good setup tags events with the namespace and team, filters access by those tags and gives platform administrators the full view. Tenants should be unable to see audit data about other tenants, which may reveal names and activity.
Multi-cluster logging
Label every event
Cluster name, environment, region and owner must be attached to every event at collection time.
One policy baseline
Use a common audit policy for all clusters, with reviewed per-cluster additions, so that evidence is consistent.
One place to search
A central store means an investigation can follow an actor across clusters in a single query.
Respect data location
Some laws require that logs stay in a region. Use regional stores with a federated view when needed.
Different depth by risk
Production and regulated clusters get full pipelines and long retention; sandboxes get lighter treatment.
Ownership
Clarify who owns what: a platform team owns the audit policy, the pipeline and the archive; security owns detection rules and investigation; application teams own application audit events and respond to alerts about their workloads; compliance owns the mapping and the audit relationship. Write this down. Gaps in ownership are where logs quietly break.
Consistency pays off
Fifty clusters each with a different logging setup are fifty separate audit problems. Provision clusters from a common template, which bakes in audit settings, shipping and retention, so that a new cluster is compliant on day one. Then verify with automated checks that no cluster has drifted.
Separate accounts and environments
Keep logs for production in an environment that development staff cannot administer. Many organizations send all security logs to a dedicated, locked-down account owned by the security team, which is read-only for everyone else.
A company with many branches uses one standard way to record visitors, sends the records to head office each night, and keeps them in a vault where branch managers cannot change them. A manager who needs to see their own branch’s records can, but cannot see the others, and certainly cannot edit any.
The more clusters you have, the more important automation becomes. A human cannot reliably check fifty clusters by hand, but a nightly job can compare every cluster’s audit configuration with the approved baseline and report differences.
27Volume, Performance and Cost
Audit logging is not free. A busy cluster can produce gigabytes per day, and the cost shows up in performance, storage and licensing.
Where the volume comes from
Most events are generated by machines, not people. Controllers, kubelets, schedulers and operators make a constant stream of reads, watches and status updates. A cluster with a thousand nodes may generate millions of events per hour. If the policy records all of them at a detailed level, the log becomes unmanageable and the signal drowns in noise.
What drives the size
| Factor | Effect on volume | Control |
|---|---|---|
| Cluster size and activity | More nodes and Pods mean more requests | Filter system accounts in the policy |
| Audit level | Request and RequestResponse bodies are far larger than Metadata | Use bodies only for important changes |
| Stages recorded | Extra stages multiply events | Omit RequestReceived |
| Managed fields in bodies | Adds bulk with no evidence value | Omit managed fields |
| Read requests | Reads are very frequent | Exclude routine reads by system users; keep reads of sensitive objects |
| Custom controllers and operators | Some are very chatty | Find the top talkers and decide whether to exclude them |
| Retention length and tiers | Storage cost grows with time | Archive in cheap storage with lifecycle rules |
| Index richness | Indexing every field in a search platform is expensive | Index only fields used for search |
Impact on the API server
Audit logging uses CPU and memory in the API server, especially when request and response bodies are recorded or when batching is poorly sized. A blocking backend adds delay to every request. In large clusters, measure API server latency before and after turning on a new policy, and watch the server’s audit metrics for dropped or delayed events.
Controlling cost without losing value
- Spend detail where risk is: sensitive namespaces, privilege changes, access control objects.
- Spend little where risk is low: routine machine chatter.
- Pre-aggregate high-volume signals before storing them, for instance counts per user per hour, while keeping raw events for sensitive classes.
- Compress and move older data to cheap storage after the search period passes.
- Review the top ten talkers monthly and keep trimming.
Do not save money by dropping the wrong things
The temptation to cut costs by shortening retention or excluding categories is strong. Always check with compliance first, and never exclude events that would be needed to reconstruct a security incident or to answer a standard audit question. Savings that cost you an audit finding are not savings.
Estimating before you build
Measure the event rate for a day in a representative cluster with the proposed policy, then multiply by retention. Include the extra copies created by replication and by archives. This estimate guards against sticker shock when the first bill arrives.
A shop with security cameras everywhere can fill a warehouse with video that nobody watches. Wise owners point high-quality cameras at the cash desk and the stockroom, use low-quality ones for the car park, and keep footage for a sensible period. The same trade-off applies to logs.
Put a monthly “cost per gigabyte and per source” chart on the team dashboard. Costs that nobody can see tend to grow until someone panics.
28Failure Modes: How Audit Logging Quietly Breaks
Audit logging fails silently. Nothing crashes; the records simply stop being complete. Knowing the typical failures lets you test for them.
| Failure | How it happens | How to detect or prevent |
|---|---|---|
| Logging was never turned on | The default is off on some self-managed setups | Configuration checks and benchmark scans; verify with a test event |
| The policy has a gap | No catch-all rule, or a general rule placed above specific ones | Review the order; run tests of each kind of request |
| Events dropped under load | Backend buffer too small, receiver slow | Alert on the API server’s dropped-event metric; size buffers |
| Shipper stopped | Expired certificate, full disk, crashed agent, changed credentials | Heartbeat test events; alert on silence |
| Control plane node replaced | New machine without the shipper or the policy file | Build both into node images and automation; verify after replacement |
| Log files rotated before shipping | Rotation settings too aggressive | Match rotation to shipper behavior; monitor lag |
| Wrong or drifting clocks | Time sources fail on some machines | Monitor clock offset; use trusted sources |
| Parsing failures in the pipeline | A new version changes field names or formats | Test pipelines on upgrade; alert on parse errors |
| Retention rule too short or deleted | Misconfigured lifecycle, cost cutting | Review settings regularly; protect with locks |
| Access too broad | Everyone can read or alter logs | Access reviews; separate accounts; immutability |
| Managed service setting changed | Someone switches off control plane logging to save money | Alert on changes to logging configuration through the cloud audit trail |
| Alert fatigue | Too many low-value alerts | Tune; tier; retire noisy rules |
| Detection rules stale | New resource types or behaviors are not covered | Review rules each quarter and after upgrades |
Test, do not assume
Because failures are quiet, build tests that prove the system works. A scheduled job performs a known action, such as creating and deleting an object with a distinctive name, and checks that the corresponding audit events arrive in central storage within a time limit. Another job compares each cluster’s audit configuration with the approved baseline. A third attempts a harmless forbidden action and verifies that the denial is recorded.
Upgrades and audit logging
Kubernetes upgrades can change audit event formats, add new fields, add or rename resources and change defaults. After each upgrade, run the end-to-end tests, review a sample of events and confirm that detection rules still match. Add this to the upgrade checklist.
The dangerous gap
The worst failure is the one noticed only when needed: an incident occurs and the logs for the critical hours do not exist. If you cannot afford that, invest in monitoring the monitoring system.
Smoke detectors quietly lose their batteries. A sensible household presses the test button on a schedule instead of trusting the silence. A silent audit log has the same property: silence might mean peace, or it might mean the detector is dead.
Believing that “we have a logging platform” means “we have audit logs.” The platform can be perfectly healthy while the API server sends it nothing. Always test from the source, not from the destination.
29Privacy, Employee Monitoring and Ethics of Logging
An audit log records the behavior of real people. That brings legal duties and ethical questions that responsible teams think about openly.
Purpose limitation
Records of people’s activity should be used for the stated purposes: security, accountability, compliance and operations. They should not become a general tool to watch employees’ productivity or personal behavior. State the purposes in policy, tell staff that logging occurs and what it is used for, and restrict access to those who need it.
Principles in practice
- Transparency: staff know that administrative actions are logged, and why.
- Minimization: collect what is needed. Do not capture the contents of personal communications or unrelated data.
- Access control: reading logs about people is itself sensitive and should require a reason and be recorded.
- Retention limits: keep identifiable logs only as long as required.
- Proportionate investigation: investigations of individuals follow a defined process, with approval from HR or legal where appropriate.
- Fairness: logs show actions, not intentions. A single event should not be taken as proof of bad faith without context.
Regional rules
Laws differ by country. Some regions give employees rights about how their data is handled, require consultation with worker representatives before monitoring systems are introduced, or restrict moving personal data across borders. Customer data inside application logs adds further obligations. Involve your privacy officer, and design to the strictest rules that apply to you.
Protecting people from log misuse
| Risk | Safeguard |
|---|---|
| Curious administrators browsing logs about colleagues | Role-based access, logging of log access, periodic review |
| Logs used for unrelated performance management | Written policy on permitted uses |
| Over-collection of personal data | Policy review, masking, short retention for identifiable fields |
| Disclosure to third parties | Contracts, access controls, encryption, region controls for log vendors |
| Misreading context | Investigation process requiring corroboration and a chance to explain |
Service providers
If logs are stored with a third-party service, treat that provider as a data processor. Check where data is held, who at the provider can access it, how it is secured, and what happens at contract end. The convenience of a hosted logging service does not remove your accountability.
A workplace may record who enters the server room, and staff understand why. But a manager reading the entry log to find out who takes long lunches would be misusing it. Clear rules about purpose keep the log trusted and keep it from becoming a source of resentment.
I am not a lawyer, and obligations differ widely by region and sector. Treat this chapter as a prompt for conversations with your privacy and legal teams, not as legal advice.
30A Worked Story: A Payments Startup Meets Its First Audit
This is an illustrative story, not a report about a real company. It shows how the ideas in this guide combine over a year.
The situation
“Paylark,” a fictional payments startup with a team of thirty engineers, ran its services on a managed Kubernetes cluster. A large customer demanded a security audit within six months. The platform lead, Dana, opened the cluster’s settings and found that control plane audit logs were not delivered anywhere, three engineers shared one administrator credential, and nobody had ever reviewed who had access to Secrets.
Month one: get visibility
Dana first switched on control plane audit log delivery, and sent it to a separate security account. She exported cloud account audit trails to the same place. She did not yet write alerts; she simply wanted the data to start flowing, since logs cannot be collected backwards in time. A heartbeat job was created to prove events were arriving.
Month two: identity
The team connected the cluster to the company’s identity provider. Every engineer now logged in with a personal, short-lived credential and multi-factor authentication. The shared administrator credential was locked away as a break-glass secret, with an alert on any use. CI pipelines received their own service accounts with narrow roles. Immediately, the audit log began showing individual names, and the volume of unexplained “admin” activity vanished.
Month three: reduce noise, protect secrets
The first week of data was overwhelming: millions of events from system components. Dana studied the top talkers and shaped a policy that dropped routine machine chatter, recorded Secrets and tokens at Metadata level only, and captured changes to roles, bindings, policies and workloads in production at Request level. Volume fell by about eighty percent, and the log finally became readable. A review of Secret reads revealed that a monitoring tool had been listing all Secrets every minute, which was replaced with a narrower permission.
Month four: detect
The team wrote a short list of alerts: use of the administrator group, new bindings to wide roles, exec into production Pods, privileged Pod creation, anonymous success and any change to audit or policy settings. They tested each one in a staging cluster. In the first week, exec alerts fired on a developer debugging production at night. This led to a conversation, a clearer on-call process and a request-and-approve mechanism for production access.
Month five: evidence and review
Paylark built an evidence map, stored in version control, linking each control to its proof. Quarterly access reviews compared roles with actual use from the logs, and removed a dozen unused permissions. Archives moved into immutable storage with a one-year lock, and a legal hold procedure was written. A mock audit by an outside consultant found two gaps: no record of an exercise of the incident playbook, and unclear ownership of application audit events. Both were fixed.
Month six: the audit
The auditor asked for the list of people with access to production Secrets, samples of audit events for chosen role changes and proof that logs could not be altered. Each request was answered within an hour, using saved queries and the evidence map. The auditor noted one finding, a missing review of node-level logs, which the team added to its roadmap. The customer deal went ahead.
The aftermath
Three months later, the alerts caught a real problem: a CI token leaked in a public repository was used to list Secrets from an unfamiliar address. The audit log gave the team the exact timeline within minutes, and they rotated the token and confirmed that nothing else had been touched.
Lessons from the story
- The first step was simply to turn the logs on, because past events cannot be recovered.
- Personal identities made the logs meaningful; shared accounts would have made them useless.
- Shaping the policy turned noise into signal, and protecting Secrets at Metadata level avoided a new risk.
- A short list of tested alerts was worth more than a long list of untested ones.
- The evidence map and saved queries made the audit short and calm.
31Anti-Patterns in Compliance and Audit Logging
These common mistakes recur in many organizations. Recognizing them is the first step toward avoiding them.
Logging turned off or never checked
The team assumes that the platform records everything. Instead: verify with a test event, and monitor from the source.
Shared administrator accounts
The log says “admin” for every action. Instead: personal identities through a central provider, and a sealed break-glass account.
Logging everything at the highest level
Secrets and personal data end up in the log, and performance suffers. Instead: Metadata by default, bodies only where needed, and never for secrets.
Logs stored where administrators can delete them
The people being audited control the evidence. Instead: a separate, immutable store with restricted access.
Collecting but never reviewing
Terabytes of logs and no alerts, no review. Instead: a short list of tested detections and a regular review with named owners.
Only the API server is logged
Nothing is known about nodes, containers or applications. Instead: add layers in proportion to the sensitivity of the environment.
Untested alerts and pipelines
The first real incident shows that nothing fires. Instead: test detections deliberately and run end-to-end heartbeat checks.
Retention chosen by accident
Defaults of a few days or weeks are kept because nobody changed them. Instead: set retention from requirements and apply it with automated rules.
Scrambling for evidence before each audit
Screenshots and manual exports a week before the auditor arrives. Instead: continuous, automated evidence and a living map of controls.
Ignoring the cloud layer
Someone weakens a firewall or key policy with no trace in the cluster logs. Instead: collect and review the cloud audit trail alongside the cluster’s.
Compliance as paperwork only
Policies on paper that nobody follows in practice. Instead: controls that are enforced by the platform, and evidence that comes from real activity.
No ownership
Everyone assumes that someone else maintains the pipeline. Instead: named owners for the policy, the pipeline, the detections and the evidence.
32A Maturity Roadmap
You do not need everything at once. This staged path shows how to grow from nothing to a confident, continuous program.
flowchart LR S0["Stage 0: Blind - no audit logs"] --> S1["Stage 1: Collecting - audit logs on and shipped off the cluster"] S1 --> S2["Stage 2: Accountable - personal identities and a shaped policy"] S2 --> S3["Stage 3: Protected - immutable storage, retention, access control"] S3 --> S4["Stage 4: Watching - tested detections and review"] S4 --> S5["Stage 5: Continuous - automated evidence and fleet-wide consistency"]
Reading the diagram
Each box is a stage that builds on the one before it. The path begins in the dark, with no audit logs at all, and moves first to simply collecting them, then to making them meaningful with real identities and a sensible policy, then to protecting them, then to using them actively and finally to producing evidence continuously across every cluster.
What each stage looks like
| Stage | Key characteristics | Next step |
|---|---|---|
| 0. Blind | No audit logs, or logs only on the machine, and shared accounts | Switch on audit logging, ship events off the cluster, and prove it with a test event |
| 1. Collecting | Events arrive centrally, but are noisy and attributed to shared users | Adopt personal identities and shape the policy |
| 2. Accountable | Actions tied to people and services; Secrets protected at Metadata level; volume manageable | Protect the logs and set retention |
| 3. Protected | Immutable archives, separate account, reviewed access, reliable clocks | Build detections and a review habit |
| 4. Watching | Tested alerts, runtime and cloud layers, investigation playbooks, access reviews | Automate evidence and standardize across clusters |
| 5. Continuous | Automated control checks, evidence map, mock audits, fleet-wide baselines | Keep improving; expand to application audit |
Questions to place yourself
- If someone deleted a namespace yesterday, could we tell who, within ten minutes?
- Could any administrator delete the evidence of their own actions?
- How long do we keep audit logs, and why that long?
- Which detections have we actually tested?
- How would we know if our log shipping stopped today?
- When did we last perform an access review?
Stages 0 and 1 are urgent, since logs cannot be collected after the fact. If you do nothing else this week, turn on audit logging and get the events somewhere safe.
33Frequently Asked Questions
Short answers to questions that come up again and again.
Is audit logging on by default in Kubernetes?
Not in many self-managed setups. Managed services vary: some record control plane activity by default into the provider’s logging service, others require you to enable delivery. Always check and test.
Do audit logs show what someone typed inside a container?
No. They show that a shell was opened, by whom and from where, but not the commands. For that you need runtime security tools, session recording or application-level logging.
Which audit level should I use?
Metadata for most things, Request or RequestResponse for important configuration and access-control changes, None for noise, and Metadata only for Secrets and anything that may hold credentials.
Why not log every request in full?
It creates enormous volume, slows the API server and copies secrets and personal data into your logs. A focused policy gives better evidence at lower cost and lower risk.
How long should I keep logs?
As long as the strictest requirement that applies to you demands, commonly a year or more for security logs, with the most recent period searchable. Do not keep identifiable data longer than needed. Confirm with compliance and privacy teams.
Can I change the audit policy on a managed service?
Usually only in limited ways. The provider sets the policy; you control delivery, retention, filtering in your own pipeline and alerting. Read the provider’s documentation to learn what is recorded.
How do I prove logs have not been tampered with?
Store them in a separate account with write-once storage, restrict access, keep integrity checksums outside the cluster, monitor for gaps and keep clocks accurate. Document these controls and keep the evidence.
What is the first alert I should create?
Any use of the built-in all-powerful administrator group, and any change to the audit and policy configuration. These are rare, high-impact and easy to explain.
Are Kubernetes events a substitute for audit logs?
No. Events are short-lived operational notes, not records of who did what. Use audit logs for accountability.
How do audit logs relate to GitOps?
The audit log shows what was applied and by which identity; the Git history shows who approved it and why. Together they cover both the technical fact and the business justification.
Do I need a SIEM?
You need a place to search, alert and report across sources. That can be a dedicated security platform or a general logging stack with detection rules. What matters is that it supports reliable collection, protected storage, search and alerting for your size and requirements.
What about audit logs and personal data?
Usernames and addresses in logs are personal data under many laws. Keep them for legitimate security purposes, limit access, set retention, avoid capturing unneeded personal content, and involve your privacy officer.
How can a small team start without being overwhelmed?
Turn on audit logging and ship it to a safe place. Move to personal identities. Use a published example policy and tweak it. Add five tested alerts. Do an access review each quarter. That alone puts you ahead of most clusters.
34Key Takeaways and Next Steps
You have walked from the first idea of a diary for the cluster to a full, continuous compliance program. Here it is in a nutshell.
What to remember
- An audit log answers who, what, when, from where and whether it was allowed. It cannot be recreated after the fact, so turn it on early.
- The API server writes audit events for every request it receives, including denied ones. They are independent of what the caller wants to record.
- The audit policy decides what to record. Rules are checked in order and the first match wins, so put specific rules first and finish with a catch-all.
- Use Metadata level for most things, bodies only where the exact change matters, and never record the contents of Secrets or tokens.
- Meaningful logs need real identities: personal credentials from a central provider, separate service accounts, controlled impersonation and a sealed break-glass account.
- Audit logs see the API front door. Combine them with node, runtime, network, application, cloud and supply chain evidence.
- Ship events off the control plane quickly, enrich them, store them in separate, immutable locations, and monitor the pipeline itself.
- Protect integrity with separation of duties, write-once storage, checksums, access control and reliable clocks.
- Turn logs into action with a short list of specific, tested detections and clear response steps.
- Use logs to right-size permissions through regular access reviews.
- Show auditors a map from controls to evidence, produced as continuously and automatically as possible.
- Respect privacy: collect what is needed, limit access and retention, and state the purposes openly.
- Test everything. Audit logging fails silently, so prove it works from the source to the report.
Your first month
Week one: switch on and ship
Enable audit logging or its delivery, send events to a separate, protected location, and run a heartbeat test. Collect the cloud audit trail too.
Week two: fix identity
Retire shared credentials, connect to your identity provider, give each automation its own service account and seal the break-glass access.
Week three: shape the policy
Study the top talkers, silence noise, protect Secrets at Metadata level and capture sensitive changes in detail.
Week four: protect and watch
Set retention and immutability, restrict access, build five tested alerts and write the first version of your evidence map.
Kubernetes, cloud provider features and compliance standards change over time. The principles in this guide, record the right things, attribute them to real identities, protect the records, watch them and prove it, remain stable. Always confirm details such as audit options, provider behavior and retention requirements against current official documentation and with your compliance team.