Use jq to get the external IP of Kubernetes Nodes

Following a brief Twitter conversation with Alexandre González, one of the organisers of the excellent Golang UK Conference, who asked if there was a better way of finding the External IP of a Kubernetes Node instead of using

1
kubectl get nodes -o json | grep ExternalIP -A1 | tail -n1|cut -d: -f2 | tr "\"" " " | tr -d '[[:space:]]'

I figured jq should be be suitable, to quote the author of jq

jq is like sed for JSON data - you can use it to slice and filter and map and transform structured data with the same ease that sed, awk, grep and friends let you play with text.

Here’s how you can use jq to obtain the External IP of one or many Kubernetes Node(s).

1
kubectl get nodes -o json | jq '.items[] | .status .addresses[] | select(.type=="ExternalIP") | .address'

Alex subsequently found a neater way of doing it using the built-in template functionality - which I much prefer.

1
kubectl get nodes -o template --template='{{range.items}}{{range.status.addresses}}{{if eq .type "ExternalIP"}}{{.address}}{{end}}{{end}} {{end}}'

Neat.

This post was tagged with:
← Back