Uriel
Uriel

Reputation: 539

How to add different label to pods from a same DaemonSet link them in single pod service?

I want a created Service per pod to be used from a dynamically generated Ingress.

But for that, I need a way to differentiate pods instantiated by my DaemonSet.

I tried:

apiVersion: v1
kind: Service
metadata:
  name: my-service-node1
spec:
  selector:
    app: my-app
    kubernetes.io/hostname: "node1"
  ports:
    - protocol: TCP
      port: 80
      targetPort: 80

but kubernetes.io/hostname is only defined in node, I look for a way to forward this label, and I find this only Q/A.

Generating a random label for each DaemonSet should work too, but I think it is not possible too.

Using variables in my template/metadata/labels in my DaemonSet would be nice, but that does not exist too.

If I could refer a pod directly in my Ingress, that would fix my problem, but it look like an Ingress can only talk to a Service.

Upvotes: 0

Views: 1133

Answers (2)

Uriel
Uriel

Reputation: 539

I published a Docker image that takes care of this issue.

the image is here.

the code source is here

Check the doc on docker hub


update: A full usage sample is available here:

can be test with:

kubectrl apply -f https://raw.githubusercontent.com/UrielCh/dyn-ingress/main/demo.yml

Upvotes: 1

Harsh Manvar
Harsh Manvar

Reputation: 30083

Didn't get 100% of your problem however you can use the init container to add labels to service and POD

So whenever any POD is starting it will run the init container first get the necessary label from where you want to get it. After that it will add the label to POD and update the service also with same selector.

Command for patch

kubectl patch service <Service-name> -p '{"spec":{"selector":{"app": "new-app"}}}'

To update the service you can use the Patch method

apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: node2pod
spec:
  replicas: 1
  template:
    metadata:
      labels:
        name: node2pod
        app: node2pod
    spec:
      initContainers:
      - name: node2pod
        image: <IMAGE>
        command:
        - "sh"
        - "-c"
        - "kubectl -n ${NAMESPACE} label pods ${POD_NAME} vm/rack=$(kubectl get no -Lvm/rack | grep ${NODE_NAME} | awk '{print $6}')"
        - "kubectl patch service <Service-name> -p '{"spec":{"selector":{"app": "new-app"}}}'"
        env:
        - name: NODE_NAME
          valueFrom:
            fieldRef:
              fieldPath: spec.nodeName
        - name: NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        - name: POD_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
      containers:
      - name: nginx
        image: nginx

Upvotes: 1

Related Questions