I'm trying to get the address from the below result of my nslookup
Here I want to get is the 2nd address which is 10.0.45.45
Server: 10.152.183.10
Address: 10.152.183.10#53
Name: pg-master-0.pg-master-headless.postgres.svc.cluster.local
Address: 10.1.45.45
Here is my code
MASTER_HOST=$(nslookup pg-master-0.pg-master-headlesss | awk '/^Address:/ {A=$2}; END {print A}');
echo $MASTER_HOST
Unfortunately, my output is:
10.152.183.10#53
Here I'm logged into the pod then ran the nslookup that way.
If you want the 2nd "Address:" from the nslookup
output, you can simply do:
awk '/^Address/{n++; if (n==2){print $2; exit}}'
Which checks if the line begins with Address
, then increments a counter n++
and when n == 2
it outputs the second field and exits.
Example Use/Output
With your data in the file called nslookup.txt, you would receive the following:
$ awk '/^Address/{n++; if (n==2){print $2; exit}}' nslookup.txt
10.1.45.45
Of course, using nslookup
you would just pipe the output to awk
. For example, if I wanted the IP of the machine valkyrie on my local subnet, I would use:
$ nslookup valkyrie | awk '/^Address/{n++; if (n==2){print $2; exit}}'
192.168.6.135
Look things over and let me know if you have further questions.
It looks like nslookup
cannot resolve pg-master-0.pg-master-headlesss
. You might be running the operation from a different pod or from your personal server/machine which would have no idea of the services running in a cluster. (Your laptop doesn't use CoreDNS in your K8s cluster)
You can try running the script from the pod in your cluster and with the full FQDN to be safe:
$ kubectl run -i --tty --rm debug --image=ubuntu --restart=Never -- bash
#
# apt update; apt -y install dnsutils # Installs dnslookup ...
# export MASTER_HOST=$(nslookup pg-master-0.pg-master-headless.postgres.svc.cluster.local | awk '/^Address:/ {A=$2}; END {print A}'); echo $MASTER_HOST"