Enable Kubernetes audit log collection on a k3s cluster by creating the audit policy and webhook configuration files, configuring k3s to use them, and restarting the service.
Importantk3s runs
kube-apiserver as a host process before CoreDNS starts, so 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 /var/lib/rancher/k3s/server/audit sudo tee /var/lib/rancher/k3s/server/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 /var/lib/rancher/k3s/server/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 - Configure k3s to use the audit policy and webhook.Edit or create
/etc/rancher/k3s/config.yaml:kube-apiserver-arg: - "audit-policy-file=/var/lib/rancher/k3s/server/audit/audit-policy.yaml" - "audit-webhook-config-file=/var/lib/rancher/k3s/server/audit/audit-webhook-config.yaml" - "audit-webhook-batch-max-size=1"
- Restart k3s to apply the changes.
sudo systemctl daemon-reload sudo systemctl restart k3s
- Verify the configuration.
sudo systemctl status k3s sudo journalctl -u k3s | grep -i audit
