如何使用kubectl命令获取集群ID

时间:2018-06-26 10:03:04

标签: kubernetes jsonpath kubectl

我需要使用kubectl命令进行cluster-id。

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"
}

我需要cluster-id的特定json

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

以上命令返回空字符串。 我也尝试了许多其他组合

1 个答案:

答案 0 :(得分:2)

您的ConfigMap资源data字段包含一个字符串,当您运行jsonpath通过'{.data.cluster-config\.json}'选择它时,它按原样解释。我的意思是,尽管它在Kubernetes中的存储方式不同,但您使用的shell仍将在stdout上将其打印为JSON。如果您运行kubectl get cm cluster-info -n kube-system -o json并查看data字段,则可能看起来像这样:

"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访问该字符串中的“字段”,因为它实际上不是ConfigMap API resource字段的一部分。

您可以尝试通过命令行JSON处理器jq使用第二个工具来获取它。该工具会即时将jsonpath的输出解释为JSON并进行相应的解析。

示例:

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

如果要安装例如jq会达到任何目的,我建议您使用grepawksed等已经可用的工具(假设您使用的是Linux)组合:

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