[英]Kubernetes delete pod job
I wanted to know is it possible to have a job in Kubernetes that will run every hour, and will delete certain pods. 我想知道在Kubernetes中是否有可能每小时运行一次并删除某些吊舱的工作。 I need this as a temporary stop gap to fix an issue. 我需要此作为暂时性的漏洞来解决问题。
Yes, it's possible. 是的,有可能。
I think the easiest way is just to call the Kubernernes API directly from a job. 我认为最简单的方法就是直接从作业中调用Kubernernes API。 Considering RBAC is configured, something like this: 考虑到已配置RBAC,如下所示:
apiVersion: batch/v1
kind: Job
metadata:
name: cleanup
spec:
serviceAccountName: service-account-that-has-access-to-api
template:
spec:
containers:
- name: cleanup
image: image-that-has-curl
command:
- curl
- -ik
- -X
- DELETE
- -H
- "Authorization: Bearer $(cat /var/run/secrets/kubernetes.io/serviceaccount/token)"
- https://kubernetes.default.svc.cluster.local/api/v1/namespaces/{namespace}/pods/{name}
restartPolicy: Never
backoffLimit: 4
You can also run a kubectl proxy sidecar to connect to the cluster using localhost
. 您也可以运行kubectl代理sidecar以使用localhost
连接到集群。 More information here 更多信息在这里
Or even running plain kubectl
in a pod is also an option: Kubernetes - How to run kubectl commands inside a container? 甚至在pod中运行普通的kubectl
也是一种选择: Kubernetes-如何在容器内运行kubectl命令?
Use a CronJob ( 1 , 2 ) to run the Job every hour. 使用一个cronjob( 1 , 2 )运行作业每隔一小时。
K8S API can be accessed from Pod ( 3 ) with proper permissions. 可以使用适当的权限从Pod( 3 )访问K8S API。 When a Pod is created a default ServiceAccount
is assigned to it ( 4 ) by default. 创建Pod时, default ServiceAccount
会为其分配default ServiceAccount
( 4 )。 The default ServiceAccount
has no RoleBinding and hence the default ServiceAccount
and also the Pod has no permissions to invoke the API. default ServiceAccount
没有RoleBinding,因此default ServiceAccount
和Pod没有调用API的权限。
If a role (with permissions) is created and mapped to the default ServiceAccount
, then all the Pods by default will get those permissions. 如果创建了一个角色(具有权限)并将其映射到default ServiceAccount
,则default ServiceAccount
,所有Pod都将获得这些权限。 So, it's better to create a new ServiceAccount instead of modifying the default ServiceAccount
. 因此,最好创建一个新的ServiceAccount,而不要修改default ServiceAccount
。
So, here are steps for RBAC ( 5 ) 因此,这是RBAC的步骤( 5 )
I know it's a bit confusing, but that's the way K8S works. 我知道这有点令人困惑,但这就是K8S的工作方式。
There is another workaround possibly. 可能还有另一种解决方法。
You could create a liveness probe (super easy if you have none already) that doesn't run until after one hour and always fail. 您可以创建一个活动探针 (如果还没有活动探针 ,则非常简单),直到一小时后才运行,并且总是失败。
livenessProbe:
tcpSocket:
port: 1234
initialDelaySeconds: 3600
This will wait 3600 seconds (1 hour) and then try to connect to port 1234 and if that fails it will kill the container (not the pod!). 这将等待3600秒(1小时),然后尝试连接到端口1234,如果失败,它将杀死容器(不是吊舱!)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.