Documentation for Kubernetes v1.11 is no longer actively maintained. The version you are currently viewing is a static snapshot. For up-to-date documentation, see the latest version.

Edit This Page


FEATURE STATE: Kubernetes v1.11 beta
This feature is currently in a beta state, meaning:

  • The version names contain beta (e.g. v2beta3).
  • Code is well tested. Enabling the feature is considered safe. Enabled by default.
  • Support for the overall feature will not be dropped, though details may change.
  • The schema and/or semantics of objects may change in incompatible ways in a subsequent beta or stable release. When this happens, we will provide instructions for migrating to the next version. This may require deleting, editing, and re-creating API objects. The editing process may require some thought. This may require downtime for applications that rely on the feature.
  • Recommended for only non-business-critical uses because of potential for incompatible changes in subsequent releases. If you have multiple clusters that can be upgraded independently, you may be able to relax this restriction.
  • Please do try our beta features and give feedback on them! After they exit beta, it may not be practical for us to make more changes.

Kubernetes auditing provides a security-relevant chronological set of records documenting the sequence of activities that have affected system by individual users, administrators or other components of the system. It allows cluster administrator to answer the following questions:

Kube-apiserver performs auditing. Each request on each stage of its execution generates an event, which is then pre-processed according to a certain policy and written to a backend. The policy determines what’s recorded and the backends persist the records. The current backend implementations include logs files and webhooks.

Each request can be recorded with an associated “stage”. The known stages are:

Note The audit logging feature increases the memory consumption of the API server because some context required for auditing is stored for each request. Additionally, memory consumption depends on the audit logging configuration.

Audit Policy

Audit policy defines rules about what events should be recorded and what data they should include. The audit policy object structure is defined in the audit.k8s.io API group. When an event is processed, it’s compared against the list of rules in order. The first matching rule sets the “audit level” of the event. The known audit levels are:

You can pass a file with the policy to kube-apiserver using the --audit-policy-file flag. If the flag is omitted, no events are logged. Note that the rules field must be provided in the audit policy file. A policy with no (0) rules is treated as illegal.

Below is an example audit policy file:

audit-policy.yaml docs/tasks/debug-application-cluster
apiVersion: audit.k8s.io/v1beta1 # This is required.
kind: Policy
# Don't generate audit events for all requests in RequestReceived stage.
  - "RequestReceived"
  # Log pod changes at RequestResponse level
  - level: RequestResponse
    - group: ""
      # Resource "pods" doesn't match requests to any subresource of pods,
      # which is consistent with the RBAC policy.
      resources: ["pods"]
  # Log "pods/log", "pods/status" at Metadata level
  - level: Metadata
    - group: ""
      resources: ["pods/log", "pods/status"]

  # Don't log requests to a configmap called "controller-leader"
  - level: None
    - group: ""
      resources: ["configmaps"]
      resourceNames: ["controller-leader"]

  # Don't log watch requests by the "system:kube-proxy" on endpoints or services
  - level: None
    users: ["system:kube-proxy"]
    verbs: ["watch"]
    - group: "" # core API group
      resources: ["endpoints", "services"]

  # Don't log authenticated requests to certain non-resource URL paths.
  - level: None
    userGroups: ["system:authenticated"]
    - "/api*" # Wildcard matching.
    - "/version"

  # Log the request body of configmap changes in kube-system.
  - level: Request
    - group: "" # core API group
      resources: ["configmaps"]
    # This rule only applies to resources in the "kube-system" namespace.
    # The empty string "" can be used to select non-namespaced resources.
    namespaces: ["kube-system"]

  # Log configmap and secret changes in all other namespaces at the Metadata level.
  - level: Metadata
    - group: "" # core API group
      resources: ["secrets", "configmaps"]

  # Log all other resources in core and extensions at the Request level.
  - level: Request
    - group: "" # core API group
    - group: "extensions" # Version of group should NOT be included.

  # A catch-all rule to log all other requests at the Metadata level.
  - level: Metadata
    # Long-running requests like watches that fall under this rule will not
    # generate an audit event in RequestReceived.
      - "RequestReceived"

You can use a minimal audit policy file to log all requests at the Metadata level:

# Log all requests at the Metadata level.
apiVersion: audit.k8s.io/v1beta1
kind: Policy
- level: Metadata

The audit profile used by GCE should be used as reference by admins constructing their own audit profiles.

Audit backends

Audit backends persist audit events to an external storage. Kube-apiserver out of the box provides two backends:

In both cases, audit events structure is defined by the API in the audit.k8s.io API group. The current version of the API is v1beta1.

Note: In case of patches, request body is a JSON array with patch operations, not a JSON object with an appropriate Kubernetes API object. For example, the following request body is a valid patch request to /apis/batch/v1/namespaces/some-namespace/jobs/some-job-name.

    "op": "replace",
    "path": "/spec/parallelism",
    "value": 0
    "op": "remove",
    "path": "/spec/template/spec/containers/0/terminationMessagePolicy"

Log backend

Log backend writes audit events to a file in JSON format. You can configure log audit backend using the following kube-apiserver flags:

Webhook backend

Webhook backend sends audit events to a remote API, which is assumed to be the same API as kube-apiserver exposes. You can configure webhook audit backend using the following kube-apiserver flags:

The webhook config file uses the kubeconfig format to specify the remote address of the service and credentials used to connect to it.


Both log and webhook backends support batching. Using webhook as an example, here’s the list of available flags. To get the same flag for log backend, replace webhook with log in the flag name. By default, batching is enabled in webhook and disabled in log. Similarly, by default throttling is enabled in webhook and disabled in log.

The following flags are used only in the batch mode.

Parameter tuning

Parameters should be set to accommodate the load on the apiserver.

For example, if kube-apiserver receives 100 requests each second, and each request is audited only on ResponseStarted and ResponseComplete stages, you should account for ~200 audit events being generated each second. Assuming that there are up to 100 events in a batch, you should set throttling level at least 2 QPS. Assuming that the backend can take up to 5 seconds to write events, you should set the buffer size to hold up to 5 seconds of events, i.e. 10 batches, i.e. 1000 events.

In most cases however, the default parameters should be sufficient and you don’t have to worry about setting them manually. You can look at the following Prometheus metrics exposed by kube-apiserver and in the logs to monitor the state of the auditing subsystem.

Multi-cluster setup

If you’re extending the Kubernetes API with the aggregation layer, you can also set up audit logging for the aggregated apiserver. To do this, pass the configuration options in the same format as described above to the aggregated apiserver and set up the log ingesting pipeline to pick up audit logs. Different apiservers can have different audit configurations and different audit policies.

Log Collector Examples

Use fluentd to collect and distribute audit events from log file

Fluentd is an open source data collector for unified logging layer. In this example, we will use fluentd to split audit events by different namespaces.

  1. install fluentd, fluent-plugin-forest and fluent-plugin-rewrite-tag-filter in the kube-apiserver node
  2. create a config file for fluentd
   $ cat <<EOF > /etc/fluentd/config
   # fluentd conf runs in the same host with kube-apiserver
       @type tail
       # audit log path of kube-apiserver
       path /var/log/audit
       pos_file /var/log/audit.pos
       format json
       time_key time
       time_format %Y-%m-%dT%H:%M:%S.%N%z
       tag audit

   <filter audit>
       type record_transformer
        namespace ${record["objectRef"].nil? ? "none":(record["objectRef"]["namespace"].nil? ?  "none":record["objectRef"]["namespace"])}

   <match audit>
       # route audit according to namespace element in context
       @type rewrite_tag_filter
       rewriterule1 namespace ^(.+) ${tag}.$1

   <filter audit.**>
      @type record_transformer
      remove_keys namespace

   <match audit.**>
       @type forest
       subtype file
       remove_prefix audit
           time_slice_format %Y%m%d%H
           compress gz
           path /var/log/audit-${tag}.*.log
           format json
           include_time_key true
  1. start fluentd
   $ fluentd -c /etc/fluentd/config  -vv
  1. start kube-apiserver with the following options:
   --audit-policy-file=/etc/kubernetes/audit-policy.yaml --audit-log-path=/var/log/kube-audit --audit-log-format=json
  1. check audits for different namespaces in /var/log/audit-*.log

Use logstash to collect and distribute audit events from webhook backend

Logstash is an open source, server-side data processing tool. In this example, we will use logstash to collect audit events from webhook backend, and save events of different users into different files.

  1. install logstash
  2. create config file for logstash
   $ cat <<EOF > /etc/logstash/config
           #TODO, figure out a way to use kubeconfig file to authenticate to logstash
           # Webhook audit backend sends several events together with EventList
           # split each event here.
           # We only need event subelement, remove others.
           remove_field=>[headers, metadata, apiVersion, "@timestamp", kind, "@version", host]
           rename => {items=>event}
           # Audit events from different users will be saved into different files.
  1. start logstash
   $ bin/logstash -f /etc/logstash/config --path.settings /etc/logstash/
  1. create a kubeconfig file for kube-apiserver webhook audit backend
   $ cat <<EOF > /etc/kubernetes/audit-webhook-kubeconfig
   apiVersion: v1
   - cluster:
       server: http://<ip_of_logstash>:8888
     name: logstash
   - context:
       cluster: logstash
       user: ""
     name: default-context
   current-context: default-context
   kind: Config
   preferences: {}
   users: []
  1. start kube-apiserver with the following options:
   --audit-policy-file=/etc/kubernetes/audit-policy.yaml --audit-webhook-config-file=/etc/kubernetes/audit-webhook-kubeconfig
  1. check audits in logstash node’s directories /var/log/kube-audit-*/audit

Note that in addition to file output plugin, logstash has a variety of outputs that let users route data where they want. For example, users can emit audit events to elasticsearch plugin which supports full-text search and analytics.

Legacy Audit

Note: Legacy Audit is deprecated and is disabled by default since 1.8 and will be removed in 1.12. To fallback to this legacy audit, disable the advanced auditing feature using the AdvancedAuditing feature gate in kube-apiserver:


In legacy format, each audit log entry contains two lines:

  1. The request line containing a unique ID to match the response and request metadata, such as the source IP, requesting user, impersonation information, resource being requested, etc.
  2. The response line containing a unique ID matching the request line and the response code.

Example output for admin user listing pods in the default namespace:

2017-03-21T03:57:09.106841886-04:00 AUDIT: id="c939d2a7-1c37-4ef1-b2f7-4ba9b1e43b53" ip="" method="GET" user="admin" groups="\"system:masters\",\"system:authenticated\"" as="<self>" asgroups="<lookup>" namespace="default" uri="/api/v1/namespaces/default/pods"
2017-03-21T03:57:09.108403639-04:00 AUDIT: id="c939d2a7-1c37-4ef1-b2f7-4ba9b1e43b53" response="200"


Kube-apiserver provides the following options which are responsible for configuring where and how audit logs are handled:

If an audit log file already exists, Kubernetes appends new audit logs to that file. Otherwise, Kubernetes creates an audit log file at the location you specified in audit-log-path. If the audit log file exceeds the size you specify in audit-log-maxsize, Kubernetes will rename the current log file by appending the current timestamp on the file name (before the file extension) and create a new audit log file. Kubernetes may delete old log files when creating a new log file; you can configure how many files are retained and how old they can be by specifying the audit-log-maxbackup and audit-log-maxage options.


Create an Issue Edit this Page