<p>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).</p>

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

<p><strong>Authenticating with Kubernetes API server</strong>:</p>

<p>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. </p>

<p>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:</p>

<ul>
<li><code>ServiceAccount</code> 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.</li>
<li><code>Role</code> which has privileges to <code>get</code> the number of replicas of deployment </li>
<li><code>RoleBinding</code> to bind the <code>Role</code> to <code>ServiceAccount</code>.</li>
</ul>

<p><em>Note</em>: Depending on the type of resource you are trying to query, you might need <code>ClusterRole</code> and <code>ClusterRoleBinding</code> instead of <code>Role</code> and <code>RoleBinding</code>.</p>

<p>To associate the ServiceAccount with the pod, use <code>spec.serviceAccountName</code> field in the pod spec. </p>

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

<p><strong>Querying Kubernetes API server</strong>:</p>

<ul>
<li><p>You can install <code>kubectl</code> inside your application's docker image and call it from your code to query the api-server. <code>kubectl</code> can detect that it is being run from inside a pod and use the token automatically to authenticate with kubernetes api-server.</p></li>
<li><p>You can also use a kubernetes client library(<a href="https://github.com/kubernetes-client/csharp" rel="nofollow noreferrer">https://github.com/kubernetes-client/csharp</a>). In this case, you need to use <code>InClusterConfig</code> to use the service account token. </p></li>
</ul>

<pre><code>    var config = KubernetesClientConfiguration.InClusterConfig()
    var client = new Kubernetes(config);
</code></pre>
