Kubernetes automation., output scripting with templates (IP addresses)

Many a times, we like to automate the Kubernetes outputs in a way that they can be consumed in a bash script or alike. I had a couple of interesting use-cases wherein I had to retrieve the External IP and Internal IP of a large cluster.

Doing this manually was a brutal exercise and had to be automated. Luckily, Kubernetes allows for output filtering., however it took me a while to scavenge through multiple examples in tits-&-bits to come up for specific automation commands.

Ensure that you have your kubectl config context set to the correct cluster

The below automation would emit a space separated text of IP addresses based on the use-case. Try it out!

Case-1 Get External IP addresses of master node

kubectl get nodes --selector='node-role.kubernetes.io/master' \
-o template \
--template='{{range.items}}{{range.status.addresses}}{{if eq .type "ExternalIP"}}{{.address}}{{end}}{{end}} {{end}}'

Case-2 Get External IP addresses of worker nodes

kubectl get nodes --selector='!node-role.kubernetes.io/master' \
-o template \
--template='{{range.items}}{{range.status.addresses}}{{if eq .type "ExternalIP"}}{{.address}}{{end}}{{end}} {{end}}'

Case-3 Get Internal IP addresses of master nodes

kubectl get nodes --selector='node-role.kubernetes.io/master' \
-o template \
--template='{{range.items}}{{range.status.addresses}}{{if eq .type "InternalIP"}}{{.address}}{{end}}{{end}} {{end}}'

Case-4 Get Internal IP addresses of worker nodes

kubectl get nodes --selector='!node-role.kubernetes.io/master' \
-o template \
--template='{{range.items}}{{range.status.addresses}}{{if eq .type "InternalIP"}}{{.address}}{{end}}{{end}} {{end}}'

Hope the above is helpful for anyone who is automating their Kubernetes outputs

cheers

Ambar@thecloudgarage

--

--

24+ years of blended experience of technology & people leadership, startup management and disruptive acceleration/adoption of next-gen technologies

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ambar Hassani

24+ years of blended experience of technology & people leadership, startup management and disruptive acceleration/adoption of next-gen technologies