Enable Kubernetes audit log collection on a kubeadm cluster by creating the audit policy and webhook configuration files, editing the kube-apiserver static pod manifest, and waiting for kubelet to restart the pod.
Importantkubeadm clusters run
kube-apiserver as a static pod managed by kubelet. Because kube-apiserver starts before CoreDNS is available, it cannot resolve Kubernetes service DNS names.
The audit collector must use hostNetwork: true and connect through 127.0.0.1. |
Procedure
- Create the audit configuration directory and files.Run the following commands to create the audit policy and webhook configuration:
sudo mkdir -p /etc/kubernetes/audit sudo tee /etc/kubernetes/audit/audit-policy.yaml << 'EOF' apiVersion: audit.k8s.io/v1 kind: Policy rules: - level: Metadata verbs: ["create"] resources: - group: "authorization.k8s.io" resources: ["subjectaccessreviews", "selfsubjectaccessreviews", "localsubjectaccessreviews"] - level: RequestResponse verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] resources: - group: "rbac.authorization.k8s.io" resources: ["roles", "rolebindings", "clusterroles", "clusterrolebindings"] - level: Metadata verbs: ["create", "update", "delete"] resources: - group: "" resources: ["serviceaccounts"] - level: None EOF sudo tee /etc/kubernetes/audit/audit-webhook-config.yaml << 'EOF' apiVersion: v1 kind: Config clusters: - name: audit-collector cluster: server: http://127.0.0.1:8030/k8s-audit contexts: - context: cluster: audit-collector user: "" name: default-context current-context: default-context preferences: {} users: [] EOF - Edit the kube-apiserver static pod manifest on each control plane node.Edit
/etc/kubernetes/manifests/kube-apiserver.yaml.- Add the following flags to
spec.containers[0].command:- --audit-policy-file=/etc/kubernetes/audit/audit-policy.yaml - --audit-webhook-config-file=/etc/kubernetes/audit/audit-webhook-config.yaml - --audit-webhook-batch-max-size=1 - Add a volume mount to
spec.containers[0].volumeMounts:- mountPath: /etc/kubernetes/audit name: audit-config readOnly: true - Add a volume to
spec.volumes:- hostPath: path: /etc/kubernetes/audit type: DirectoryOrCreate name: audit-config
- Add the following flags to
- Wait for the automatic restart.kubelet watches
/etc/kubernetes/manifests/and automatically restarts the kube-apiserver pod when you save the manifest. No manual restart is needed.
Note
It might take up to a minute for kubelet to detect the change and restart the pod. During restart, the API server will be briefly unavailable. - Verify the configuration.
# Check kube-apiserver is running kubectl get pods -n kube-system -l component=kube-apiserver # Confirm audit flags are applied kubectl get pod -n kube-system -l component=kube-apiserver -o yaml | grep -E "audit-policy|audit-webhook" # Check audit collector logs kubectl logs -n trendmicro-system -l app.kubernetes.io/component=trendmicro-audit-log-collector --tail=20
