kubernetesnetwork-programmingamazon-eksdigkube-dns

How to get list of pods hostnames from headless service?


I have a stateful set for MongoDB replication where I need all the hostnames of pods through the service endpoint. I am able to fetch the names but not exactly the only list of hostnames.

$ dig srv mongodb +search +short
0 100 27017 mongodb-0.mongodb.pilot-bots.svc.cluster.local.

Here I'm getting extra content 0 100 27017 whichI want to exclude.

How can I get only names? like IPS below.

$ dig mongodb A +search +short
172.1.0.220


Solution

  • @anemyte provided a valid solution with his awk:

    dig srv mongodb +search +short | awk '{print $4}'
    

    However, you could also approach this from a different way. Dig has several options that can be adjusted in order to print only the info you desire as an output. This guide explains this approach in more detail:

    Get a not-quite-so-short answer?

    Note that a short answer is different from only an answer. The way to get a detailed answer, but without any auxiliary information, is to turn off all the results (+noall) and then turn on only those sections you want.

    Here’s a short answer followed by only an answer; the latter includes all the configuration information, including time-to-live (TTL) data, displayed in a format compatible with BIND configuration files.

    Using +noall followed by other option of your choosing will result in showing only those records that interest you. You can also just hide the records you don't want to print, for example, hide the TTL by using +nottlid option.