Assign ExternalIP of LoadBalancer to Deployment as ENV variable

12/10/2019

I have very specific case when my Pod should access to another LoadBalancer service via an ExternalIP.

Is there any way to assign LoadBalancer ExternalIP as an ENV variable to Deployment.yaml?

Thank you in advance!

-- user2738882
google-kubernetes-engine
kubernetes
kubernetes-helm

2 Answers

12/12/2019

I found the way how to do it but @David Maze was perfectly right - there is no straight way how to do it.

So, my solution to add DNS with public and private zones:

apiVersion: v1
kind: Service
metadata:
  name: nginx-lb
  labels:
    app.kubernetes.io/name: nginx-lb
  annotations:
    external-dns.alpha.kubernetes.io/hostname: mycoolservice.{{ .Values.dns_external_zone }}.
    external-dns.alpha.kubernetes.io/zone-type: public,private
    external-dns.alpha.kubernetes.io/ttl: "1"
spec:
  type: LoadBalancer
  ports:
    - name: https
      port: 443
      targetPort: https
    - name: http
      port: 80
      targetPort: http
  selector:
    app.kubernetes.io/name: nginx
-- user2738882
Source: StackOverflow

12/10/2019

I don't think this is directly possible in any of the standard templating tools. Part of the problem is that creating a cloud-hosted load balancer is an asynchronous operation, so that external-IP value won't be available until some time after kubectl apply (or the equivalent helm install) has finished.

If you can create the Service in advance then you can hard-code its external IP address or host name into other configuration, but this is intrinsically two steps. (If you're bought into Kubernetes operators, this should be possible with custom code: watch the Service, and once it gets its external address, create a corresponding ConfigMap that holds the address.)

Depending on your specific use case it may also work to just target the LoadBalancer Service within your cluster, the same as any other Service. This won't go out through the cloud provider's load-balancer tier, but it should be indistinguishable otherwise.

-- David Maze
Source: StackOverflow