How to delete another pod when based on lifeCycle of one pod

Viewed 317

I have a requirement to delete all pods for service1-deployment when container restart happens in service2-deployment.

I found out that we can do it through lifeCycle event handler service2-deployment.

But we can not specify kubeclt delete pod command here since it runs inside a pod. Is there any easy way to restart 2nd pod based on 1st Pod's lifeCycle events?

2 Answers

Disclaimer - as mentioned in the comments, you should avoid this solution (microservices should be independent) until you really have no other choice.


You can setup both postStart and preStop handlers (for installing kubectl binary and for deleting the pods from deployment), but first you need to create a proper Service Account for the pod and Role(Bindings) with permissions to delete pods:

apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: role-for-hook
subjects:
- kind: ServiceAccount
  name: service-account-for-hook
  namespace: default
roleRef:
  kind: ClusterRole
  name: delete-pods-role
  apiGroup: rbac.authorization.k8s.io
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: service-account-for-hook
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: delete-pods-role
  labels:
    # Add these permissions to the "view" default role.
    rbac.authorization.k8s.io/aggregate-to-view: "true"
rules:
- apiGroups: ["*"]
  resources: ["pods"]
  verbs: ["delete","list"]

Then, you can use newly created Service Account + postStart and preStop handlers in pod / deployment definition - example for NGINX image. I assumed, that the label for the pods from the Service1 is app=service1

apiVersion: apps/v1
kind: Deployment
metadata:
  name: service2-deployment
spec:
  selector:
    matchLabels:
      app: service2
  replicas: 2
  template:
    metadata:
      labels:
        app: service2
    spec:
      serviceAccountName: service-account-for-hook
      containers:
      - name: service2
        image: nginx:latest
        lifecycle:
          postStart:
            exec:
              command: ["/bin/sh", "-c", "apt update && apt install curl && curl -L https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl -o /usr/local/bin/kubectl && chmod +x /usr/local/bin/kubectl"] 
          preStop:
            exec:
              command: ["/bin/sh", "-c", "kubectl delete pods -l app=service1"]
        ports:
          - containerPort: 80

Then, if the pod from Service2 is restarted, the pods from Service1 are also restarted.

Commands used in the command: could be different for you, it depends which base image you are using for your application.

you can call rest API of api-server to delete pods of another deployment..

you can call your custom API after lifecycle event got executed something like this

Related