Search code examples
javajsonportfabric8

How to get the nodePort using fabric8 java api for kubernetes?


I am creating a service in the following way

io.fabric8.kubernetes.api.model.Service myService = new ServiceBuilder()
        .withNewMetadata()
        .withName(svcName).addToLabels(svcLabelKey,svcLabelValue)
        .endMetadata()
        .withNewSpec().addToSelector(specSelectorKey, specSelectorValue).withType(svcType)
        .addNewPort()
        .withProtocol(protocol)
        .withPort(port)
        .endPort()
        .endSpec()
        .build();
        client.services().inNamespace(namespace).create(myService);
        return myService;

How do I get the nodePort it returns from this json?

  {
 "metadata": {
        "name": "my-svc",
        "namespace": "myns",
        "selfLink": "",
        "uid": "6cb0f222-7e57-11e5-96f2-005056976c6f",
        "resourceVersion": "1016121",
        "creationTimestamp": "2015-10-29T16:09:25Z",
        "labels": {
          "name": ""
        }
      },
      "spec": {
        "ports": [
          {
            "protocol": "TCP",
            "port": 80,
            "targetPort": 80,
            "nodePort": 20430
          }
        ],
        "selector": {
          "name": "p"
        },
        "clusterIP": "10.254.181.34",
        "type": "LoadBalancer",
        "sessionAffinity": "None"
      },
      "status": {
        "loadBalancer": {}
      }
    },

Are there examples to fetch teh nodeport after a service is created? I can get the service port but not the node port that is added later after creation


Solution

  • The nodePort is a property defined inside io.fabric8.kubernetes.api.model.ServicePort.

    You can obtain the service instance, like:

    Service srv = client.services().inNamespace(namespace).withName("myid").get();
    

    And then you can access the property like:

    Integer nodePort = srv.getSpec().getPorts().get(0).getNodePort();
    

    The code above, will get the nodePort of the first port defined for the service. (see get(0)). If you have more ports, you'll have to iterate and pick the port you want.

    I hope this helps.