核心命令行是
kubectl get pipelinerun -o jsonpath='{range .items[?(@.status.completionTime)]}{.status.completionTime}{" "}{.metadata.name}{"\n"}{end}' -n lizhe
使用cronjob
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: cleaner
namespace: lizhe
---
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: cleaner
namespace: lizhe
rules:
- apiGroups: ["tekton.dev"]
resources: ["pipelineruns"]
verbs: ["delete", "get", "watch", "list"]
---
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: cleaner-to-cleaner
namespace: lizhe
roleRef:
kind: Role
name: cleaner
apiGroup: rbac.authorization.k8s.io
subjects:
- kind: ServiceAccount
name: cleaner
---
apiVersion: batch/v1beta1
kind: CronJob
metadata:
name: cleanup-pipelineruns
namespace: lizhe
spec:
successfulJobsHistoryLimit: 5
failedJobsHistoryLimit: 5
schedule: "*/30 * * * *"
concurrencyPolicy: Forbid
jobTemplate:
spec:
template:
spec:
restartPolicy: OnFailure
serviceAccount: cleaner
containers:
- name: kubectl
image: libaibai/kubectl
env:
- name: NUM_TO_KEEP
value: "3"
command:
- /bin/bash
- -c
- |
TO_DELETE="$(kubectl get pipelinerun -o jsonpath='{range .items[?(@.status.completionTime)]}{.status.completionTime}{" "}{.metadata.name}{"\n"}{end}' -n lizhe | sort | head -n -${NUM_TO_KEEP} | awk '{ print $2}')"
test -n "$TO_DELETE" && kubectl delete pipelinerun ${TO_DELETE} || true
此脚本会
- 每30分钟运行一次
- 只清理已经完成的 (失败或者成功)的pod
- 保留历史记录3个
- job 本身保留历史记录5个
以上参数都是可以配置的
使用的镜像没有特殊要求,只要能提供 kubectl 就可以了,因为使用的是 RBAC 所以也不需要额外的 config
可以使用下面的镜像构建
FROM ubuntu
RUN apt update -y && apt install -y curl
WORKDIR /
RUN curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
RUN chmod 777 /kubectl
RUN cp /kubectl /usr/local/bin