Can I set an environment variable for a container to the value of the clusterIP of a service in my cluster?

8/30/2019

I need to set an environment variable in my container to the IP address provided by a service that is already running in my cluster.

I had this working with the following:

spec:
  containers:
    - name: new_container
      image: my_image:latest
      env:
        - name: ENV_VAR
          value: k8s_service_name

I modified the spec to provide the container all host network traffic via:

spec:
  hostNetwork: true
  containers:
    - name: new_container
      image: my_image:latest
      env:
        - name: ENV_VAR
          value: k8s_service_name

However, the container no longer seems to understand what 'k8s_service_name' is, so I need to pass the actual IP value of that service.

The address I need is available in the container as K8S_SERVICE_NAME_SERVICE_HOST=255.255.255.255

But for the application to work I need to make ENV_VAR=255.255.255.255

The following did not work
value: $K8S_SERVICE_NAME_SERVICE_HOST
value: $K8S_SERVICE_NAME_SERVICE_HOST
value: $(K8S_SERVICE_NAME_SERVICE_HOST)
value: {{K8S_SERVICE_NAME_SERVICE_HOST}}
value: {{env.K8S_SERVICE_NAME_SERVICE_HOST}}

Expected:

>>> printenv | grep ENV_VAR
ENV_VAR=255.255.255.255

Actual Results:

>>> printenv | grep ENV_VAR
ENV_VAR=$K8S_SERVICE_NAME_SERVICE_HOST

or errors involving the value not converting from yaml to json properly.

A solution like below would be

valueFrom:
  fieldRef:
    fieldName: k8s_service_name.clusterIP
-- Chris A.
kubernetes

1 Answer

8/30/2019

Use: value: $(K8S_SERVICE_NAME_SERVICE_HOST)

To get the service ip. (use parenthesis)

-- Amityo
Source: StackOverflow