How to list Hosts associated with Ingress

76 views Asked by At

We are using kubernetes java client , https://github.com/kubernetes-client/java

to get the information about resources from EKS cluster. below is the code we are using to list the ingress

ApiClient client = Config.defaultClient();
     Configuration.setDefaultApiClient(client); 

    NetworkingV1Api netapi = new NetworkingV1Api();
    V1IngressList list1 = netapi.listIngressForAllNamespaces(null, null, null, null, null, null, null, null, null, null, null);
    
    for (V1Ingress item : list1.getItems()) {
        System.out.println("ingress list" + item.getMetadata().getName());
    }

Similarly, is there any way OR method to get the list of hosts associated with the ingress ? I tried searching docs but could not get the info .

Any help / pointers please Thanks

1

There are 1 answers

0
Turing85 On BEST ANSWER

The Java API closely mirrors the actual resources definition. If we take a look at the resource definition of an ingress, we can figure it out:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: -registry-ui
  annotations:
    traefik.ingress.kubernetes.io/router.entrypoints: websecure
    traefik.ingress.kubernetes.io/router.tls: 'true'
spec:
  ingressClassName: traefik
  rules:
  - host: PLACEHOLDER
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: -registry-ui
            port:
              name: http

(Sample is taken from one of my github.com repos)

We are interested in the value(s) of the host field. The path to the resources thus is spec.rules.[].host. Notice that rules is an array. This will be translated to a List in the java client, meaning we will need to have some sort of iteration or reduction over all rules of an ingress.

Now, to translate this to java code, we simply call the corresponding getters:

for (V1Ingress item : list1.getItems()) {
    List<String> hosts = item.getSpec().getRules().stream()
            .map(V1IngressRule::getHost)
            .toList();
    System.out.println("Host list" + hosts);
}

If we want to get all hosts of all ingresses, we can achieve this through:

List<String> hosts = list1.stream()
    .map(V1Ingress::getSpec)
    .map(V1IngressSpec::getRules)
    .flatMap(List::stream)
    .map(V1IngressRule::getHost)
    .distinct() // if we want to remove duplicates
    .toList();