How to get cluster id using kubectl command

6/26/2018

I need cluster-id using kubectl command.

root@vagrant-xenial64:~# kubectl get cm cluster-info -n kube-system -o jsonpath='{.data.cluster-config\.json}'
{
  "cluster_id": "xxx",
  "cluster_name": "prod-yyy-mmm",
  "cluster_type": "rrr",
  "cluster_pay_tier": "vvv",
  "datacenter": "cse",
  "account_id": "456777",
  "created": "2018-06-32323dffdf:35:48+0000"
}

I need cluster-id of this particular json

root@vagrant-xenial64:~# kubectl get cm cluster-info -n kube-system -o jsonpath='{.data.cluster-config\.json.cluster_id}'
root@vagrant-xenial64:~# 

Above command returns empty string. I tried many other combinations too

-- ambikanair
jsonpath
kubectl
kubernetes

1 Answer

6/26/2018

Your ConfigMap resource data-field contains a string which are interpreted as-is when you run jsonpath to select it via '{.data.cluster-config\.json}'. What i mean is that the shell you use will print it as JSON at stdout although it's stored differently in Kubernetes. If you run kubectl get cm cluster-info -n kube-system -o json and look at the data-field it might look something like this:

"data": {
    "cluster-config.json": "{\n  \"cluster_id\": \"xxx\",\n  \"cluster_name\": \"prod-yyy-mmm\",\n  \"cluster_type\": \"rrr\",\n  \"cluster_pay_tier\": \"vvv\",\n  \"datacenter\": \"cse\",\n  \"account_id\": \"456777\",\n  \"created\": \"2018-06-32323dffdf:35:48+0000\"\n}\n"
}

You won't be able to access the "fields" within that string with jsonpath since it's not actually part of the ConfigMap API resource fields.

You could try to use a second tool to fetch it though, using jq, a command-line JSON processor. This tool would interpret the output of jsonpath as JSON on the fly and parse it accordingly.

Example:

kubectl get cm cluster-info -n kube-system -o jsonpath='{.data.cluster-config\.json}' | jq '.cluster_id'
"xxx"

If installing e.g. jq defeat any purposes i would recommend to use a combination of already available tools (assuming you're on Linux) like grep, awk and sed:

kubectl get cm cluster-info -n kube-system -o jsonpath='{.data.cluster-config\.json}' | grep cluster_id | awk '{ print $2 }' | sed -e 's/"//' -e 's/",//'
xxx
-- mikejoh
Source: StackOverflow