Search code examples
kubernetesnsq

Kubernetes get endpoints


I have a set of pods providing nsqlookupd service. Now I need each nsqd container to have a list of nsqlookupd servers to connect to (while service will point to different every time) simultaneously. Something similar I get with

kubectl describe service nsqlookupd
...
Endpoints: ....

but I want to have it in a variable within my deployment definition or somehow from within nsqd container


Solution

  • Sounds like you would need an extra service running either in your nsqd container or in a separate container in the same pod. The role of that service would be to pole the API regularly in order to fetch the list of endpoints.

    Assuming that you enabled Service Accounts (enabled by default), here is a proof of concept on the shell using curl and jq from inside a pod:

    # Read token and CA cert from Service Account
    CACERT="/var/run/secrets/kubernetes.io/serviceaccount/ca.crt"
    TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)
    
    # Replace the namespace ("kube-system") and service name ("kube-dns")
    ENDPOINTS=$(curl -s --cacert "$CACERT" -H "Authorization: Bearer $TOKEN" \
        https://kubernetes.default.svc/api/v1/namespaces/kube-system/endpoints/kube-dns \
    )
    
    # Filter the JSON output
    echo "$ENDPOINTS" | jq -r .subsets[].addresses[].ip
    # output:
    #   10.100.42.3
    #   10.100.67.3
    

    Take a look at the source code of Kube2sky for a good implementation of that kind of service in Go.