Audit
Audit performs periodic evaluations of existing resources against constraints, detecting pre-existing misconfigurations.
Triggering an Audit
On-demand audit is an alpha feature, disabled by default. Enable it on the audit process with
--enable-audit-trigger=true (Helm: enableAuditTrigger: true) and install the AuditTrigger CRD
and its RBAC permissions. Only set this flag or Helm value with an image that supports it.
The chart and standard manifests include the CRD; its presence alone
does not enable the feature. Static manifests include trigger permissions; Helm grants the explicit
trigger permissions only when enabled.
With the feature disabled, Gatekeeper does not register the trigger controller or read or write trigger status, and periodic audits do not depend on the trigger CRD. If the CRD is installed, requests can still be created but are not acknowledged or processed while disabled. Requests left pending are processed when the feature is enabled.
With the feature disabled, periodic audits via API discovery support scoped read permissions. If a group's resources cannot be discovered or the first LIST of a resource kind is forbidden, Gatekeeper logs the error and publishes results for the kinds it could audit. If a Namespace GET is forbidden, Gatekeeper skips objects whose namespace it could not read. Status and violation totals cover only the readable scope: for example, a wildcard constraint may report zero even if an unreadable object violates it. If no eligible kind could be audited, a Namespace denial prevented every object review, or another scan operation fails (for example, fetching a later page or a policy review returning an error), the previous statuses and violation totals are retained.
Once enabled, an audit can be requested before the next configured audit interval by creating an AuditTrigger.
Change spec.auditNonce to a fresh random UUID to request an audit as soon as possible.
The nonce is only a change token: it is not an audit ID or a scheduling instruction.
apiVersion: audit.gatekeeper.sh/v1alpha1
kind: AuditTrigger
metadata:
name: audit-trigger
spec:
auditNonce: "c13ca135-c7bd-4ee4-94aa-9334505ad847"
audit-trigger is a singleton; other resource names are rejected. Save the metadata.uid and
metadata.generation from the successful write response. Reapplying an unchanged nonce does not
request another audit. When updating a full object, use metadata.resourceVersion and retry conflicts.
For the generation G returned by your write, evaluate status in this order:
- If the UID changed, the singleton was recreated; submit a new request.
- If
status.successfulGeneration >= G, the request is satisfied. - If
status.failedGeneration >= G, a covering audit failed; change the nonce to retry. - Otherwise, wait.
status.acknowledgedGeneration >= Gmeans Gatekeeper accepted the request.
Missing generation watermarks mean zero. Watermarks never decrease within the same object's lifetime.
A later failure does not invalidate an earlier success. status.lastRun describes the most recently
reported execution, regardless of what triggered it; clients use the generation watermarks to track requests.
Run a single audit replica. lastRun is intended as a best-effort diagnostic rather than a contract the
client can rely on: during rollout or restart overlap, lastRun may be overwritten out of order. Generation watermarks are guaranteed monotonic,
hence the intended client behavior being to use those instead.
Constraint-status writes reject audit timestamps older than the stored timestamp, and rejected publication fails the audit rather than reporting success. This check does not guarantee execution ordering across pods with different clocks.
Success includes completion of constraint-status writes, but does not mean that no violations were found or that an external consumer uploaded the results.
Trigger readers need not have access to every audited namespace. On failure, lastRun.message
contains a reference instead of resource names or underlying errors. An operator can search
the audit pod logs for that reference to see the cause.
With the feature enabled, discovery, resource listing, disk spooling, and errors returned by policy review fail both scheduled and on-demand audits, even without a pending trigger request. An incomplete scan does not publish new constraint statuses or violation totals; the previous results are retained. Constraint-status writes are not atomic across constraints: a failure while writing a complete scan's results can leave some constraints updated, but does not advance the successful generation. A missing required ConstraintTemplate CRD also fails the audit. An absent constraint API is treated as an empty audit. Timing metrics and audit-finished logs/export messages mark the end of an attempt, including failed attempts; use the trigger's generation watermarks to determine success. Waiting for initial ingestion is not an audit attempt: these retries do not update run timing metrics, write an export, or evict an earlier export. A completed audit with no findings still does. Error collection retains at most ten diagnostic messages of up to 256 bytes each, plus an omission marker. Complete per-resource errors are logged rather than retained in the audit result.
Multiple requests observed before an audit starts are coalesced into that audit. A request received
during an audit requires a subsequent run; it is not silently skipped. A periodic audit can satisfy
an already-observed request. Following a restart, requests without durable completion are rerun,
so execution is at-least-once, not exactly-once. If constraints exist and the restarted audit
process is still ingesting its initial policy or synced data, a pending request keeps its
generation and retries automatically. No new nonce is needed. This uses Gatekeeper's
startup readiness expectations; it is not a guarantee that subsequent
policy or resource updates have reached every cache when an audit starts.
Cache-based audits (--audit-from-cache=true) wait for policy and synced data, but do not
wait for expansion templates or mutators: they evaluate cached objects without expanding them.
Discovery-based audits still wait for those inputs when resource expansion is enabled.
This does not relax the pod's overall readiness check.
A successful on-demand scan resets the periodic audit schedule even if its completion status
cannot yet be persisted, so another audit will still start within the configured
--audit-interval. Setting --audit-interval=0 disables periodic audits; with the trigger feature
enabled, audits can still be requested with an AuditTrigger. With both the feature disabled and
the interval set to zero, auditing is fully disabled.
If a completion cannot be persisted, Gatekeeper retains the highest successful and failed generations in memory and retries without blocking periodic scans. Failed periodic scans wait for the next configured interval; they do not schedule fast scan retries. Completion-status persistence failures from periodic runs use the same bookkeeping retry backoff as on-demand runs, without repeating the scan unless a new request needs one.
Reading Audit Results
There are three ways to gather audit results, depending on the level of detail needed.
Prometheus Metrics
Prometheus metrics provide an aggregated look at the number of audit violations:
gatekeeper_audit_last_run_timeprovides the start time timestamp of the most recent audit rungatekeeper_audit_last_run_end_timeprovides the end time timestamp of the last completed audit rungatekeeper_violationsprovides the total number of audited violations for the last audit run, broken down by violation severity
Constraint Status
Violations of constraints are listed in the status field of the corresponding constraint.
Note that only violations from the most recent audit run are reported. Also note that there
is a maximum number of individual violations that will be reported on the constraint
itself. If the number of current violations is greater than this cap, the excess violations
will not be reported (though they will still be included in the totalViolations count).
This is because Kubernetes has a cap on how large individual API objects can grow, which makes
unbounded growth a bad idea. This limit can be configured via the --constraint-violations-limit flag.
Here is an example of a constraint with violations:
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
name: ns-must-have-gk
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["Namespace"]
parameters:
labels: ["gatekeeper"]
status:
auditTimestamp: "2019-05-11T01:46:13Z"
enforced: true
violations:
- enforcementAction: deny
group: ""
version: v1
kind: Namespace
message: 'you must provide labels: {"gatekeeper"}'
name: default
- enforcementAction: deny
group: ""
version: v1
kind: Namespace
message: 'you must provide labels: {"gatekeeper"}'
name: gatekeeper-system
- enforcementAction: deny
group: ""
version: v1
kind: Namespace
message: 'you must provide labels: {"gatekeeper"}'
name: kube-public
- enforcementAction: deny
group: ""
version: v1
kind: Namespace
message: 'you must provide labels: {"gatekeeper"}'
name: kube-system
Limitations of getting violations from constraint status:
- To reduce in-memory consumption of Gatekeeper audit pod and to avoid hitting default etcd limit of 1.5MB per resource, gatekeeper recommends configuring a limit up-to 500 violations(by default 20) on constraint. Because of these limitations, users might not get all the violations from a Constraint resource.
Audit Logs
Violations
The audit pod emits JSON-formatted audit logs to stdout. The following is an example audit event:
{
"level": "info",
"ts": 1632889070.3075402,
"logger": "controller",
"msg": "container <kube-scheduler> has no resource limits",
"process": "audit",
"audit_id": "2021-09-29T04:17:47Z",
"event_type": "violation_audited",
"constraint_group": "constraints.gatekeeper.sh",
"constraint_api_version": "v1beta1",
"constraint_kind": "K8sContainerLimits",
"constraint_name": "container-must-have-limits",
"constraint_namespace": "",
"constraint_action": "deny",
"constraint_enforcement_actions": [],
"constraint_annotations": {
"test-annotation-1": "annotation_1"
},
"resource_group": "",
"resource_api_version": "v1",
"resource_kind": "Pod",
"resource_namespace": "kube-system",
"resource_name": "kube-scheduler-kind-control-plane"
"resource_labels": {
"env": "prod",
"my-app-system": "true"
}
}
In addition to information on the violated constraint, violating resource, and violation message, the audit log entries also contain:
- An
audit_idfield that uniquely identifies a given audit run. This allows indexing of historical audits - An
event_typefield with a value ofviolation_auditedto make it easy to programmatically identify audit violations
Limitations of getting violations from audit logs:
- It could be difficult to parse audit pod logs to look for violation messages, as violation logs would be mixed together with other log statements.
Other Event Types
In addition to violations, these other audit events may be useful (all uniquely identified via the event_type field):
audit_startedmarks the beginning of a new audit runconstraint_auditedmarks when a constraint is done being audited for a given run, along with the number of violations foundaudit_finishedmarks the end of the current audit run
All of these events (including violation_audited) are marked
with the same audit_id for a given audit run.
Export violations
This feature allows different systems to be provided for Gatekeeper to export audit violations. Thereby, ensuring violations are not subject to reporting limits. Please refer to the export guide to configure audit to push violations via this feature.
Limitations/drawbacks of exporting violations:
- There is a risk of messages getting dropped. You might not receive all the exported violations. This depends on the type of backend you are using for delivery. For example, using a network as backend to export violation has the risk of messages getting dropped.
- Additional dependency on the backend system provided. For example, using pubsub tools to export violations.
Running Audit
Why Audit Runs as a Singleton
Gatekeeper audit is designed to run as a singleton because it writes audit results to Constraint status. Multiple audit instances can contend on the same Constraint status fields. In Gatekeeper v3.18 and later, the audit deployment may also run the generate operation, which creates or updates Constraint CRDs and, when VAP/VAPB generation is enabled, ValidatingAdmissionPolicy and ValidatingAdmissionPolicyBinding resources. The generate operation should also run as a singleton.
If your setup only consumes audit results from logs or exports, setting --constraint-violations-limit=0 avoids storing individual violations in Constraint .status.violations. This does not disable all Constraint status writes: audit still updates fields such as .status.auditTimestamp and .status.totalViolations, so running multiple audit replicas can still cause status update contention. If you scale the audit deployment beyond one replica, ensure that only one instance runs the generate operation, or disable it for the audit deployment, for example with Helm's audit.disableGenerateOperation=true. If VAP/VAPB generation is enabled, ensure it is handled by a singleton generator or disable it with defaultCreateVAPForTemplates=false and defaultCreateVAPBindingForConstraints=false (or the equivalent runtime flags).
For more details on how to deploy audit and number of instances to run, please refer to operations audit.
Configuring Audit
- Audit violations per constraint: set
--constraint-violations-limit=123(defaults to20). NOTE: This flag only impacts when gathering audit results using the constraint status model. If you want to export audit results via other means, please refer to the export guide. Both approaches for getting audit violations can be configured independently and work simultaneously without any interference. - Audit chunk size: set
--audit-chunk-size=400(defaults to500,0= infinite) Lower chunk size can reduce memory consumption of the auditingPodbut can increase the number requests to the Kubernetes API server. - Audit interval: set
--audit-interval=123(defaults to every60seconds). Disable periodic audits by setting--audit-interval=0;AuditTriggerrequests remain enabled. - Audit api server cache write to disk (Gatekeeper v3.7.0+): Starting from v3.7.0, by default, audit writes api server cache to the disk attached to the node. This reduces the memory consumption of the audit
pod. If there are concerns with high IOPS, then switch audit to write cache to a tmpfs ramdisk instead. NOTE: write to ramdisk will increase memory footprint of the auditpod.- helm install
--set audit.writeToRAMDisk=true - if not using helm, modify the deployment manifest to mount a ramdisk
- emptyDir:
medium: Memory
- helm install
By default, audit will request each resource from the Kubernetes API during each audit cycle. To rely on the audit informer cache instead, use the flag --audit-from-cache=true. Note that this requires replication of Kubernetes resources into the audit cache before they can be evaluated against the enforced policies. Refer to the Replicating data section for more information.
Disabling Audit
If you want to completely disable the audit process (for example, to reduce CPU or Memory usage), you must be careful not to break other singleton operations like CRD generation and status aggregation, which are also handled by the audit pod.
Instead of completely removing the audit deployment (e.g., by setting disableAudit: true in Helm), you should disable just the audit operation:
- In Helm, set
audit.disableAuditOperation: true. - If not using Helm, remove the
--operation=auditflag from the audit deployment manifest.
Audit using kinds specified in the constraints only
By default, Gatekeeper will audit all resources in the cluster. This operation can take some time depending on the number of resources.
If all of your constraints match against specific kinds (e.g. "match only pods"), then you can speed up audit runs by setting --audit-match-kind-only=true flag. This will only check resources of the kinds specified in all constraints defined in the cluster.
For example, defining this constraint will only audit Pod kind:
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sAllowedRepos
metadata:
name: prod-repo-is-openpolicyagent
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]
...
If any of the constraints do not specify kinds, it will be equivalent to not setting --audit-match-kind-only flag (false by default), and will fall back to auditing all resources in the cluster.
Opt-out of Audit in constraints
By default, all constraints are opted-in audit. To opt-out of the audit process at constraint, you can use enforcementAction: scoped and define scopedEnforcementActions without including audit enforcement point.
For example, defining this constraint will opt-out of audit
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sAllowedRepos
metadata:
name: prod-repo-is-openpolicyagent
spec:
...
enforcementAction: scoped
scopedEnforcementActions:
- action: warn
enforcementPoints:
- name: "validation.gatekeeper.sh"
- action: deny
enforcementPoints:
- name: "gator.gatekeeper.sh"
...
Find out more about different enforcement points in Gatekeeper.
Audit UserInfo
When using input.review.userInfo, NOTE the request's user's information, such as username, uid, groups, extra, cannot be populated by Kubernetes for audit reviews and therefore constraint templates that rely on userInfo are not auditable. It is up to the rego author to handle the case where userInfo is unset and empty in order to avoid every matching resource being reported as violating resources.