Data&Processing

kubernetes 에서 주기적 pod삭제

별이별이 2019. 11. 29. 00:20

deployments/statefulset 등으로 실행한 pod를 주기적으로 restart 시켜줄 필요가 있을때 사용합니다. kubernetes 내부 기능인 cronjob을 이용해서 pod 삭제 api를 주기적으로 호출해서 pod를 삭제합니다.

필요한기술

---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: monitor-serviceaccount
  namespace: monitor
  labels:
    app.kubernetes.io/name: monitor
    app.kubernetes.io/part-of: monitor
---
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRole
metadata:
  name: monitor-clusterrole
  labels:
    app.kubernetes.io/name: monitor
    app.kubernetes.io/part-of: monitor
rules:
  - apiGroups:
      - ""
    resources:
      - pods
    verbs:
      - list
      - watch
      - delete
      - deletecollection
  - apiGroups:
      - ""
    resources: ["pods", "replicationcontrollers","namespaces","deployments","services"]
    verbs: ["get", "watch", "list"]
  - apiGroups: ["apps"]
    resources: ["pods", "replicationcontrollers","namespaces","deployments","services"]
    verbs: ["get", "watch", "list"]
---
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRoleBinding
metadata:
  name: monitor-clusterrole-binding
  labels:
    app.kubernetes.io/name: monitor
    app.kubernetes.io/part-of: monitor
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: monitor-clusterrole
subjects:
  - kind: ServiceAccount
    name: monitor-serviceaccount
    namespace: monitor

 

 kubectl get secrets -o jsonpath="{.items[?(@.metadata.annotations['kubernetes\.io/service-account\.name']=='monitor-serviceaccount')].data.token}" -n monitor |base64 --decode

 

    • pod내부에서 다음과 같이 테스트해볼수 있습니다.
curl -ik -X GET -H "Authorization: Bearer "" https://kubernetes.default.svc.cluster.local/api/v1/namespaces/{namespaceName}/pods?labelSelector={tagKey}%3D{tagValue}

 

    • cronjob yaml을 다음과 같이 만들고 적용합니다.
apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: cleanup-cronjob
  namespace: monitor
  labels:
    app: cleanup-cronjob
spec:
  schedule: "min hour day * *"
  jobTemplate:
    spec:
      template:
        spec:
          serviceAccountName: monitor-serviceaccount
          restartPolicy: OnFailure
          containers:
          - name: cleanup
            image: radial/busyboxplus:curl
            args:
            - curl
            - -ik 
            - -X
            - DELETE
            - -H
            - "Authorization: Bearer {위에서 생성된 auth Key}"
            - https://kubernetes.default.svc.cluster.local/api/v1/namespaces/{namespace}/pods?labelSelector={metaKey}%3D{metaValue}