combinatorial
combinatorial

Reputation: 9561

How to get Kubernetes service IP inside a pod definition

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?

Upvotes: 0

Views: 707

Answers (2)

creztoe
creztoe

Reputation: 11

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

- name: VARIABLE_NAME
  value: $(MYSERVICE_SERVICE_HOST)

Upvotes: 1

Robert Bailey
Robert Bailey

Reputation: 18230

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.

Upvotes: 2

Related Questions