我需要設定一個 kubernetes pod 來為我的 Web 應用程式的客戶端創建演示環境,試用期為 20 天。這20天后,pod應該會自動洗掉,我怎樣才能讓pod在20天后自毀?我使用 Rancher 來部署我的 Pod。
uj5u.com熱心網友回復:
您可以使用兩種方式實作此目的,撰寫自己的代碼并在 K8s 上運行以檢查狀態,這將在 20 天后洗掉部署 (POD)
參考github:https ://github.com/dignajar/clean-pods
您的 pod 沒有自動洗掉的選項。
您可以每隔20天運行一次cronjob ,這將洗掉特定的部署,但在這種情況下,您必須再次傳遞部署或 pod名稱,以便 cronjob 具有該變數。
示例:1
使用delete_namespaced_pod
from kubernetes import client, config
from kubernetes.client.rest import ApiException
config.load_incluster_config() # if running inside k8s cluster config.load_kube_config()
configuration = client.Configuration()
with client.ApiClient(configuration) as api_client:
api_instance = client.CoreV1Api(api_client)
namespace = '<Namespace name>'
name = '<POD name>'
api_instance.list_namespaced_pod(namespace)
try:
api_response = api_instance.delete_namespaced_pod(name, namespace)
print(api_response)
except ApiException as e:
print("Exception when calling CoreV1Api->delete_namespaced_pod: %s\n" % e)
示例:2
定時任務
apiVersion: batch/v1beta1
kind: CronJob
metadata:
name: cleanup
spec:
schedule: "30 1 1,20 * *"
jobTemplate:
spec:
template:
spec:
containers:
- name: kubectl-container
image: bitnami/kubectl:latest
command: ["sh", "-c", "kubectl delete pod <POD name or add variable here>"]
restartPolicy: Never
額外的
您還可以撰寫shell 腳本,每天運行一些命令來檢查POD的AGE,如果等于20天則洗掉
kubectl get pods --field-selector=status.phase=Pending --sort-by=.metadata.creationTimestamp | awk 'match($5,/[20-9]d|[0-9][0-9]d|[0-9][0-9][0-9]d/) {print $0}'
更新
如果您遇到任何禁止錯誤,請創建服務帳戶并將其與 cronjob 一起使用
apiVersion: v1
kind: ServiceAccount
metadata:
name: sa-name
namespace: default
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
namespace: default
name: sa-role
rules:
- apiGroups: ["*"]
resources: ["*"]
verbs: ["list", "delete"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: sa-rolebinding
namespace: default
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: sa-role
subjects:
- kind: ServiceAccount
name: sa-name
namespace: default
---
apiVersion: batch/v1beta1
kind: CronJob
metadata:
name: jobs
spec:
schedule: "*/30 * * * *"
jobTemplate:
spec:
template:
spec:
serviceAccountName: sa-role
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/425771.html
標籤:Kubernetes Kubernetes-pod 牧场主 演示
下一篇:驗證資料時出錯:[ValidationError(CronJob.spec.jobTemplate.spec.template.spec):io.k8s.api.core.v1.PodSpec中的未知
