how to count num of diff clusters in k8s in kubeconfig file using shell?

1/23/2022

The file is this:

- name: development
  cluster:
    certificate-authority: /etc/kubernetes/pki/ca.crt
    server: https://controlplane:6443

- name: kubernetes-on-aws
  cluster:
    certificate-authority: /etc/kubernetes/pki/ca.crt
    server: https://controlplane:6443

- name: test-cluster-1
  cluster:
    certificate-authority: /etc/kubernetes/pki/ca.crt
    server: https://controlplane:6443

contexts:
- name: test-user@development
  context:
    cluster: development
    user: test-user

- name: aws-user@kubernetes-on-aws
  context:
    cluster: kubernetes-on-aws
    user: aws-user

- name: test-user@production
  context:
    cluster: production
    user: test-user

- name: research
  context:
    cluster: test-cluster-1
    user: dev-user

users:
- name: test-user
  user:
    client-certificate: /etc/kubernetes/pki/users/test-user/test-user.crt
    client-key: /etc/kubernetes/pki/users/test-user/test-user.key
- name: dev-user
  user:
    client-certificate: /etc/kubernetes/pki/users/dev-user/developer-user.crt
    client-key: /etc/kubernetes/pki/users/dev-user/dev-user.key
- name: aws-user
  user:
    client-certificate: /etc/kubernetes/pki/users/aws-user/aws-user.crt
    client-key: /etc/kubernetes/pki/users/aws-user/aws-user.key

current-context: test-user@development
preferences: {}

i dont want to count how many diff clusters there is. HOw to count it with shell cmd?

cat config.txt > grep 'cluster' wc -l

is not working

-- ERJAN
config
kubernetes

2 Answers

1/23/2022

You can use kubectl config view command with the help of -o jsonpath to list cluster names:

$  kubectl config view -o jsonpath='{.clusters[*].name}'
cluster-1 cluster-2 cluster-3

To count them:

$ kubectl config view -o jsonpath='{.clusters[*].name}' | wc -w
3

You can also prettify your output by using tr " " "\n" command which will replace white space with a newline.

$ kubectl config view -o jsonpath='{.clusters[*].name}' | tr " " "\n"
cluster-1
cluster-2
cluster-3
-- Kamol Hasan
Source: StackOverflow

1/24/2022

This one is simple

kubectl config get-contexts | grep -v NAME | wc -l
-- P Ekambaram
Source: StackOverflow