Kubernetes: Writing hostname to a file
Over the weekend I spent a bit of time playing around with Kubernetes and to get the hang of the technology I set myself the task of writing the hostname of the machine to a file.
I’m using the excellent minikube tool to create a local Kubernetes cluster for my experiments so the first step is to spin that up:
$ minikube start
Starting local Kubernetes cluster...
Kubectl is now configured to use the cluster.
The first thing I needed to work out how to get the hostname. I figured there was probably an environment variable that I could access. We can call the env command to see a list of all the environment variables in a container so I created a pod template that would show me that information:
hostname_super_simple.yaml
apiVersion: v1
kind: Pod
metadata:
name: mark-super-simple-test-pod
spec:
containers:
- name: test-container
image: gcr.io/google_containers/busybox:1.24
command: [ "/bin/sh", "-c", "env" ]
dnsPolicy: Default
restartPolicy: Never
I then created a pod from that template and checked the logs of that pod:
$ kubectl create -f hostname_super_simple.yaml
pod "mark-super-simple-test-pod" created
$ kubectl logs mark-super-simple-test-pod
KUBERNETES_SERVICE_PORT=443
KUBERNETES_PORT=tcp://10.0.0.1:443
HOSTNAME=mark-super-simple-test-pod
SHLVL=1
HOME=/root
KUBERNETES_PORT_443_TCP_ADDR=10.0.0.1
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
KUBERNETES_PORT_443_TCP_PORT=443
KUBERNETES_PORT_443_TCP_PROTO=tcp
KUBERNETES_SERVICE_PORT_HTTPS=443
KUBERNETES_PORT_443_TCP=tcp://10.0.0.1:443
PWD=/
KUBERNETES_SERVICE_HOST=10.0.0.1
The information we need is in $HOSTNAME so the next thing we need to do is created a pod template which puts that into a file.
hostname_simple.yaml
apiVersion: v1
kind: Pod
metadata:
name: mark-test-pod
spec:
containers:
- name: test-container
image: gcr.io/google_containers/busybox:1.24
command: [ "/bin/sh", "-c", "echo $HOSTNAME > /tmp/bar; cat /tmp/bar" ]
dnsPolicy: Default
restartPolicy: Never
We can create a pod using this template by running the following command:
$ kubectl create -f hostname_simple.yaml
pod "mark-test-pod" created
Now let’s check the logs of the instance to see whether our script worked:
$ kubectl logs mark-test-pod
mark-test-pod
Indeed it did, good times!
About the author
I'm currently working on short form content at ClickHouse. I publish short 5 minute videos showing how to solve data problems on YouTube @LearnDataWithMark. I previously worked on graph analytics at Neo4j, where I also co-authored the O'Reilly Graph Algorithms Book with Amy Hodler.