Changing the /etc/hosts on every Kubernetes pod with a label by Fabian Bull on February 24, 2019

I once was tasked to setup a SaaS application in Kubernetes (short K8S). Everything went smoothly until I found out that some pod, spawned by the application, had to have their /etc/hosts/ file adjusted.

So this is what I did

I created a hosts file in my home directory containing the lines I wanted to add. Than I run:

kubectl exec <podName> -- sh -c "echo '$(cat ~/hosts )' >> /etc/hosts"; 

The command executes an echo on the pod and appends to output to /etc/hosts. The tricky part is, what gets echoed. Before executing the shell, on your computer, replaces $(catĀ·~/hostsĀ·)'with the actual content of ~/hosts. This feature of a shell is called Command Substitution and is available in both Bash and Zsh.

Look ma no hands

If you want to run this on all pods labeled foo=bar, you can use shell for loops:

for podName in $(kubectl get pods -l foo=bar -o name | sed 's/pod\///'); do
  kubectl exec $podName -- sh -c "echo '$(cat ~/hosts )' >> /etc/hosts"; 
done

Disclaimer

Do not do these things in production. This tip is useful while testing and debugging but setting up your production environment should be completely automated.