Kubernetes - Finding out how many replicas there are in a service?

1/10/2020

I have multiple replicas of a .net core C# console application grouped in a service. I would like to be able to be read inside each of the replicas the total number of them (after they get rescaled -> total number decreases or increases).

-- Oros Bogdan-Ioan
c#
kubernetes

1 Answer

1/10/2020

You need to query kubernetes api server to get the details of replicas from your application running inside a pod.

Authenticating with Kubernetes API server:

To query kubernetes api server which has RBAC enabled, you need to be authenticated and depending on the api endpoint that you are querying you also need required roles.

Every pod has a service account associated with it using which you can authenticate with the api-server. You need to create the following resources:

  • ServiceAccount and associate it with the pod. You can also use the default service account but it is better to create new service account so that you don't grant the extra roles to all the pods in the namespace.
  • Role which has privileges to get the number of replicas of deployment
  • RoleBinding to bind the Role to ServiceAccount.

Note: Depending on the type of resource you are trying to query, you might need ClusterRole and ClusterRoleBinding instead of Role and RoleBinding.

To associate the ServiceAccount with the pod, use spec.serviceAccountName field in the pod spec.

Kubernetes mounts the token associated with the service account inside every pod at /var/run/secrets/kubernetes.io/serviceaccount/token.

Querying Kubernetes API server:

  • You can install kubectl inside your application's docker image and call it from your code to query the api-server. kubectl can detect that it is being run from inside a pod and use the token automatically to authenticate with kubernetes api-server.

  • You can also use a kubernetes client library(https://github.com/kubernetes-client/csharp). In this case, you need to use InClusterConfig to use the service account token.

    var config = KubernetesClientConfiguration.InClusterConfig()
    var client = new Kubernetes(config);
-- Shashank V
Source: StackOverflow