如何使用kubectl命令获取集群ID [英] How to get cluster id using kubectl command
问题描述
我需要使用kubectl命令进行cluster-id.
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"
}
我需要此特定json的cluster-id
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
推荐答案
您的ConfigMap
资源data
-字段包含一个字符串,当您运行jsonpath
通过'{.data.cluster-config\.json}'
选择它时,它按原样解释.我的意思是,尽管它在Kubernetes中的存储方式不同,但您使用的shell仍将在stdout
处将其打印为JSON.如果运行kubectl get cm cluster-info -n kube-system -o json
并查看data
字段,则可能看起来像这样:
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"
}
您将无法使用jsonpath
访问该字符串中的字段",因为它实际上不是
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.
您可以尝试使用第二个工具来获取它,方法是使用 jq
,命令行JSON处理器.该工具会即时将jsonpath
的输出解释为JSON并进行相应的解析.
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.
示例:
kubectl get cm cluster-info -n kube-system -o jsonpath='{.data.cluster-config\.json}' | jq '.cluster_id'
"xxx"
如果要安装例如jq
击败任何目的,我建议您使用诸如grep
,awk
和sed
之类的已经可用的工具(假设您使用的是Linux)的组合:
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
这篇关于如何使用kubectl命令获取集群ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!