问题
I'd like to create a Job to kill the following pod every single minute or any time when is created.
My testing pod is:
apiVersion: v1
kind: Pod
metadata:
name: myapp-pod
labels:
app: myapp
spec:
containers:
- name: myapp-container
image: busybox
command: ['sh', '-c', 'echo Hello && sleep 3600']
Is it possible to do that?
回答1:
Yes, you can delete the pods with kubectl within the cluster. First, you need to create a set of RBAC(Role-based access control) object. Here is the sample.
apiVersion: v1
kind: ServiceAccount
metadata:
name: test # this is service account for binding the pod
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: test # This defines a role and what API it can access
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["delete", "get", "list"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: test # This will bind the role and service account
subjects:
- kind: ServiceAccount
name: test
roleRef:
kind: Role
name: test
apiGroup: rbac.authorization.k8s.io
These objects will define a proper RABC rule so that the pod created can interact with Kubernetes's corresponding API. Then, you can define your Job with a Cronjob type like this.
apiVersion: batch/v1beta1
kind: CronJob
metadata:
name: kill-pod
spec:
schedule: "*/1 * * * *"
jobTemplate:
spec:
template:
spec:
serviceAccountName: test
containers:
- name: kill-pod
image: bitnami/kubectl:latest
command:
- kubectl
args:
- delete
- pod
- sth
restartPolicy: OnFailure
来源:https://stackoverflow.com/questions/60697650/kubernetes-job-to-delete-a-single-pod-every-minute