How to get Kubernetes service IP inside a pod definition

4/14/2016

Using Kubernetes 1.2.1 with Google Cloud. I have a service defined and running. I want to start a pod that gets the cluster IP address for the service. So that I can pass this IP through to a script that runs when the container starts.

From what I have read I can use the form MYSERVICE_SERVICE_HOST where MYSERVICE is the name of the service. Here is the Pod definition:

apiVersion: v1
kind: Pod
metadata:
  labels:
    name: mypod
  name: mypod
spec:
  containers:
    - name: mypod
      image: myimage
      env:
        - name: VARIABLE_NAME
          value: MYSERVICE_SERVICE_HOST

The script for the image runs this...

echo "Variable: $VARIABLE_NAME"

when I run kubectl logs mypod I see...

Variable: MYSERVICE_SERVICE_HOST

What am I doing wrong?

-- combinatorial
google-cloud-platform
kubernetes

2 Answers

4/14/2016

Your script is working correctly. In your pod yaml you are setting the environment variable VARIABLE_NAME to MYSERVICE_SERVICE_HOST and your script is printing out the value you specified. If you change your script to echo "MYSERVICE_SERVICE_HOST: $MYSERVICE_SERVICE_HOST" it should print out the IP that you are looking for.

-- Robert Bailey
Source: StackOverflow

3/25/2019

You just need to wrap the K8 env var name in $()

- name: VARIABLE_NAME
  value: $(MYSERVICE_SERVICE_HOST)
-- creztoe
Source: StackOverflow