# 第十四题 Audit
###### tags: `真题讲解`
切换集群kubectl config use-context k8s
**Task**
Enable audit logs in the cluster.To do so, enable the log backend, and ensure that:
* logs are stored at **/var/log/kubernetes/audit-logs.txt**
* log files are retained for **5 days**
* At maximum, a number of 10 auditlog files are retained
A basic policy is provided at /etc/kubernetes/logpolicy/sample-policy.yaml . it only specifies what not to log.
The base policy is located on the cluster's master node.
Edit and extend the basic policy to log:
* namespaces changes at RequestResponse level
* the request body of pods changes in the namespace **front-apps**
* configMap and secret changes in all namespaces at the Metadata level
Also, add a catch-all rule to log all other requests at the Metadata level.
Don't forget to apply the modified policy.
## 解法
考试时, 直接参考官方文档. [k8s.io/audit](https://v1-20.docs.kubernetes.io/docs/tasks/debug-application-cluster/audit/#audit-policy)
我在Miro上画的Audit逻辑图, 供理解参考

步骤1, 创建Audit Policy, 根据题意, 参考官网范例:
```
// 举例我的Audit Policy放在/etc/kubernetes/audit文件夹下, 具体位置审题
root@ubuk8s-vm01:/etc/kubernetes/audit# ls
audit_policy.yaml audit_policy.yaml.bak
```
根据题意我认为解法
```
vim audit_policy.yaml
apiVersion: audit.k8s.io/v1 # This is required.
kind: Policy
rules:
- level: RequestResponse
- level: Request
resources:
- group: ""
resources: ["pods"]
namespaces: ["front-apps"]
- level: Metadata
resources:
- group: "" # core API group
resources: ["configmaps","secrets"]
- level: Metadata
```
然后根据题意修改Kube-apiserver参数:

确保Audit Policy文件路径和Log输出位置已经正确的挂在在Kube-apiserver上.
**Tips: Log输出位置type: FileOrCreate, 挂在时readOnly: false, 在官网文档下方有范例**
```
- mountPath: /etc/kubernetes/audit/audit_policy.yaml
name: audit
readOnly: true
- mountPath: /var/log/kubernetes/audit-logs.txt
name: audit-log
readOnly: false
volumes:
- hostPath:
path: /etc/kubernetes/audit/audit_policy.yaml
type: File
name: audit
- hostPath:
path: /var/log/kubernetes/audit-logs.txt
type: FileOrCreate
name: audit-log
```
## 校验
1. 先确保Apiserver能够正常启动, 如果不能不要慌, 练习的时候参考[cks-exam-series-4-crash-that-apiserver](https://itnext.io/cks-exam-series-4-crash-that-apiserver-5f4d3d503028) 学习一下如果Debug
2. 在/var/log/kubernetes路径下找到audit-logs.txt (kubernetes这个文件夹如果没有, 则需要手工创建, 否则Apiserver启动失败因为无法挂载, audit-logs.txt不需要手工创建)
3. `tail -f audit-logs.txt | jq` 看到日志在持续输出就行了